@runtypelabs/persona 4.21.1 → 4.22.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.
- package/dist/{approval-ui-RNNBR5R3.js → approval-ui-K7R5Q5OC.js} +1 -1
- package/dist/approval-ui.cjs +2 -2
- package/dist/approval-ui.d.cts +73 -2
- package/dist/approval-ui.d.ts +73 -2
- package/dist/approval-ui.js +2 -2
- package/dist/artifacts-ui-F4N6VMKF.js +7 -0
- package/dist/artifacts-ui.cjs +1 -1
- package/dist/artifacts-ui.d.cts +73 -2
- package/dist/artifacts-ui.d.ts +73 -2
- package/dist/artifacts-ui.js +1 -1
- package/dist/chunk-NQLDCJAP.js +4 -0
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +73 -2
- package/dist/context-mentions.d.ts +73 -2
- package/dist/event-stream-view-FKWDY3UB.js +1 -0
- package/dist/event-stream-view.cjs +1 -1
- package/dist/event-stream-view.d.cts +73 -2
- package/dist/event-stream-view.d.ts +73 -2
- package/dist/event-stream-view.js +1 -1
- package/dist/forms-ui.d.cts +73 -2
- package/dist/forms-ui.d.ts +73 -2
- package/dist/index.cjs +63 -63
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +136 -5
- package/dist/index.d.ts +136 -5
- package/dist/index.global.js +48 -48
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +64 -64
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/session-reconnect.d.cts +73 -2
- package/dist/session-reconnect.d.ts +73 -2
- package/dist/smart-dom-reader.d.cts +73 -2
- package/dist/smart-dom-reader.d.ts +73 -2
- package/dist/theme-editor-preview.cjs +64 -64
- package/dist/theme-editor-preview.d.cts +73 -2
- package/dist/theme-editor-preview.d.ts +73 -2
- package/dist/theme-editor-preview.js +45 -45
- package/dist/theme-editor.cjs +4 -4
- package/dist/theme-editor.d.cts +73 -2
- package/dist/theme-editor.d.ts +73 -2
- package/dist/theme-editor.js +2 -2
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +65 -1
- package/dist/theme-reference.d.ts +65 -1
- package/dist/theme-reference.js +1 -1
- package/dist/webmcp-polyfill.js +1 -4
- package/dist/webmcp-runtime-JI7T4QYF.js +6 -0
- package/dist/webmcp-runtime.cjs +2 -2
- package/dist/webmcp-runtime.d.cts +34 -2
- package/dist/webmcp-runtime.d.ts +34 -2
- package/dist/webmcp-runtime.js +2 -2
- package/package.json +2 -2
- package/src/components/artifact-preview.ts +5 -0
- package/src/components/event-stream-badge-theming.test.ts +159 -0
- package/src/components/event-stream-view.ts +50 -20
- package/src/generated/runtype-openapi-contract.ts +8 -0
- package/src/index-core.ts +2 -0
- package/src/runtime/init.registry.test.ts +56 -0
- package/src/runtime/init.ts +17 -0
- package/src/types/theme.ts +41 -1
- package/src/types.ts +38 -1
- package/src/ui.reasoning-display.test.ts +136 -2
- package/src/ui.ts +41 -10
- package/src/utils/__snapshots__/tokens-parity.test.ts.snap +1740 -0
- package/src/utils/formatting.ts +22 -0
- package/src/utils/theme.ts +16 -0
- package/src/utils/tokens.ts +59 -0
- package/src/webmcp-bridge.test.ts +132 -23
- package/src/webmcp-bridge.ts +26 -2
- package/src/webmcp-runtime-entry.ts +71 -11
- package/dist/artifacts-ui-J6AKUGTS.js +0 -7
- package/dist/chunk-HBE7LFNT.js +0 -4
- package/dist/event-stream-view-73NWKWVQ.js +0 -1
- package/dist/webmcp-runtime-P3CHZRHF.js +0 -6
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
"use strict";var h0=Object.create;var qd=Object.defineProperty;var y0=Object.getOwnPropertyDescriptor;var b0=Object.getOwnPropertyNames;var v0=Object.getPrototypeOf,C0=Object.prototype.hasOwnProperty;var we=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fn=(t,e)=>{for(var n in e)qd(t,n,{get:e[n],enumerable:!0})},lC=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of b0(e))!C0.call(t,r)&&r!==n&&qd(t,r,{get:()=>e[r],enumerable:!(o=y0(e,r))||o.enumerable});return t};var cC=(t,e,n)=>(n=t!=null?h0(v0(t)):{},lC(e||!t||!t.__esModule?qd(n,"default",{value:t,enumerable:!0}):n,t)),w0=t=>lC(qd({},"__esModule",{value:!0}),t);var Ft,Zn=we(()=>{"use strict";Ft=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 uC={};Fn(uC,{DOMPurify:()=>pC.default,Marked:()=>dC.Marked});var dC,pC,mC=we(()=>{"use strict";dC=require("marked"),pC=cC(require("dompurify"),1)});var a1,x0,S0,Hf,Ud,fC,gC,Ji,Rf,So,ei=we(()=>{"use strict";Zn();({setLoader:a1,load:x0,provide:S0,getSync:Hf}=Ft({fallbackImport:()=>Promise.resolve().then(()=>(mC(),uC))})),Ud=new Set,fC=()=>{let t=[...Ud];Ud.clear();for(let e of t)try{e()}catch{}},gC=()=>{let t=Hf();return t?Promise.resolve(t):x0().then(e=>(fC(),e))},Ji=t=>Hf()?()=>{}:(Ud.add(t),()=>{Ud.delete(t)}),Rf=t=>{S0(t),fC()},So=Hf});var A0,Wf,jd,d1,Er,Kd=we(()=>{"use strict";ei();A0=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},Wf=t=>{let e=null;return n=>{let o=So();if(!o)return Er(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=A0(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},jd=t=>t?Wf({markedOptions:t.options,renderer:t.renderer}):Wf(),d1=Wf(),Er=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")});var M0,T0,E0,Gd,Bf=we(()=>{"use strict";Kd();ei();M0={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"]},T0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,E0=()=>{let t=null;return e=>{let n=So();if(!n)return Er(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:")&&!T0.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,M0)}},Gd=t=>t===!1?null:typeof t=="function"?t:E0()});function EC(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}:${I0(e.join(""))}`}function MC(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 I0(t){let e=MC(t,0).toString(36),n=MC(t,2654435761).toString(36);return`${e}.${n}`}var kr,Df,TC,Yd,AC,H0,Zi,kC,ea=we(()=>{"use strict";kr="webmcp:",Df=new Map,TC=t=>{Df.clear();for(let e of t){let n=e.title?.trim();n&&Df.set(e.name,n)}},Yd=t=>Df.get(H0(t)),AC=null;H0=t=>t.startsWith(kr)?t.slice(kr.length):t,Zi=t=>t.startsWith(kr),kC=()=>AC?AC():import("@mcp-b/webmcp-polyfill")});var LC,R0,Qd,Xd,W0,B0,O0,Do,D0,_0,N0,F0,PC=we(()=>{"use strict";LC="webmcp:",R0=t=>t.startsWith(LC)?t.slice(LC.length):t,Qd={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Xd=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 Qd.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={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=B0(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Do("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Do(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=R0(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return Do(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(b=>b.name===s);if(!l)return Do(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Do(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Do("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 Do("User declined the tool call.");if(o?.aborted)return Do("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,N0(n),{signal:u.signal});return O0(b)}catch(b){if(m)return Do(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Do("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return Do(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){Qd.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,Qd.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??D0;try{return await n(e)}catch(o){return Qd.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=>W0(e,o))}},W0=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},B0=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},O0=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:F0(e)}]}},Do=t=>({isError:!0,content:[{type:"text",text:t}]}),D0=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=_0(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
|
|
1
|
+
"use strict";var C0=Object.create;var Ud=Object.defineProperty;var w0=Object.getOwnPropertyDescriptor;var x0=Object.getOwnPropertyNames;var S0=Object.getPrototypeOf,A0=Object.prototype.hasOwnProperty;var we=(t,e)=>()=>(t&&(e=t(t=0)),e);var $n=(t,e)=>{for(var n in e)Ud(t,n,{get:e[n],enumerable:!0})},dC=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of x0(e))!A0.call(t,r)&&r!==n&&Ud(t,r,{get:()=>e[r],enumerable:!(o=w0(e,r))||o.enumerable});return t};var pC=(t,e,n)=>(n=t!=null?C0(S0(t)):{},dC(e||!t||!t.__esModule?Ud(n,"default",{value:t,enumerable:!0}):n,t)),M0=t=>dC(Ud({},"__esModule",{value:!0}),t);var zt,eo=we(()=>{"use strict";zt=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 fC={};$n(fC,{DOMPurify:()=>mC.default,Marked:()=>uC.Marked});var uC,mC,gC=we(()=>{"use strict";uC=require("marked"),mC=pC(require("dompurify"),1)});var f1,T0,E0,Wf,jd,hC,yC,Zi,Bf,Ao,ei=we(()=>{"use strict";eo();({setLoader:f1,load:T0,provide:E0,getSync:Wf}=zt({fallbackImport:()=>Promise.resolve().then(()=>(gC(),fC))})),jd=new Set,hC=()=>{let t=[...jd];jd.clear();for(let e of t)try{e()}catch{}},yC=()=>{let t=Wf();return t?Promise.resolve(t):T0().then(e=>(hC(),e))},Zi=t=>Wf()?()=>{}:(jd.add(t),()=>{jd.delete(t)}),Bf=t=>{E0(t),hC()},Ao=Wf});var k0,Of,Kd,y1,kr,Gd=we(()=>{"use strict";ei();k0=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},Of=t=>{let e=null;return n=>{let o=Ao();if(!o)return kr(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=k0(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Kd=t=>t?Of({markedOptions:t.options,renderer:t.renderer}):Of(),y1=Of(),kr=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")});var L0,P0,I0,Yd,Df=we(()=>{"use strict";Gd();ei();L0={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"]},P0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,I0=()=>{let t=null;return e=>{let n=Ao();if(!n)return kr(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:")&&!P0.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,L0)}},Yd=t=>t===!1?null:typeof t=="function"?t:I0()});function LC(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}:${B0(e.join(""))}`}function EC(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 B0(t){let e=EC(t,0).toString(36),n=EC(t,2654435761).toString(36);return`${e}.${n}`}var Lr,Nf,kC,Qd,TC,O0,ea,PC,ta=we(()=>{"use strict";Lr="webmcp:",Nf=new Map,kC=t=>{Nf.clear();for(let e of t){let n=e.title?.trim();n&&Nf.set(e.name,n)}},Qd=t=>Nf.get(O0(t)),TC=null;O0=t=>t.startsWith(Lr)?t.slice(Lr.length):t,ea=t=>t.startsWith(Lr),PC=()=>TC?TC():import("@mcp-b/webmcp-polyfill")});var IC,D0,Xd,Zd,_0,Jd,N0,F0,$0,_o,V0,z0,q0,U0,HC=we(()=>{"use strict";IC="webmcp:",D0=t=>t.startsWith(IC)?t.slice(IC.length):t,Xd={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Zd=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 Xd.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=N0(r.annotations);return{name:r.name,description:r.description,parametersSchema:F0(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 _o("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return _o(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=D0(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return _o(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(b=>b.name===s);if(!l)return _o(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return _o(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return _o("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 _o("User declined the tool call.");if(o?.aborted)return _o("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,q0(n),{signal:u.signal});return $0(b)}catch(b){if(m)return _o(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return _o("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return _o(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){Xd.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,Xd.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??V0;try{return await n(e)}catch(o){return Xd.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)},Jd={type:"object",properties:{}},N0=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},F0=t=>{if(t===void 0||t==="")return{...Jd};if(typeof t=="object")return t!==null&&!Array.isArray(t)?t:{...Jd};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{...Jd}}catch{return{...Jd}}},$0=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:U0(e)}]}},_o=t=>({isError:!0,content:[{type:"text",text:t}]}),V0=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=z0(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
|
|
2
2
|
|
|
3
3
|
Arguments:
|
|
4
4
|
${e}`:"")+(t.description?`
|
|
5
5
|
|
|
6
|
-
${t.description}`:"");return window.confirm(n)},
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),cs=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},
|
|
6
|
+
${t.description}`:"");return window.confirm(n)},z0=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},q0=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},U0=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}});var RC={};$n(RC,{WebMcpBridge:()=>Zd});var WC=we(()=>{"use strict";HC()});var v,NC,q,Dt,qe=we(()=>{"use strict";v=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},NC=()=>document.createDocumentFragment(),q=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))o.setAttribute(s,a);if(e.style){let s=o.style,a=e.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Dt=(...t)=>t.filter(Boolean).join(" ")});var la,tw,cs,AL,nw,ML,TL,ow,EL,rw,sp,Ll,ip,Kf,ap,kl,kL,Pl,sw,iw,aw,lw,oi=we(()=>{"use strict";la=require("partial-json"),tw=t=>t.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),cs=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},AL=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},nw=t=>t.status==="complete"?AL(t):t.status==="pending"?"Waiting":"",ML=15e3,TL=1200,ow=(t,e)=>{let n=e?.durationMs??ML,o=e?.chars??TL;return typeof t.durationMs=="number"?t.durationMs<n:(t.chunks??[]).join("").length<o},EL=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},rw=t=>t.status==="complete"?EL(t):"Using tool...",sp=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Ll=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return sp(e)},ip=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return sp(e)},Kf=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Ll(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ap=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&kl(o,n.slice(s,a.index),[]),a[1]!==void 0?kl(o,a[1],["bold"]):a[2]!==void 0?kl(o,a[2],["italic"]):a[3]!==void 0&&kl(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&kl(o,n.slice(s),[]),o},kl=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},kL=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
8
8
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},
|
|
10
|
-
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Pl=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},sw=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},iw=()=>{let t=kL();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},aw=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,la.parse)(n,la.STR|la.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?tw(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=tw(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}},lw=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}}});function $L(t){let e=0;for(let n of t.split(`
|
|
10
|
+
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Wl(t,e){let n="`".repeat(Math.max(3,$L(e)+1));return`${n}${t}
|
|
11
11
|
${e}
|
|
12
|
-
${n}`}function
|
|
12
|
+
${n}`}function VL(t,e,n){return e.includes("</document_content>")?Wl(t,e):`<document index="${n+1}">
|
|
13
13
|
<source>${t}</source>
|
|
14
14
|
<document_content>
|
|
15
15
|
${e}
|
|
16
16
|
</document_content>
|
|
17
|
-
</document>`}function Mw(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),Rl(t.label,t.text)}return n==="document"?BL(t.label,t.text,e):Rl(t.label,t.text)}var Yf=we(()=>{"use strict"});function dp(t){return t instanceof or}var or,Wl=we(()=>{"use strict";or=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var ca,Zf=we(()=>{"use strict";ca=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)===VL?new Uint8Array(t,44):new Uint8Array(t)}function qL(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 Pw,NL,FL,$L,VL,da,eg=we(()=>{"use strict";Zf();Pw=16e3,NL=24e3,FL=4096,$L=4,VL=1380533830;da=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:Pw,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:Pw});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ca(NL);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=`${qL(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(FL,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*$L));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 ps,tg=we(()=>{"use strict";ps=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 Ol(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new da(t.runtype);case"browser":if(!ps.isSupported())throw new Error("Browser speech recognition not supported");return new ps(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 ng(t){if(t?.type==="custom"&&t.custom)return Ol({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return Ol({type:"runtype",runtype:t.runtype});if(ps.isSupported())return Ol({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Iw(t){try{return ng(t),!0}catch{return!1}}var Hw=we(()=>{"use strict";eg();tg()});var Rw={};Fn(Rw,{BrowserVoiceProvider:()=>ps,RuntypeVoiceProvider:()=>da,createBestAvailableVoiceProvider:()=>ng,createVoiceProvider:()=>Ol,isVoiceSupported:()=>Iw});var Ww=we(()=>{"use strict";Hw();eg();tg()});function KL(t){return t.replace(/\/+$/,"")}async function GL(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 up,Ow=we(()=>{"use strict";Zf();up=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 ca(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=`${KL(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 GL(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 mp,Dw=we(()=>{"use strict";mp=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 _w={};Fn(_w,{FallbackSpeechEngine:()=>mp,RuntypeSpeechEngine:()=>up});var Nw=we(()=>{"use strict";Ow();Dw()});var $w={};Fn($w,{createReconnectController:()=>QL});function QL(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 I of t.getMessages())I.streaming&&(I.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??YL,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 I=t.getResumable(),E=I.lastEventId,O=new AbortController;t.setAbortController(O),t.emitReconnect({phase:"resuming",handle:I,attempt:e});let M=null;try{let D=await S({executionId:I.executionId,after:I.lastEventId,signal:O.signal});D&&D.ok&&D.body&&(M=D.body)}catch{M=null}if(O.signal.aborted)return;if(M){let D=t.getMessages().find(B=>B.id===I.assistantMessageId)?.content,L=typeof D=="string"?D:"";try{await t.resumeConnect(M,I.assistantMessageId,L)}catch{}if(O.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:I});return}t.getResumable().lastEventId!==E&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await m(b[Math.min(e-1,b.length-1)]??1e3),O.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 YL,Vw=we(()=>{"use strict";YL=[1e3,2e3,4e3,8e3,8e3]});var Ke,eo=we(()=>{"use strict";Ke=(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 Uw={};Fn(Uw,{EXTRA_LUCIDE_ICONS:()=>tP});var ce,tP,jw=we(()=>{"use strict";ce=require("lucide"),tP={user:ce.User,mail:ce.Mail,phone:ce.Phone,calendar:ce.Calendar,clock:ce.Clock,building:ce.Building,"map-pin":ce.MapPin,lock:ce.Lock,key:ce.Key,"credit-card":ce.CreditCard,hash:ce.Hash,globe:ce.Globe,link:ce.Link,"circle-check":ce.CircleCheck,"circle-x":ce.CircleX,"triangle-alert":ce.TriangleAlert,info:ce.Info,ban:ce.Ban,shield:ce.Shield,house:ce.House,"pen-line":ce.PenLine,save:ce.Save,share:ce.Share,funnel:ce.Funnel,settings:ce.Settings,"rotate-cw":ce.RotateCw,"shopping-cart":ce.ShoppingCart,"shopping-bag":ce.ShoppingBag,package:ce.Package,truck:ce.Truck,tag:ce.Tag,gift:ce.Gift,receipt:ce.Receipt,wallet:ce.Wallet,store:ce.Store,"dollar-sign":ce.DollarSign,percent:ce.Percent,play:ce.Play,pause:ce.Pause,"volume-x":ce.VolumeX,camera:ce.Camera,image:ce.Image,film:ce.Film,headphones:ce.Headphones,"message-circle":ce.MessageCircle,bell:ce.Bell,heart:ce.Heart,"eye-off":ce.EyeOff,bookmark:ce.Bookmark,"calendar-days":ce.CalendarDays,timer:ce.Timer,folder:ce.Folder,"folder-open":ce.FolderOpen,files:ce.Files,"chart-column":ce.ChartColumn,sparkles:ce.Sparkles,zap:ce.Zap,sun:ce.Sun,moon:ce.Moon,flag:ce.Flag,lightbulb:ce.Lightbulb,monitor:ce.Monitor,smartphone:ce.Smartphone}});var nP,oP,lg,gp,hp=we(()=>{"use strict";Zn();({setLoader:nP,load:oP}=Ft({fallbackImport:()=>Promise.resolve().then(()=>(jw(),Uw))})),lg=nP,gp=oP});var he,rP,sP,yp,pa,cg,bp,iP,Kw,aP,dg,lP,cP,He,Jt=we(()=>{"use strict";eo();hp();he=require("lucide"),rP={activity:he.Activity,"arrow-down":he.ArrowDown,"arrow-up":he.ArrowUp,"arrow-up-right":he.ArrowUpRight,bot:he.Bot,"chevron-down":he.ChevronDown,"chevron-up":he.ChevronUp,"chevron-right":he.ChevronRight,"chevron-left":he.ChevronLeft,check:he.Check,clipboard:he.Clipboard,"clipboard-copy":he.ClipboardCopy,"code-xml":he.CodeXml,copy:he.Copy,file:he.File,"file-code":he.FileCode,"file-spreadsheet":he.FileSpreadsheet,"file-text":he.FileText,"image-plus":he.ImagePlus,loader:he.Loader,"loader-circle":he.LoaderCircle,mic:he.Mic,paperclip:he.Paperclip,quote:he.Quote,"refresh-cw":he.RefreshCw,search:he.Search,send:he.Send,"shield-alert":he.ShieldAlert,"shield-check":he.ShieldCheck,"shield-x":he.ShieldX,square:he.Square,"thumbs-down":he.ThumbsDown,"thumbs-up":he.ThumbsUp,upload:he.Upload,"volume-2":he.Volume2,x:he.X,"at-sign":he.AtSign,"arrow-left":he.ArrowLeft,"arrow-right":he.ArrowRight,"external-link":he.ExternalLink,ellipsis:he.Ellipsis,"ellipsis-vertical":he.EllipsisVertical,menu:he.Menu,"panel-left":he.PanelLeft,plus:he.Plus,minus:he.Minus,pencil:he.Pencil,trash:he.Trash,"trash-2":he.Trash2,download:he.Download,maximize:he.Maximize,minimize:he.Minimize,"message-square":he.MessageSquare,star:he.Star,eye:he.Eye,history:he.History},sP=["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"],yp=new Map(Object.entries(rP)),pa=new Set,cg=!1,bp=new Set,iP=t=>{let e=[...bp];t&&bp.clear();for(let n of e)try{n()}catch{}},Kw=t=>cg?()=>{}:(bp.add(t),()=>{bp.delete(t)}),aP=()=>{let t=0;for(let e of[...pa]){let n=yp.get(e.name);if(!n)continue;pa.delete(e),t++;let o=Ke(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},dg=!1,lP=()=>{gp().then(t=>{if(!cg){for(let[e,n]of Object.entries(t.EXTRA_LUCIDE_ICONS))yp.has(e)||yp.set(e,n);cg=!0,aP(),iP(!0)}}).catch(t=>{dg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},cP=(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},He=(t,e=24,n="currentColor",o=2)=>{let r=yp.get(t);if(r)return Ke(r,e,n,o);if(sP.includes(t)){dg&&(dg=!1);let s=cP(e,n,o);if(pa.size>=500){let a=pa.values().next().value;a&&pa.delete(a)}return pa.add({el:s,name:t,size:e,color:n,strokeWidth:o}),lP(),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,In,ua,us=we(()=>{"use strict";fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},In=1e5,ua=In+1});function dx(t){let e=t.getRootNode?.();return e&&px(e)||e&&Rp(e)?e:t.ownerDocument??document}function Hp(t,e,n){let o=Rp(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(Rp(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function Wp(t,e,n){if(Rp(t)||px(t)){Hp(t,e,n);return}let o=t;if(o.isConnected){Hp(dx(o),e,n);return}let r=o.ownerDocument??document;Hp(r,e,n),queueMicrotask(()=>{let s=dx(o);s!==r&&Hp(s,e,n)})}function TP(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function ms(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??TP(e),h=!1,g=null,b=()=>{if(!h)return;let I=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${I.width}px`),a&&(n.style.maxWidth=`${I.width}px`);let E=n.getBoundingClientRect(),O=l?.()??null,M=O!=null?I.top+O:I.top,D=o==="top-start"||o==="top-end"?M-r-E.height:I.bottom+r,B=o==="bottom-end"||o==="top-end"?I.right-E.width:I.left,W=a?.()??null;if(W!=null){let z=Math.max(I.left,I.right-E.width);B=Math.min(Math.max(I.left+W,I.left),z)}n.style.top=`${D}px`,n.style.left=`${B}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 I=(e.ownerDocument??document).defaultView??window,E=e.ownerDocument??document,O=()=>{if(!e.isConnected){C(),u?.("anchor-removed");return}b()},M=L=>{let B=typeof L.composedPath=="function"?L.composedPath():[];B.includes(n)||B.includes(e)||(C(),u?.("outside"))},D=I.setTimeout(()=>{E.addEventListener("pointerdown",M,!0)},0);I.addEventListener("scroll",O,!0),I.addEventListener("resize",O),g=()=>{I.clearTimeout(D),E.removeEventListener("pointerdown",M,!0),I.removeEventListener("scroll",O,!0),I.removeEventListener("resize",O)},p?.()};return{get isOpen(){return h},open:S,close:C,toggle:()=>h?C():S(),reposition:b,destroy:C}}function ux(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Rp,px,ga=we(()=>{"use strict";Rp=t=>t.nodeType===Node.DOCUMENT_NODE,px=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});function ha(t){t.style.display=t.childElementCount>0?"flex":"none"}function Mg(t){let e=t.querySelector(Ag);if(e)return e;let n=q("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 Ag,Bp=we(()=>{"use strict";Ue();Ag="[data-persona-composer-chip-row]"});function $l(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Fx(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:()=>$l(t.form),dispatchInput:e,focus:()=>t.focus()}}var _p=we(()=>{"use strict"});function QP(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
|
|
18
|
-
`:o===""||
|
|
19
|
-
`||a==="\uFFFC"||!r&&
|
|
17
|
+
</document>`}function kw(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),Wl(t.label,t.text)}return n==="document"?VL(t.label,t.text,e):Wl(t.label,t.text)}var Xf=we(()=>{"use strict"});function up(t){return t instanceof or}var or,Bl=we(()=>{"use strict";or=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var da,tg=we(()=>{"use strict";da=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 QL(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===YL?new Uint8Array(t,44):new Uint8Array(t)}function XL(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 Rw,jL,KL,GL,YL,pa,ng=we(()=>{"use strict";tg();Rw=16e3,jL=24e3,KL=4096,GL=4,YL=1380533830;pa=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:Rw,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:Rw});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new da(jL);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=`${XL(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(KL,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*GL));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=QL(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 ps,og=we(()=>{"use strict";ps=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 Dl(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new pa(t.runtype);case"browser":if(!ps.isSupported())throw new Error("Browser speech recognition not supported");return new ps(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 rg(t){if(t?.type==="custom"&&t.custom)return Dl({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return Dl({type:"runtype",runtype:t.runtype});if(ps.isSupported())return Dl({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ww(t){try{return rg(t),!0}catch{return!1}}var Bw=we(()=>{"use strict";ng();og()});var Ow={};$n(Ow,{BrowserVoiceProvider:()=>ps,RuntypeVoiceProvider:()=>pa,createBestAvailableVoiceProvider:()=>rg,createVoiceProvider:()=>Dl,isVoiceSupported:()=>Ww});var Dw=we(()=>{"use strict";Bw();ng();og()});function eP(t){return t.replace(/\/+$/,"")}async function tP(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 fp,Nw=we(()=>{"use strict";tg();fp=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 da(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=`${eP(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 tP(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 gp,Fw=we(()=>{"use strict";gp=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 $w={};$n($w,{FallbackSpeechEngine:()=>gp,RuntypeSpeechEngine:()=>fp});var Vw=we(()=>{"use strict";Nw();Fw()});var qw={};$n(qw,{createReconnectController:()=>oP});function oP(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 I of t.getMessages())I.streaming&&(I.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??nP,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 I=t.getResumable(),E=I.lastEventId,O=new AbortController;t.setAbortController(O),t.emitReconnect({phase:"resuming",handle:I,attempt:e});let M=null;try{let D=await S({executionId:I.executionId,after:I.lastEventId,signal:O.signal});D&&D.ok&&D.body&&(M=D.body)}catch{M=null}if(O.signal.aborted)return;if(M){let D=t.getMessages().find(B=>B.id===I.assistantMessageId)?.content,L=typeof D=="string"?D:"";try{await t.resumeConnect(M,I.assistantMessageId,L)}catch{}if(O.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:I});return}t.getResumable().lastEventId!==E&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await m(b[Math.min(e-1,b.length-1)]??1e3),O.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 nP,Uw=we(()=>{"use strict";nP=[1e3,2e3,4e3,8e3,8e3]});var Ke,to=we(()=>{"use strict";Ke=(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 Gw={};$n(Gw,{EXTRA_LUCIDE_ICONS:()=>lP});var ce,lP,Yw=we(()=>{"use strict";ce=require("lucide"),lP={user:ce.User,mail:ce.Mail,phone:ce.Phone,calendar:ce.Calendar,clock:ce.Clock,building:ce.Building,"map-pin":ce.MapPin,lock:ce.Lock,key:ce.Key,"credit-card":ce.CreditCard,hash:ce.Hash,globe:ce.Globe,link:ce.Link,"circle-check":ce.CircleCheck,"circle-x":ce.CircleX,"triangle-alert":ce.TriangleAlert,info:ce.Info,ban:ce.Ban,shield:ce.Shield,house:ce.House,"pen-line":ce.PenLine,save:ce.Save,share:ce.Share,funnel:ce.Funnel,settings:ce.Settings,"rotate-cw":ce.RotateCw,"shopping-cart":ce.ShoppingCart,"shopping-bag":ce.ShoppingBag,package:ce.Package,truck:ce.Truck,tag:ce.Tag,gift:ce.Gift,receipt:ce.Receipt,wallet:ce.Wallet,store:ce.Store,"dollar-sign":ce.DollarSign,percent:ce.Percent,play:ce.Play,pause:ce.Pause,"volume-x":ce.VolumeX,camera:ce.Camera,image:ce.Image,film:ce.Film,headphones:ce.Headphones,"message-circle":ce.MessageCircle,bell:ce.Bell,heart:ce.Heart,"eye-off":ce.EyeOff,bookmark:ce.Bookmark,"calendar-days":ce.CalendarDays,timer:ce.Timer,folder:ce.Folder,"folder-open":ce.FolderOpen,files:ce.Files,"chart-column":ce.ChartColumn,sparkles:ce.Sparkles,zap:ce.Zap,sun:ce.Sun,moon:ce.Moon,flag:ce.Flag,lightbulb:ce.Lightbulb,monitor:ce.Monitor,smartphone:ce.Smartphone}});var cP,dP,dg,yp,bp=we(()=>{"use strict";eo();({setLoader:cP,load:dP}=zt({fallbackImport:()=>Promise.resolve().then(()=>(Yw(),Gw))})),dg=cP,yp=dP});var he,pP,uP,vp,ua,pg,Cp,mP,Qw,fP,ug,gP,hP,He,en=we(()=>{"use strict";to();bp();he=require("lucide"),pP={activity:he.Activity,"arrow-down":he.ArrowDown,"arrow-up":he.ArrowUp,"arrow-up-right":he.ArrowUpRight,bot:he.Bot,"chevron-down":he.ChevronDown,"chevron-up":he.ChevronUp,"chevron-right":he.ChevronRight,"chevron-left":he.ChevronLeft,check:he.Check,clipboard:he.Clipboard,"clipboard-copy":he.ClipboardCopy,"code-xml":he.CodeXml,copy:he.Copy,file:he.File,"file-code":he.FileCode,"file-spreadsheet":he.FileSpreadsheet,"file-text":he.FileText,"image-plus":he.ImagePlus,loader:he.Loader,"loader-circle":he.LoaderCircle,mic:he.Mic,paperclip:he.Paperclip,quote:he.Quote,"refresh-cw":he.RefreshCw,search:he.Search,send:he.Send,"shield-alert":he.ShieldAlert,"shield-check":he.ShieldCheck,"shield-x":he.ShieldX,square:he.Square,"thumbs-down":he.ThumbsDown,"thumbs-up":he.ThumbsUp,upload:he.Upload,"volume-2":he.Volume2,x:he.X,"at-sign":he.AtSign,"arrow-left":he.ArrowLeft,"arrow-right":he.ArrowRight,"external-link":he.ExternalLink,ellipsis:he.Ellipsis,"ellipsis-vertical":he.EllipsisVertical,menu:he.Menu,"panel-left":he.PanelLeft,plus:he.Plus,minus:he.Minus,pencil:he.Pencil,trash:he.Trash,"trash-2":he.Trash2,download:he.Download,maximize:he.Maximize,minimize:he.Minimize,"message-square":he.MessageSquare,star:he.Star,eye:he.Eye,history:he.History},uP=["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"],vp=new Map(Object.entries(pP)),ua=new Set,pg=!1,Cp=new Set,mP=t=>{let e=[...Cp];t&&Cp.clear();for(let n of e)try{n()}catch{}},Qw=t=>pg?()=>{}:(Cp.add(t),()=>{Cp.delete(t)}),fP=()=>{let t=0;for(let e of[...ua]){let n=vp.get(e.name);if(!n)continue;ua.delete(e),t++;let o=Ke(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},ug=!1,gP=()=>{yp().then(t=>{if(!pg){for(let[e,n]of Object.entries(t.EXTRA_LUCIDE_ICONS))vp.has(e)||vp.set(e,n);pg=!0,fP(),mP(!0)}}).catch(t=>{ug=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},hP=(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},He=(t,e=24,n="currentColor",o=2)=>{let r=vp.get(t);if(r)return Ke(r,e,n,o);if(uP.includes(t)){ug&&(ug=!1);let s=hP(e,n,o);if(ua.size>=500){let a=ua.values().next().value;a&&ua.delete(a)}return ua.add({el:s,name:t,size:e,color:n,strokeWidth:o}),gP(),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 hn,Rn,ma,us=we(()=>{"use strict";hn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Rn=1e5,ma=Rn+1});function mx(t){let e=t.getRootNode?.();return e&&fx(e)||e&&Bp(e)?e:t.ownerDocument??document}function Wp(t,e,n){let o=Bp(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(Bp(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function Op(t,e,n){if(Bp(t)||fx(t)){Wp(t,e,n);return}let o=t;if(o.isConnected){Wp(mx(o),e,n);return}let r=o.ownerDocument??document;Wp(r,e,n),queueMicrotask(()=>{let s=mx(o);s!==r&&Wp(s,e,n)})}function RP(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function ms(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??RP(e),h=!1,g=null,b=()=>{if(!h)return;let I=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${I.width}px`),a&&(n.style.maxWidth=`${I.width}px`);let E=n.getBoundingClientRect(),O=l?.()??null,M=O!=null?I.top+O:I.top,D=o==="top-start"||o==="top-end"?M-r-E.height:I.bottom+r,B=o==="bottom-end"||o==="top-end"?I.right-E.width:I.left,W=a?.()??null;if(W!=null){let z=Math.max(I.left,I.right-E.width);B=Math.min(Math.max(I.left+W,I.left),z)}n.style.top=`${D}px`,n.style.left=`${B}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 I=(e.ownerDocument??document).defaultView??window,E=e.ownerDocument??document,O=()=>{if(!e.isConnected){C(),u?.("anchor-removed");return}b()},M=L=>{let B=typeof L.composedPath=="function"?L.composedPath():[];B.includes(n)||B.includes(e)||(C(),u?.("outside"))},D=I.setTimeout(()=>{E.addEventListener("pointerdown",M,!0)},0);I.addEventListener("scroll",O,!0),I.addEventListener("resize",O),g=()=>{I.clearTimeout(D),E.removeEventListener("pointerdown",M,!0),I.removeEventListener("scroll",O,!0),I.removeEventListener("resize",O)},p?.()};return{get isOpen(){return h},open:S,close:C,toggle:()=>h?C():S(),reposition:b,destroy:C}}function gx(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Bp,fx,ha=we(()=>{"use strict";Bp=t=>t.nodeType===Node.DOCUMENT_NODE,fx=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});function ya(t){t.style.display=t.childElementCount>0?"flex":"none"}function Eg(t){let e=t.querySelector(Tg);if(e)return e;let n=q("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 Tg,Dp=we(()=>{"use strict";qe();Tg="[data-persona-composer-chip-row]"});function Vl(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function zx(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:()=>Vl(t.form),dispatchInput:e,focus:()=>t.focus()}}var Fp=we(()=>{"use strict"});function oI(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
|
|
18
|
+
`:o===""||Kx.test(o)}function rI(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 oI(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(a===`
|
|
19
|
+
`||a==="\uFFFC"||!r&&Kx.test(a))return null;s--}return null}function zl(t,e,n){for(let o of n){let r=rI(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Gx(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function Yx(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var Kx,$p=we(()=>{"use strict";Kx=/\s/});function Vp(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 Pg=we(()=>{"use strict"});var Xx,Ig,zp,qp=we(()=>{"use strict";Xx=null,Ig=t=>{Xx=t},zp=(t,e,n,o)=>Xx?.(t,e,n,o)??null});function Zx(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:(I,E)=>{if(I===g&&E===b)return;g=I,b=E;let O=n.renderMentionChip({ref:e,status:g,payload:b,remove:o});C.replaceWith(O),C=O}}}let r=e.iconName??n.chipIconName??"at-sign",s=q("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=zp(g,13,"currentColor",2);b&&a.appendChild(b)};l(r);let d=v("span","persona-mention-chip-spinner"),p=q("span",{className:"persona-mention-chip-label",text:e.label}),u=q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),m=Ke(Jx.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 Jx,eS=we(()=>{"use strict";qe();Jx=require("lucide");to();qp()});function Up(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var tS,jp,Hg=we(()=>{"use strict";eS();Dp();Xf();tS=(t,e)=>`${t}\0${e}`,jp=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=tS(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=Up(e,n),a={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return a.chip=Zx({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:Up(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=tS(h.source.id,h.item.id);if(!p.has(b)){if(p.add(b),g.llmAppend&&g.llmAppend.trim())try{a.push(kw({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(){ya(this.opts.contextRow)}}});var nS,oS=we(()=>{"use strict";nS=`
|
|
20
20
|
.persona-mention-menu {
|
|
21
21
|
box-sizing: border-box;
|
|
22
22
|
display: flex;
|
|
@@ -174,13 +174,13 @@ ${e}
|
|
|
174
174
|
min-height: 36px;
|
|
175
175
|
}
|
|
176
176
|
}
|
|
177
|
-
`});function Up(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var tS=we(()=>{"use strict"});function rS(t){let{config:e,listboxId:n}=t,o=q("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=q("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),a=Ke(oS.Search,15,"currentColor",2);a&&s.appendChild(a);let l=q("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",H=>t.onSearchKeydown?.(H));let d=q("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,d);let p=[],u=[],m=-1,h=new Map,g=(H,w)=>`${H}\0${w}`,b=H=>`${n}-opt-${H}`,C=H=>`${n}-grp-${H}`,S=(H,w)=>{let k=p[H];k&&(w?k.setAttribute("data-active","true"):k.removeAttribute("data-active"),k.setAttribute("aria-selected",w?"true":"false"),u[H]?.(w))},I=(H,w=!0)=>{m>=0&&m!==H&&S(m,!1),m=H;let k=p[H];k?(S(H,!0),w&&k.scrollIntoView?.({block:"nearest"}),d.setAttribute("aria-activedescendant",k.id),l.setAttribute("aria-activedescendant",k.id)):(d.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},E=(H,w)=>{let k=C(w),R=q("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":k}});return R.appendChild(q("div",{className:"persona-mention-group-header",attrs:{id:k},text:H})),R},O=()=>{let H=q("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),w=v("span","persona-mention-option-icon");H.appendChild(w);let k="",R=v("span","persona-mention-option-text"),_=v("span","persona-mention-option-labelline"),X=v("span","persona-mention-option-label");_.appendChild(X),R.appendChild(_),H.appendChild(R);let j=null,Q=null,Z={el:H,index:0,update:(ie,se,pe)=>{Z.index=se,H.id=b(se),H.setAttribute("aria-setsize",String(pe)),H.setAttribute("aria-posinset",String(se+1)),H.removeAttribute("data-active"),H.setAttribute("aria-selected","false");let ue=ie.iconName??e.chipIconName??"at-sign";if(ue!==k){k=ue;let be=JP(ue,15,2);w.replaceChildren(...be?[be]:[])}X.textContent!==ie.label&&(X.textContent=ie.label);let xe=ie.commandArgsPlaceholder?`\u2039${ie.commandArgsPlaceholder}\u203A`:null;xe?(j||(j=v("span","persona-mention-option-arghint"),_.appendChild(j)),j.textContent!==xe&&(j.textContent=xe)):j&&(j.remove(),j=null),ie.description?(Q||(Q=v("span","persona-mention-option-desc"),R.appendChild(Q)),Q.textContent!==ie.description&&(Q.textContent=ie.description)):Q&&(Q.remove(),Q=null)}};return H.addEventListener("mousedown",ie=>{ie.button===0&&(ie.preventDefault(),t.onSelectIndex(Z.index))}),H.addEventListener("mouseenter",()=>t.onHoverIndex(Z.index)),Z},M=(H,w,k,R,_)=>{let X=q("div",{className:"persona-mention-option",attrs:{role:"option",id:b(R),"aria-selected":"false","aria-setsize":String(_),"aria-posinset":String(R+1)}}),j=Q=>{X.replaceChildren(e.renderMentionItem({item:H,source:w,query:k,active:Q,index:R}))};return j(!1),X.addEventListener("mousedown",Q=>{Q.button===0&&(Q.preventDefault(),t.onSelectIndex(R))}),X.addEventListener("mouseenter",()=>t.onHoverIndex(R)),{el:X,paint:j}},D=H=>{let w=q("div",{className:"persona-mention-status persona-mention-error"});if(w.appendChild(q("span",{className:"persona-mention-error-text",text:`Couldn't load ${H.label}`})),t.onRetry){let k=q("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});k.addEventListener("mousedown",R=>R.preventDefault()),k.addEventListener("click",R=>{R.preventDefault(),t.onRetry(H.id)}),w.appendChild(k)}return w};return{el:o,render:H=>{d.replaceChildren(),p=[],u=[],m=-1;let w=new Set,k=0,R=0,_=0,X=0,j=0,Q=H.groups.reduce((Z,ie)=>ie.status==="ready"?Z+ie.items.length:Z,0);for(let Z of H.groups)if(Z.status==="loading"){_++;let ie=E(Z.source.label,j++);ie.appendChild(q("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),d.appendChild(ie)}else if(Z.status==="error"){X++;let ie=E(Z.source.label,j++);ie.appendChild(D(Z.source)),d.appendChild(ie)}else if(Z.status==="ready"&&Z.items.length>0){let ie=new Map;for(let pe of Z.items){let ue=pe.group??Z.source.label,xe=ie.get(ue);xe?xe.push(pe):ie.set(ue,[pe])}let se=Array.from(ie.entries());se.forEach(([pe,ue],xe)=>{let be=E(pe,j++);for(let F of ue){let Ce=k++,Ee;if(e.renderMentionItem){let qe=M(F,Z.source,H.query,Ce,Q);Ee=qe.el,u.push(qe.paint)}else{let qe=g(Z.source.id,F.id),ke=w.has(qe)?void 0:h.get(qe);ke||(ke=O(),w.has(qe)||h.set(qe,ke)),w.add(qe),ke.update(F,Ce,Q),Ee=ke.el,u.push(null)}p.push(Ee),be.appendChild(Ee),R++}Z.truncated&&xe===se.length-1&&be.appendChild(q("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),d.appendChild(be)})}for(let Z of h.keys())w.has(Z)||h.delete(Z);R===0&&_===0&&X===0&&d.appendChild(q("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),p.length>0?I(Math.min(Math.max(0,H.activeIndex),p.length-1)):(d.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:I,destroy:()=>{d.replaceChildren(),p=[],h.clear(),o.remove()},showSearch:(H,w)=>{l.value=H,w&&(l.placeholder=w),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var oS,nS,JP,sS=we(()=>{"use strict";Ue();oS=require("lucide");eo();Vp();nS=new Map,JP=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=nS.get(o);return r===void 0&&(r=$p(t,e,"currentColor",n),nS.set(o,r)),r?r.cloneNode(!0):null}});var ZP,eI,jp,iS=we(()=>{"use strict";ga();eS();Np();kg();tS();sS();Pg();ZP=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",eI=0,jp=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=Fp(n),r=o.filter(a=>a.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++eI}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():rS({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:a=>this.selectIndex(a),onHoverIndex:a=>this.setActiveIndex(a,!1),onRetry:a=>this.retrySource(a),onSearchInput:a=>this.setQuery(a),onSearchKeydown:a=>{this.handleKeydown(a)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(a=>a.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(a=>a.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=Vl(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=Vl(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=ms({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),Wp(this.menu.el,"persona-mention-menu",Zx),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,a=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(a).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}ZP(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(a=>a.id===r.source.id)-o.findIndex(a=>a.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return Up(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),a=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,a),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=zp(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let a=this.input.getValue();this.input.setValueWithCaret(a.slice(0,s)+o+a.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=Up(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
|
|
177
|
+
`});function Kp(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var rS=we(()=>{"use strict"});function aS(t){let{config:e,listboxId:n}=t,o=q("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=q("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),a=Ke(iS.Search,15,"currentColor",2);a&&s.appendChild(a);let l=q("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",H=>t.onSearchKeydown?.(H));let d=q("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,d);let p=[],u=[],m=-1,h=new Map,g=(H,w)=>`${H}\0${w}`,b=H=>`${n}-opt-${H}`,C=H=>`${n}-grp-${H}`,S=(H,w)=>{let k=p[H];k&&(w?k.setAttribute("data-active","true"):k.removeAttribute("data-active"),k.setAttribute("aria-selected",w?"true":"false"),u[H]?.(w))},I=(H,w=!0)=>{m>=0&&m!==H&&S(m,!1),m=H;let k=p[H];k?(S(H,!0),w&&k.scrollIntoView?.({block:"nearest"}),d.setAttribute("aria-activedescendant",k.id),l.setAttribute("aria-activedescendant",k.id)):(d.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},E=(H,w)=>{let k=C(w),R=q("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":k}});return R.appendChild(q("div",{className:"persona-mention-group-header",attrs:{id:k},text:H})),R},O=()=>{let H=q("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),w=v("span","persona-mention-option-icon");H.appendChild(w);let k="",R=v("span","persona-mention-option-text"),_=v("span","persona-mention-option-labelline"),X=v("span","persona-mention-option-label");_.appendChild(X),R.appendChild(_),H.appendChild(R);let j=null,Q=null,Z={el:H,index:0,update:(ie,se,pe)=>{Z.index=se,H.id=b(se),H.setAttribute("aria-setsize",String(pe)),H.setAttribute("aria-posinset",String(se+1)),H.removeAttribute("data-active"),H.setAttribute("aria-selected","false");let ue=ie.iconName??e.chipIconName??"at-sign";if(ue!==k){k=ue;let be=sI(ue,15,2);w.replaceChildren(...be?[be]:[])}X.textContent!==ie.label&&(X.textContent=ie.label);let xe=ie.commandArgsPlaceholder?`\u2039${ie.commandArgsPlaceholder}\u203A`:null;xe?(j||(j=v("span","persona-mention-option-arghint"),_.appendChild(j)),j.textContent!==xe&&(j.textContent=xe)):j&&(j.remove(),j=null),ie.description?(Q||(Q=v("span","persona-mention-option-desc"),R.appendChild(Q)),Q.textContent!==ie.description&&(Q.textContent=ie.description)):Q&&(Q.remove(),Q=null)}};return H.addEventListener("mousedown",ie=>{ie.button===0&&(ie.preventDefault(),t.onSelectIndex(Z.index))}),H.addEventListener("mouseenter",()=>t.onHoverIndex(Z.index)),Z},M=(H,w,k,R,_)=>{let X=q("div",{className:"persona-mention-option",attrs:{role:"option",id:b(R),"aria-selected":"false","aria-setsize":String(_),"aria-posinset":String(R+1)}}),j=Q=>{X.replaceChildren(e.renderMentionItem({item:H,source:w,query:k,active:Q,index:R}))};return j(!1),X.addEventListener("mousedown",Q=>{Q.button===0&&(Q.preventDefault(),t.onSelectIndex(R))}),X.addEventListener("mouseenter",()=>t.onHoverIndex(R)),{el:X,paint:j}},D=H=>{let w=q("div",{className:"persona-mention-status persona-mention-error"});if(w.appendChild(q("span",{className:"persona-mention-error-text",text:`Couldn't load ${H.label}`})),t.onRetry){let k=q("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});k.addEventListener("mousedown",R=>R.preventDefault()),k.addEventListener("click",R=>{R.preventDefault(),t.onRetry(H.id)}),w.appendChild(k)}return w};return{el:o,render:H=>{d.replaceChildren(),p=[],u=[],m=-1;let w=new Set,k=0,R=0,_=0,X=0,j=0,Q=H.groups.reduce((Z,ie)=>ie.status==="ready"?Z+ie.items.length:Z,0);for(let Z of H.groups)if(Z.status==="loading"){_++;let ie=E(Z.source.label,j++);ie.appendChild(q("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),d.appendChild(ie)}else if(Z.status==="error"){X++;let ie=E(Z.source.label,j++);ie.appendChild(D(Z.source)),d.appendChild(ie)}else if(Z.status==="ready"&&Z.items.length>0){let ie=new Map;for(let pe of Z.items){let ue=pe.group??Z.source.label,xe=ie.get(ue);xe?xe.push(pe):ie.set(ue,[pe])}let se=Array.from(ie.entries());se.forEach(([pe,ue],xe)=>{let be=E(pe,j++);for(let F of ue){let Ce=k++,Ee;if(e.renderMentionItem){let Ve=M(F,Z.source,H.query,Ce,Q);Ee=Ve.el,u.push(Ve.paint)}else{let Ve=g(Z.source.id,F.id),ke=w.has(Ve)?void 0:h.get(Ve);ke||(ke=O(),w.has(Ve)||h.set(Ve,ke)),w.add(Ve),ke.update(F,Ce,Q),Ee=ke.el,u.push(null)}p.push(Ee),be.appendChild(Ee),R++}Z.truncated&&xe===se.length-1&&be.appendChild(q("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),d.appendChild(be)})}for(let Z of h.keys())w.has(Z)||h.delete(Z);R===0&&_===0&&X===0&&d.appendChild(q("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),p.length>0?I(Math.min(Math.max(0,H.activeIndex),p.length-1)):(d.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:I,destroy:()=>{d.replaceChildren(),p=[],h.clear(),o.remove()},showSearch:(H,w)=>{l.value=H,w&&(l.placeholder=w),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var iS,sS,sI,lS=we(()=>{"use strict";qe();iS=require("lucide");to();qp();sS=new Map,sI=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=sS.get(o);return r===void 0&&(r=zp(t,e,"currentColor",n),sS.set(o,r)),r?r.cloneNode(!0):null}});var iI,aI,Gp,cS=we(()=>{"use strict";ha();oS();$p();Pg();rS();lS();Hg();iI=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",aI=0,Gp=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=Vp(n),r=o.filter(a=>a.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++aI}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():aS({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:a=>this.selectIndex(a),onHoverIndex:a=>this.setActiveIndex(a,!1),onRetry:a=>this.retrySource(a),onSearchInput:a=>this.setQuery(a),onSearchKeydown:a=>{this.handleKeydown(a)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(a=>a.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(a=>a.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=zl(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=zl(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=ms({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),Op(this.menu.el,"persona-mention-menu",nS),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,a=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(a).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}iI(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(a=>a.id===r.source.id)-o.findIndex(a=>a.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return Kp(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),a=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,a),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=Up(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let a=this.input.getValue();this.input.setValueWithCaret(a.slice(0,s)+o+a.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=Kp(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
|
|
178
178
|
`):[e.split(`
|
|
179
|
-
`)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:a}=
|
|
180
|
-
`,p=
|
|
181
|
-
`?0:1);return{doc:{blocks:p},caret:u}}function
|
|
182
|
-
`});function
|
|
183
|
-
`);return s<0?"":t.slice(0,s)}return t},
|
|
179
|
+
`)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:a}=Kp(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=Yx(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 Rg(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,lI),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 lI,dS=we(()=>{"use strict";lI={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 pS(t){let e=t.composerInput??zx(t.textarea),n=Rg("polite",t.liveRegionHost),o=Rg("assertive",t.liveRegionHost),r=p=>n.announce(p),s=p=>o.announce(p),a=new jp({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Gp({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 uS=we(()=>{"use strict";Hg();cS();Fp();dS();qp()});var mS={};$n(mS,{mountContextMentions:()=>pS,setMentionIconRenderer:()=>Ig});var fS=we(()=>{"use strict";uS()});function Og(t){return t.kind==="text"?t.value.length:1}function Dg(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 gS(){return{blocks:[{kind:"text",value:""}]}}function _g(t){return{blocks:[{kind:"text",value:t}]}}function Ng(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${dI}${e.ref.label}`).join("")}function Qp(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function Xp(t){return t.blocks.reduce((e,n)=>e+Og(n),0)}function pI(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Yp(t,e){let n=[],o=[],r=0;for(let s of t){let a=Og(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 Fg(t,e,n,o){let r=Yp(t.blocks,e.start).left,s=Yp(t.blocks,e.end).right,a=s[0],l=a?.kind==="text"?a.value.charAt(0):"",d=l!==" "&&l!==" "&&l!==`
|
|
180
|
+
`,p=Dg([...r,{kind:"mention",id:o,ref:n},...d?[{kind:"text",value:" "}]:[],...s]),u=e.start+1+(l===`
|
|
181
|
+
`?0:1);return{doc:{blocks:p},caret:u}}function hS(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+=Og(a);return r?{doc:{blocks:Dg(t.blocks.filter(a=>!(a.kind==="mention"&&a.id===e)))},caret:n}:{doc:t,caret:o}}function Jp(t,e,n,o){let r=Xp(t),s=Math.max(0,Math.min(e,n,r)),a=Math.min(r,Math.max(e,n,0)),l=Yp(t.blocks,s).left,d=Yp(t.blocks,a).right;return{doc:{blocks:Dg([...l,{kind:"text",value:o},...d])},caret:s+o.length}}function yS(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:Ng(t),contextMentions:pI(t).map(n=>n.ref),contentSegments:e}}var dI,$g=we(()=>{"use strict";$p();dI="@"});function Kl(t){return t.nodeType===1&&t.hasAttribute(jl)}function CS(t){return t.nodeType===1&&t.tagName==="BR"}function Zp(t){return t.nodeType===3?t.data.length:Kl(t)||CS(t)?1:t.textContent?.length??0}function bS(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?Zp(r):0);if(r.contains(e))return Kl(r)?o+1:o+mI(r,e,n);o+=Zp(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let a=0;a<Math.min(n,s.length);a++)r+=Zp(s[a]);return r}return o}function mI(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 Ul(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],a=Zp(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 fI(t,e){let n=[];for(let o of Array.from(t.childNodes))if(Kl(o)){let r=o.getAttribute(jl),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(CS(o))n.push({kind:"text",value:vS});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 wS(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=()=>fI(o,n),l=W=>{o.replaceChildren();for(let z of W.blocks)if(z.kind==="text")z.value.length>0&&o.appendChild(document.createTextNode(z.value));else{n.set(z.id,z.ref);let H=e(z.ref);H.setAttribute("contenteditable","false"),H.setAttribute(jl,z.id),o.appendChild(H)}},d=()=>{let z=o.getRootNode().activeElement;return z===o||z!=null&&o.contains(z)},p=(W,z)=>{if(s=W,!z?.focus&&!d())return;let H=typeof window<"u"?window.getSelection():null;if(!H)return;let w=Ul(o,W);try{let k=document.createRange();k.setStart(w.node,w.offset),k.collapse(!0),H.removeAllRanges(),H.addRange(k)}catch{}},u=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},m=()=>{let W={start:s,end:s},z=typeof window<"u"?window.getSelection():null;if(!z||z.rangeCount===0)return W;let H=z.getRangeAt(0);if(!o.contains(H.startContainer))return W;let w=bS(o,H.startContainer,H.startOffset),k=H.collapsed?w:bS(o,H.endContainer,H.endOffset);return{start:Math.min(w,k),end:Math.max(w,k)}},h=()=>{let W=new Set;for(let z of Array.from(o.childNodes))Kl(z)&&W.add(z.getAttribute(jl));for(let z of Array.from(n.keys()))W.has(z)||(n.delete(z),t.onMentionRemoved?.(z))},g=()=>{r||n.size!==0&&h()},b=()=>{r=!0},C=()=>{r=!1,h()},S=W=>{W.preventDefault();let z=W.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,z);else{let{start:H,end:w}=m(),k=Jp(a(),H,w,z);l(k.doc),p(k.caret,{focus:!0}),h()}u()},I=W=>{if(r)return;let z=W.inputType;if(z==="insertParagraph"){W.preventDefault();let{start:Z,end:ie}=m(),se=Jp(a(),Z,ie,vS);l(se.doc),p(se.caret,{focus:!0}),n.size>0&&h(),u();return}if(z!=="deleteContentBackward"&&z!=="deleteContentForward"||n.size===0)return;let{start:H,end:w}=m();if(H!==w)return;let k=a(),R=Qp(k),_=z==="deleteContentBackward"?H-1:H;if(_<0||_>=R.length||R[_]!=="\uFFFC")return;let X=0,j=null;for(let Z of k.blocks){let ie=Z.kind==="text"?Z.value.length:1;if(Z.kind==="mention"&&_>=X&&_<X+ie){j=Z.id;break}X+=ie}if(!j)return;W.preventDefault();let Q=hS(k,j);l(Q.doc),p(Q.caret,{focus:!0}),h(),u()},E=(W,z)=>{l(_g(W)),p(z)},O=(W,z)=>{if(!Number.isFinite(W)||!Number.isFinite(z)||z<=W)return null;try{let H=Ul(o,W),w=Ul(o,z),k=document.createRange();k.setStart(H.node,H.offset),k.setEnd(w.node,w.offset);let R=k.getBoundingClientRect();return R.width===0&&R.height===0?null:R}catch{return null}},M=(W,z,H)=>{let w=Jp(a(),W,z,H);l(w.doc),p(w.caret,{focus:!0})},D=(W,z)=>{let H=a(),w=Qp(H),k=z.triggerIndex,R=z.triggerIndex+1+z.query.length;if(k<0||R>w.length||w.slice(k+1,R)!==z.query)return null;let _=t.generateId(),X=Fg(H,{start:k,end:R},W,_);return l(X.doc),p(X.caret,{focus:!0}),t.onMentionInserted?.(_,W),u(),_},L=W=>{let z=a(),H=m(),k=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:H.start,end:H.end}:{start:Xp(z),end:Xp(z)},R=t.generateId(),_=Fg(z,k,W,R);return l(_.doc),p(_.caret,{focus:!0}),t.onMentionInserted?.(R,W),u(),R},B=(W,z)=>{for(let H of Array.from(o.childNodes))if(Kl(H)&&H.getAttribute(jl)===W){let w=z==="error";if(H.classList.toggle(uI,w),w){H.hasAttribute(ql)||(H.setAttribute(ql,H.getAttribute("aria-label")??""),H.setAttribute(Vg,H.getAttribute("title")??""));let k=n.get(W)?.label??"";H.setAttribute("title",`${k}: failed to attach context`),H.setAttribute("aria-label",`${k}, failed to attach context`)}else if(H.hasAttribute(ql)){let k=H.getAttribute(ql),R=H.getAttribute(Vg);k?H.setAttribute("aria-label",k):H.removeAttribute("aria-label"),R?H.setAttribute("title",R):H.removeAttribute("title"),H.removeAttribute(ql),H.removeAttribute(Vg)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",b),o.addEventListener("compositionend",C),o.addEventListener("paste",S),o.addEventListener("beforeinput",I),l(gS()),{element:o,getValue:()=>Ng(a()),getLogicalText:()=>Qp(a()),getDocument:a,getSelection:m,setSelection:(W,z=W)=>{let H=typeof window<"u"?window.getSelection():null;if(H)try{let w=Ul(o,W),k=Ul(o,z),R=document.createRange();R.setStart(w.node,w.offset),R.setEnd(k.node,k.offset),H.removeAllRanges(),H.addRange(R)}catch{}},setValueWithCaret:E,getLogicalRangeRect:O,setValue:W=>{l(_g(W)),o.focus(),p(W.length,{focus:!0}),u()},replaceLogicalRange:M,insertMentionAtTrigger:D,insertMentionAtSelection:L,setMentionStatus:B,submit:()=>Vl(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",I)}}}var uI,jl,ql,Vg,vS,xS=we(()=>{"use strict";$g();Fp();uI="persona-mention-token-error",jl="data-mention-id",ql="data-mention-prev-label",Vg="data-mention-prev-title",vS=`
|
|
182
|
+
`});function yI(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 bI(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 SS(t){let{textarea:e}=t,n={generateId:hI,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=wS(n),r=o.element,s=e.getAttribute("aria-label")!=null;yI(e,r),bI(r,o,s),r.getInlineMessageFields=()=>yS(o.getDocument?.()??{blocks:[]});let a=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,a),{input:o,element:r,destroy:o.destroy}}var gI,hI,AS=we(()=>{"use strict";xS();$g();gI=0,hI=()=>`pmention-${++gI}`});var MS={};$n(MS,{mountInlineComposer:()=>SS});var TS=we(()=>{"use strict";AS()});function KS(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 lu(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function ir(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Hr(t,e){return ir(t)-t.scrollTop<=e}function cu(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 du(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 GS(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Gg(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 YS(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Yg=we(()=>{"use strict"});var Jl,_I,pu,NI,Jg,XS,ri,Zl,uu,FI,$I,Qg,VI,zI,qI,ec,mu,tc,QS,UI,Xg,jI,JS,nc,oc=we(()=>{"use strict";Jl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},_I=["pre","code","a","script","style"],pu=t=>({type:t?.type??Jl.type,placeholder:t?.placeholder??Jl.placeholder,speed:t?.speed??Jl.speed,duration:t?.duration??Jl.duration,buffer:t?.buffer??Jl.buffer}),NI=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Jg=new Map;for(let t of NI)Jg.set(t.name,t);XS=["wipe","glyph-cycle"],ri=t=>{Jg.set(t.name,t)},Zl=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Jg.get(t)??null,uu=(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
|
+
`);return s<0?"":t.slice(0,s)}return t},FI=(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},$I=(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},Qg=/\s/,VI=(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},zI=(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(Qg.test(s[l])){let d=l;for(;d<s.length&&Qg.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&&!Qg.test(s[p]);)d.appendChild(FI(o,s[p],e,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,t)},qI=(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($I(o,d,e,n.value)),n.value+=1));r.replaceChild(a,t)},ec=(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??_I).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)VI(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=e==="char"?zI:qI;for(let m of l)u(m,n,p);return r.innerHTML},mu=(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},tc=(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},QS=new WeakMap,UI=(t,e)=>{if(!t.styles)return;let n=QS.get(e);if(n||(n=new Set,QS.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)},Xg=new WeakMap,jI=(t,e)=>{if(!t.onAttach)return;let n=Xg.get(e);if(n||(n=new Map,Xg.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},JS=t=>{let e=Xg.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},nc=(t,e)=>{UI(t,e),jI(t,e)}});var KI,ZS,eA,tA=we(()=>{"use strict";oc();KI=`
|
|
184
184
|
@keyframes persona-stream-wipe {
|
|
185
185
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
186
186
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -216,7 +216,7 @@ ${e}
|
|
|
216
216
|
mask-image: none !important;
|
|
217
217
|
}
|
|
218
218
|
}
|
|
219
|
-
`.trim(),
|
|
219
|
+
`.trim(),ZS={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:KI};ri(ZS);eA=ZS});var GI,rc,YI,QI,Zg,XI,JI,ZI,cA,eh,eH,nA,oA,rA,tH,sA,iA,aA,nH,Ca,oH,rH,sH,dA,iH,lA,aH,pA,uA,mA=we(()=>{"use strict";oc();GI=`
|
|
220
220
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
221
221
|
animation: persona-stream-glyph-cycle-fade
|
|
222
222
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -234,13 +234,13 @@ ${e}
|
|
|
234
234
|
opacity: 1 !important;
|
|
235
235
|
}
|
|
236
236
|
}
|
|
237
|
-
`.trim(),oc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",VI=10,zI=120,Xg=120,qI=.4,UI=50,jI=t=>{if(!t)return Xg;let n=(t.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Xg},iA=t=>{let e=t.closest(".persona-stream-glyph-cycle"),n=jI(e);return zI*n/Xg},Jg=t=>{let e=oc[Math.floor(Math.random()*oc.length)];return t&&e===t&&(e=oc[(oc.indexOf(e)+1)%oc.length]),e},KI=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()<qI&&(r.textContent=Jg())}},ZS=new WeakMap,eA=25,tA=.5,GI=6,nA=.25,oA=new WeakMap,rA=new WeakMap,YI=(t,e)=>{if(!t)return eA*tA;let n=oA.get(t);oA.set(t,e);let o=rA.get(t)??eA;if(n!==void 0){let r=e-n;r>1&&(o=o*(1-nA)+r*nA,rA.set(t,o))}return Math.max(GI,o*tA)},va=new Map,QI=t=>t.closest("[data-message-id]")?.dataset.messageId??null,XI=t=>{t&&va.set(t,(va.get(t)??0)+1)},JI=t=>{if(!t)return;let e=va.get(t)??0;e<=1?va.delete(t):va.set(t,e-1)},aA=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=Jg();let n=QI(t);n&&(t.dataset.glyphCycleMessageId=n),XI(n);let o=t.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=YI(o,r),a=iA(t),l=VI*a,d=r+l;if(o){let p=ZS.get(o);p!==void 0&&(d=Math.max(d,p)),ZS.set(o,d+s)}ZI(t,e,d)},ZI=(t,e,n)=>{if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let o=iA(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,JI(t.dataset.glyphCycleMessageId??null),delete t.dataset.glyphCycleMessageId;return}let a=Jg(r);t.textContent=a,r=a,KI(t),setTimeout(s,o)};setTimeout(s,o)},sA=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))aA(n)},eH=t=>t.nodeType===1,lA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:$I,bufferContent(t){if(t.length<UI)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(va.get(t.id)??0)>0},onAttach(t){sA(t);let e=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))eH(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?aA(r):sA(r))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};ri(lA);cA=lA});var pA={};Fn(pA,{glyphCycle:()=>cA,wipe:()=>XS});var uA=we(()=>{"use strict";JS();dA()});function cc(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(ua)):(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 I=document.createElement("hr");l.appendChild(I)}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 I=He(b.icon,16,"currentColor",1.5);I&&C.appendChild(I)}let S=document.createElement("span");S.textContent=b.label,C.appendChild(S),C.addEventListener("click",I=>{I.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 sh=we(()=>{"use strict";Ue();Jt();us()});function gn(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=t,p=v("button",Bt(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=He(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 ai(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=He(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 mu(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 yA(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},I=r&&n?gn({...S,icon:n,size:o??14}):ai({...S,icon:n,iconSize:o??14}),E=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(I,E);let O=null,M=()=>{if(O)return O;let D=(typeof p=="function"?p():p)??void 0;return O=cc({items:s,onSelect:a,anchor:C,position:d,portal:D,onOpenChange:L=>{E.setAttribute("aria-expanded",L?"true":"false")}}),D||C.appendChild(O.element),O};return C.isConnected?M():requestAnimationFrame(()=>{O||M()}),E.addEventListener("click",D=>{D.stopPropagation(),M().toggle()}),{element:C,primaryButton:I,chevronButton:E,openMenu:()=>M().show(),closeMenu:()=>O?.hide(),toggleMenu:()=>M().toggle(),destroy:()=>{O?.destroy(),C.remove()}}}function bA(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=He(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=cc({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 li=we(()=>{"use strict";Ue();Jt();sh()});var ys,wu=we(()=>{"use strict";Ue();ys=(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 KA,Sh,Lu,Pu=we(()=>{"use strict";KA=()=>{},Sh=t=>{KA=t.webMcpToolTitle},Lu=t=>KA(t)});var ko,ci,di,GA,YA,QA,Ah,Mh,Th=we(()=>{"use strict";Ue();oi();Pu();ko=require("lucide");eo();ea();ci=new Map,di=t=>{let n=(t.startsWith(kr)?t.slice(kr.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)},GA=t=>t?.approval!==!1?t?.approval:void 0,YA=(t,e)=>{let n=GA(e)?.detailsDisplay??"collapsed";return ci.get(t)??n==="expanded"},QA=(t,e,n)=>{let o=GA(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=Ke(e?ko.ChevronUp:ko.ChevronDown,14,"currentColor",2);a&&s.appendChild(a)}},Ah=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=YA(t,n);QA(o,s,n),r.style.display=s?"":"none"},Mh=(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"?ko.ShieldX:n.status==="timeout"?ko.ShieldAlert:ko.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=Ke(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 B=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");B.setAttribute("data-approval-status",n.status),n.status==="approved"?(B.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",B.style.color="var(--persona-palette-colors-success-700, #15803d)",B.textContent="Approved"):n.status==="denied"?(B.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",B.style.color="var(--persona-palette-colors-error-700, #b91c1c)",B.textContent="Denied"):n.status==="timeout"&&(B.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",B.style.color="var(--persona-palette-colors-warning-700, #b45309)",B.textContent="Timeout"),h.appendChild(B)}m.appendChild(h);let C=n.toolType==="webmcp"||n.toolName.startsWith(kr)?Lu(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}:{}}),I=!n.toolName,E=S||(I?n.description:`The assistant wants to use \u201C${C??di(n.toolName)}\u201D.`),O=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(O.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(O.style.color=o.descriptionColor),O.textContent=E,m.appendChild(O),n.reason){let B=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");B.setAttribute("data-approval-reason","true"),o?.reasonColor?B.style.color=o.reasonColor:o?.descriptionColor&&(B.style.color=o.descriptionColor);let W=v("span","persona-font-medium");W.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,B.appendChild(W),B.appendChild(document.createTextNode(n.reason)),m.appendChild(B)}let M=o?.detailsDisplay??"collapsed",D=!!n.description&&!I,L=D||!!n.parameters;if(M!=="hidden"&&L){let B=YA(t.id,e),W=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");W.type="button",W.setAttribute("data-expand-header","true"),W.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(W.style.color=o.descriptionColor);let z=v("span");z.setAttribute("data-approval-details-label","true");let H=v("span","persona-inline-flex persona-items-center");H.setAttribute("data-approval-details-chevron","true"),W.append(z,H),QA(W,B,e),m.appendChild(W);let w=v("div");if(w.setAttribute("data-approval-details","true"),w.style.display=B?"":"none",D){let k=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=n.description,w.appendChild(k)}if(n.parameters){let k=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&&(k.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(k.style.color=o.parameterTextColor),k.style.fontSize="0.75rem",k.style.lineHeight="1rem",k.textContent=cs(n.parameters),w.appendChild(k)}m.appendChild(w)}if(r){let B=v("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");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-border-none persona-cursor-pointer");W.type="button",W.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",W.style.color=o?.approveButtonTextColor??"#ffffff",W.setAttribute("data-approval-action","approve");let z=Ke(ko.ShieldCheck,14,o?.approveButtonTextColor??"#ffffff",2);z&&(z.style.marginRight="4px",W.appendChild(z));let H=document.createTextNode(o?.approveLabel??"Approve");W.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 k=Ke(ko.ShieldX,14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);k&&(k.style.marginRight="4px",w.appendChild(k));let R=document.createTextNode(o?.denyLabel??"Deny");w.appendChild(R),B.append(W,w),m.appendChild(B)}return a.append(l,m),s.appendChild(a),s}});var ui,oR,XA,pi,rR,sR,Eh,iR,aR,lR,kh,JA=we(()=>{"use strict";Ue();Pu();ui=require("lucide");eo();oi();ea();ga();Th();oR=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),XA=(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))},pi=(t,e)=>{XA(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)},rR=t=>t?.approval!==!1?t?.approval:void 0,sR=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return ci.get(t)??n==="expanded"},Eh=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},iR=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(kr)?Lu(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??di(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},aR=t=>{let e=v("div","persona-approval-resolved"),n=Ke(ui.Ban,15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?di(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},lR=(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&&sR(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"),I=Ke(ui.ShieldCheck,16,"currentColor",2);I&&S.appendChild(I),C.appendChild(S);let E=iR(n,o);if(m){let W=v("span","persona-approval-toggle");W.setAttribute("aria-hidden","true");let z=Ke(ui.ChevronDown,14,"currentColor",2);z&&W.appendChild(z),E.append(" "),E.appendChild(W)}C.appendChild(E),l.appendChild(C);let O=v("div","persona-approval-body");if(m){let W=v("div","persona-approval-details");if(W.setAttribute("data-role","params"),W.hidden=!h,p){let z=v("p","persona-approval-desc");o?.descriptionColor&&(z.style.color=o.descriptionColor),z.textContent=n.description,W.appendChild(z)}if(u){let z=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(z.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(z.style.color=o.parameterTextColor),z.textContent=cs(n.parameters),W.appendChild(z)}O.appendChild(W)}if(n.reason){let W=v("p","persona-approval-reason");o?.reasonColor?W.style.color=o.reasonColor:o?.descriptionColor&&(W.style.color=o.descriptionColor);let z=v("span","persona-approval-reason-label");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,W.append(z,document.createTextNode(n.reason)),O.appendChild(W)}let M=v("div","persona-approval-actions"),D=null,L=W=>{o?.approveButtonColor&&(W.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(W.style.color=o.approveButtonTextColor)},B=v("button","persona-approval-deny");if(B.type="button",B.setAttribute("data-action","deny"),o?.denyButtonColor&&(B.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(B.style.color=o.denyButtonTextColor),B.append(o?.denyLabel??"Deny"),a){let W=v("div","persona-approval-split"),z=v("button","persona-approval-primary");z.type="button",z.setAttribute("data-action","always"),L(z),z.append(o?.approveLabel??"Always allow",Eh("\u23CE"));let H=v("button","persona-approval-caret");H.type="button",H.setAttribute("data-action","toggle-menu"),H.setAttribute("aria-label","More options"),L(H);let w=Ke(ui.ChevronDown,15,"currentColor",2);w&&H.appendChild(w),W.append(z,H),M.append(W,B),B.append(Eh("Esc"));let k=v("div","persona-approval-menu"),R=v("button","persona-approval-menu-item");R.type="button",R.append("Allow once",Eh("\u2318\u23CE")),k.appendChild(R),D=ms({anchor:W,content:k,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,D),R.addEventListener("click",()=>{pi(t,e.id),r()})}else{let W=v("button","persona-approval-primary persona-approval-primary--solo");W.type="button",W.setAttribute("data-action","allow"),L(W),W.append(o?.approveLabel??"Allow"),M.append(W,B)}return O.appendChild(M),l.appendChild(O),l.addEventListener("click",W=>{let z=W.target instanceof Element?W.target.closest("[data-action]"):null;if(!z)return;let H=z.getAttribute("data-action");if(H==="toggle-params"){let w=l.querySelector('[data-role="params"]');if(w){let k=w.hidden;w.hidden=!k,C.setAttribute("aria-expanded",k?"true":"false"),C.setAttribute("aria-label",k?b:g),ci.set(e.id,k)}return}if(H==="toggle-menu"){D?.toggle();return}if(H==="always"){pi(t,e.id),r({remember:!0});return}if(H==="allow"){pi(t,e.id),r();return}if(H==="deny"){pi(t,e.id),s();return}}),l},kh=()=>{let t=oR();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=rR(a);if(l.status!=="pending"){if(pi(t,o.id),l.status==="approved"){let m=document.createElement("div");return m.style.display="none",m}return aR(l)}XA(t,o.id);let p=d?.enableAlwaysAllow===!0,u=lR(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=>{ux(h)||o.id===t.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),pi(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()])pi(t,o);t.latestPendingApprovalId=null}}}});var ZA=we(()=>{"use strict";Th();JA();Pu()});var eM={};Fn(eM,{approvalDetailsExpansionState:()=>ci,createApprovalBubble:()=>Mh,createBuiltInApprovalPlugin:()=>kh,humanizeToolName:()=>di,initApprovalUi:()=>Sh,updateApprovalDetailsUI:()=>Ah});var tM=we(()=>{"use strict";ZA()});function Ta(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function gR(t,e){let n={...pR,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return uR}function hR(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function yR(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 bR(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 vR(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 CR(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 wR(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function xR(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 SR(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 Lh(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");Ta(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=Ke(d?kn.ChevronDown:kn.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]"),I=o.timestampFormat??"relative";S.textContent=I==="relative"?hR(t.timestamp,n):yR(t.timestamp);let E=null;o.showSequenceNumbers!==!1&&(E=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),E.textContent=String(e+1));let O=gR(t.type,o.badgeColors),M=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");M.style.backgroundColor=O.bg,M.style.color=O.text,M.style.borderColor=O.text+"50",M.textContent=t.type;let D=o.descriptionFields??mR,L=bR(t.payload,D),B=null;L&&(B=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=L);let W=v("div","persona-flex-1 persona-min-w-0"),z=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=Ke(kn.Clipboard,"12px","currentColor",1.5);return H&&z.appendChild(H),z.addEventListener("click",async w=>{w.stopPropagation(),await vR(CR(t)),z.innerHTML="";let k=Ke(kn.Check,"12px","currentColor",1.5);k&&z.appendChild(k),setTimeout(()=>{z.innerHTML="";let R=Ke(kn.Clipboard,"12px","currentColor",1.5);R&&z.appendChild(R)},1500)}),g.appendChild(b),g.appendChild(S),E&&g.appendChild(E),g.appendChild(M),B&&g.appendChild(B),g.appendChild(W),g.appendChild(z),h.appendChild(g),d&&h.appendChild(SR(t,a,l)),h}}function Ph(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");Ta(S,C?.panel);let I=[],E="",O="",M=null,D=[],L={},B=0,W=iu(),z=0,H=0,w=!1,k=null,R=!1,_=0,X=new Set,j=new Map,Q="",Z="",ie=null,se,pe,ue,xe,be=null,F=null,Ce=null;function Ee(){let J=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),re=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(Ta(re,C?.headerBar),a){F=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),F.style.cursor="help",be=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"),be.textContent="-- tok/s",Ce=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"),Ce.style.display="none",Ce.style.pointerEvents="none";let Hn=F,rn=Ce,st=()=>{if(!rn.textContent)return;let Yt=Hn.getBoundingClientRect(),Qe=J.getBoundingClientRect();rn.style.left=`${Yt.left-Qe.left}px`,rn.style.top=`${Yt.bottom-Qe.top+4}px`,rn.style.display="block"},Fe=()=>{rn.style.display="none"};F.addEventListener("mouseenter",st),F.addEventListener("mouseleave",Fe),F.appendChild(be)}let Le=v("div","persona-flex-1");se=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 Me=v("option","");Me.value="",Me.textContent="All events (0)",se.appendChild(Me),pe=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"),pe.type="button",pe.title="Copy All";let ct=Ke(kn.ClipboardCopy,"12px","currentColor",1.5);ct&&pe.appendChild(ct);let zt=v("span","persona-event-copy-all persona-text-xs");zt.textContent="Copy All",pe.appendChild(zt),F&&re.appendChild(F),re.appendChild(Le),re.appendChild(se),re.appendChild(pe);let ft=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ta(ft,C?.searchBar);let Je=Ke(kn.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");Je&&et.appendChild(Je),ue=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"),Ta(ue,C?.searchInput),ue.type="text",ue.placeholder="Search event payloads...",xe=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"),xe.type="button",xe.style.display="none";let xt=Ke(kn.X,"12px","currentColor",2);return xt&&xe.appendChild(xt),ft.appendChild(et),ft.appendChild(ue),ft.appendChild(xe),J.appendChild(re),J.appendChild(ft),Ce&&J.appendChild(Ce),J}let qe,ke=s.find(J=>J.renderEventStreamToolbar);ke?.renderEventStreamToolbar&&r?qe=ke.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ee(),eventCount:e.getSize(),filteredCount:0,onFilterChange:re=>{E=re,Ge(),Lt()},onSearchChange:re=>{O=re,Ge(),Lt()}})??Ee():qe=Ee();let Ie=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");Ie.style.display="none";function Te(){if(!a||!be||!F)return;let J=a(),re=wR(J);be.textContent=re;let Le=xR(J);Ce&&(Ce.textContent=Le,Le||(Ce.style.display="none")),F.setAttribute("aria-label",Le?`Throughput: ${re}, ${Le}`:`Throughput: ${re}`)}let vt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Ye=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Ye.style.height="100%";let Et=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");Ta(Et,C?.scrollIndicator),Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let je=l(u,"14px","currentColor",2);je&&Et.appendChild(je);let lt=v("span","");lt.textContent=m,Et.appendChild(lt);let Vt=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Vt.style.display="none",vt.appendChild(Ye),vt.appendChild(Vt),vt.appendChild(Et),S.setAttribute("tabindex","0"),S.appendChild(qe),S.appendChild(Ie),S.appendChild(vt);function It(){let J=e.getAll(),re={};for(let ft of J)re[ft.type]=(re[ft.type]||0)+1;let Le=Object.keys(re).sort(),Me=Le.length!==D.length||!Le.every((ft,Je)=>ft===D[Je]),mt=!Me&&Le.some(ft=>re[ft]!==L[ft]),ct=J.length!==Object.values(L).reduce((ft,Je)=>ft+Je,0);if(!Me&&!mt&&!ct||(D=Le,L=re,!se))return;let zt=se.value;if(se.options[0].textContent=`All events (${J.length})`,Me){for(;se.options.length>1;)se.remove(1);for(let ft of Le){let Je=v("option","");Je.value=ft,Je.textContent=`${ft} (${re[ft]||0})`,se.appendChild(Je)}zt&&Le.includes(zt)?se.value=zt:zt&&(se.value="",E="")}else for(let ft=1;ft<se.options.length;ft++){let Je=se.options[ft];Je.textContent=`${Je.value} (${re[Je.value]||0})`}}function Gt(){let J=e.getAll();if(E&&(J=J.filter(re=>re.type===E)),O){let re=O.toLowerCase();J=J.filter(Le=>Le.type.toLowerCase().includes(re)||Le.payload.toLowerCase().includes(re))}return J}function Ot(){return E!==""||O!==""}function Ge(){B=0,z=0,W.resume(),Et.style.display="none"}function hn(J){X.has(J)?X.delete(J):X.add(J),ie=J;let re=Ye.scrollTop,Le=W.isFollowing();R=!0,W.pause(),Lt(),Ye.scrollTop=re,Le&&W.resume(),R=!1}function Dt(){return Ir(Ye,50)}function Lt(){H=Date.now(),w=!1,Te(),It();let J=e.getEvictedCount();J>0?(Ie.textContent=`${J.toLocaleString()} older events truncated`,Ie.style.display=""):Ie.style.display="none",I=Gt();let re=I.length,Le=e.getSize()>0;re===0&&Le&&Ot()?(Vt.textContent=O?`No events matching '${O}'`:"No events matching filter",Vt.style.display="",Ye.style.display="none"):(Vt.style.display="none",Ye.style.display=""),pe&&(pe.title=Ot()?`Copy Filtered (${re})`:"Copy All"),p&&!W.isFollowing()&&re>B&&(z+=re-B,lt.textContent=m?`${m}${z>0?` (${z})`:""}`:"",Et.style.display=""),B=re;let Me=e.getAll(),mt=Me.length>0?Me[0].timestamp:0,ct=new Set(I.map(Je=>Je.id));for(let Je of X)ct.has(Je)||X.delete(Je);let zt=E!==Q||O!==Z,ft=j.size===0&&I.length>0;if(zt||ft||I.length===0){Ye.innerHTML="",j.clear();let Je=document.createDocumentFragment();for(let et=0;et<I.length;et++){let xt=Lh(I[et],et,mt,h,X,hn,s,r);j.set(I[et].id,xt),Je.appendChild(xt)}Ye.appendChild(Je),Q=E,Z=O,ie=null}else{if(ie!==null){let et=j.get(ie);if(et&&et.parentNode===Ye){let xt=I.findIndex(Hn=>Hn.id===ie);if(xt>=0){let Hn=Lh(I[xt],xt,mt,h,X,hn,s,r);Ye.insertBefore(Hn,et),et.remove(),j.set(ie,Hn)}}ie=null}let Je=new Set(I.map(et=>et.id));for(let[et,xt]of j)Je.has(et)||(xt.remove(),j.delete(et));for(let et=0;et<I.length;et++){let xt=I[et];if(!j.has(xt.id)){let Hn=Lh(xt,et,mt,h,X,hn,s,r);j.set(xt.id,Hn),Ye.appendChild(Hn)}}}W.isFollowing()&&(Ye.scrollTop=Ye.scrollHeight)}function jn(){if(Date.now()-H>=fR){k!==null&&(cancelAnimationFrame(k),k=null),Lt();return}w||(w=!0,k=requestAnimationFrame(()=>{k=null,Lt()}))}let rt=(J,re)=>{if(!pe)return;pe.innerHTML="";let Le=Ke(J,"12px","currentColor",1.5);Le&&pe.appendChild(Le);let Me=v("span","persona-text-xs");Me.textContent="Copy All",pe.appendChild(Me),setTimeout(()=>{pe.innerHTML="";let mt=Ke(kn.ClipboardCopy,"12px","currentColor",1.5);mt&&pe.appendChild(mt);let ct=v("span","persona-text-xs");ct.textContent="Copy All",pe.appendChild(ct),pe.disabled=!1},re)},Zt=async()=>{if(pe){pe.disabled=!0;try{let J;Ot()?J=I:n?(J=await n(),J.length===0&&(J=e.getAll())):J=e.getAll();let re=J.map(Le=>{try{return JSON.parse(Le.payload)}catch{return Le.payload}});await navigator.clipboard.writeText(JSON.stringify(re,null,2)),rt(kn.Check,1500)}catch{rt(kn.X,1500)}}},ln=()=>{se&&(E=se.value,Ge(),Lt())},K=()=>{!ue||!xe||(xe.style.display=ue.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{O=ue.value,Ge(),Lt()},150))},ae=()=>{!ue||!xe||(ue.value="",O="",xe.style.display="none",M&&clearTimeout(M),Ge(),Lt())},A=()=>{if(R)return;let J=Ye.scrollTop,{action:re,nextLastScrollTop:Le}=au({following:W.isFollowing(),currentScrollTop:J,lastScrollTop:_,nearBottom:Dt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});_=Le,re==="resume"?(W.resume(),z=0,Et.style.display="none"):re==="pause"&&(W.pause(),p&&(lt.textContent=m,Et.style.display=""))},T=J=>{let re=lu({following:W.isFollowing(),deltaY:J.deltaY,nearBottom:Dt(),resumeWhenNearBottom:!0});re==="pause"?(W.pause(),p&&(lt.textContent=m,Et.style.display="")):re==="resume"&&(W.resume(),z=0,Et.style.display="none")},V=()=>{p&&(Ye.scrollTop=Ye.scrollHeight,W.resume(),z=0,Et.style.display="none")},U=J=>{let re=J.target;if(!re||re.closest("button"))return;let Le=re.closest("[data-event-id]");if(!Le)return;let Me=Le.getAttribute("data-event-id");Me&&hn(Me)},ee=J=>{if((J.metaKey||J.ctrlKey)&&J.key==="f"){J.preventDefault(),ue?.focus(),ue?.select();return}J.key==="Escape"&&(ue&&document.activeElement===ue?(ae(),ue.blur(),S.focus()):o&&o())};pe&&pe.addEventListener("click",Zt),se&&se.addEventListener("change",ln),ue&&ue.addEventListener("input",K),xe&&xe.addEventListener("click",ae),Ye.addEventListener("scroll",A),Ye.addEventListener("wheel",T,{passive:!0}),Ye.addEventListener("click",U),Et.addEventListener("click",V),S.addEventListener("keydown",ee);function me(){M&&clearTimeout(M),k!==null&&(cancelAnimationFrame(k),k=null),w=!1,j.clear(),pe&&pe.removeEventListener("click",Zt),se&&se.removeEventListener("change",ln),ue&&ue.removeEventListener("input",K),xe&&xe.removeEventListener("click",ae),Ye.removeEventListener("scroll",A),Ye.removeEventListener("wheel",T),Ye.removeEventListener("click",U),Et.removeEventListener("click",V),S.removeEventListener("keydown",ee)}return{element:S,update:jn,destroy:me}}}var kn,pR,uR,mR,fR,rM=we(()=>{"use strict";Ue();kn=require("lucide");eo();Kg();pR={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},uR={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},mR=["flowName","stepName","reasoningText","text","name","tool","toolName"],fR=100});var mc,sM=we(()=>{"use strict";mc=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 fc,iM=we(()=>{"use strict";fc=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 Ih(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Iu(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function LR(t,e){return typeof e.type=="string"?e.type:t}function PR(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function IR(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function lM(t){let e=mi(t,"result"),n=[mi(t,"tokens"),mi(t,"totalTokens"),e?mi(e,"tokens"):void 0,mi(t,"usage"),e?mi(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=mo(o.output)??mo(o.outputTokens)??mo(o.completionTokens);if(r!==void 0)return r}return mo(t.outputTokens)??mo(t.completionTokens)??(e?mo(e.outputTokens)??mo(e.completionTokens):void 0)}function HR(t){let e=mi(t,"result");return mo(t.executionTime)??mo(t.executionTimeMs)??mo(t.execution_time)??mo(t.duration)??(e?mo(e.executionTime)??mo(e.executionTimeMs):void 0)}function RR(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var AR,MR,TR,ER,kR,aM,cM,mo,mi,gc,dM=we(()=>{"use strict";AR=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),MR=new Set(["step_start","execution_start"]),TR=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),ER=new Set(["step_complete","agent_turn_complete"]),kR=new Set(["flow_complete","agent_complete"]),aM=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),cM=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),mo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,mi=(t,e)=>{let n=t[e];return cM(n)?n:void 0};gc=class{constructor(e=RR){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:Iu(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(!cM(n)){aM.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=LR(e,n),r=this.now();if(AR.has(o)){this.startRun(r);return}if(MR.has(o)){this.run||this.startRun(r);return}if(TR.has(o)){if(!IR(o,n))return;let s=PR(n);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+Ih(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Iu(l,d),outputTokens:l,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(ER.has(o)){if(!this.run)return;let s=this.run,a=lM(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+Ih(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Iu(d,p),outputTokens:d,durationMs:p,source:l?"usage":"estimate"};return}if(kR.has(o)){if(!this.run)return;let s=this.run,a=lM(n),l=a??s.exactOutputTokens+Ih(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Iu(l,p),outputTokens:l,durationMs:p,source:d},this.run=null;return}if(aM.has(o)){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:HR(n)??o-e.startedAt}}});var pM=we(()=>{"use strict";rM();sM();iM();dM()});var uM={};Fn(uM,{EventStreamBuffer:()=>mc,EventStreamStore:()=>fc,ThroughputTracker:()=>gc,createEventStreamView:()=>Ph});var mM=we(()=>{"use strict";pM()});var Rh,No,hc=we(()=>{"use strict";Rh=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)})}},No=new Rh});function ar(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function fM(t){let e=ar(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Hu(t){if(typeof t!="string")return"";let e=t.indexOf(`
|
|
237
|
+
`.trim(),rc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",YI=10,QI=120,Zg=120,XI=.4,JI=50,ZI=t=>{if(!t)return Zg;let n=(t.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Zg},cA=t=>{let e=t.closest(".persona-stream-glyph-cycle"),n=ZI(e);return QI*n/Zg},eh=t=>{let e=rc[Math.floor(Math.random()*rc.length)];return t&&e===t&&(e=rc[(rc.indexOf(e)+1)%rc.length]),e},eH=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()<XI&&(r.textContent=eh())}},nA=new WeakMap,oA=25,rA=.5,tH=6,sA=.25,iA=new WeakMap,aA=new WeakMap,nH=(t,e)=>{if(!t)return oA*rA;let n=iA.get(t);iA.set(t,e);let o=aA.get(t)??oA;if(n!==void 0){let r=e-n;r>1&&(o=o*(1-sA)+r*sA,aA.set(t,o))}return Math.max(tH,o*rA)},Ca=new Map,oH=t=>t.closest("[data-message-id]")?.dataset.messageId??null,rH=t=>{t&&Ca.set(t,(Ca.get(t)??0)+1)},sH=t=>{if(!t)return;let e=Ca.get(t)??0;e<=1?Ca.delete(t):Ca.set(t,e-1)},dA=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=eh();let n=oH(t);n&&(t.dataset.glyphCycleMessageId=n),rH(n);let o=t.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=nH(o,r),a=cA(t),l=YI*a,d=r+l;if(o){let p=nA.get(o);p!==void 0&&(d=Math.max(d,p)),nA.set(o,d+s)}iH(t,e,d)},iH=(t,e,n)=>{if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let o=cA(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,sH(t.dataset.glyphCycleMessageId??null),delete t.dataset.glyphCycleMessageId;return}let a=eh(r);t.textContent=a,r=a,eH(t),setTimeout(s,o)};setTimeout(s,o)},lA=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))dA(n)},aH=t=>t.nodeType===1,pA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:GI,bufferContent(t){if(t.length<JI)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(Ca.get(t.id)??0)>0},onAttach(t){lA(t);let e=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))aH(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?dA(r):lA(r))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};ri(pA);uA=pA});var fA={};$n(fA,{glyphCycle:()=>uA,wipe:()=>eA});var gA=we(()=>{"use strict";tA();mA()});function dc(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(ma)):(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 I=document.createElement("hr");l.appendChild(I)}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 I=He(b.icon,16,"currentColor",1.5);I&&C.appendChild(I)}let S=document.createElement("span");S.textContent=b.label,C.appendChild(S),C.addEventListener("click",I=>{I.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 ah=we(()=>{"use strict";qe();en();us()});function yn(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=t,p=v("button",Dt(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=He(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 ai(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=He(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 gu(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=yn({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 CA(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},I=r&&n?yn({...S,icon:n,size:o??14}):ai({...S,icon:n,iconSize:o??14}),E=yn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(I,E);let O=null,M=()=>{if(O)return O;let D=(typeof p=="function"?p():p)??void 0;return O=dc({items:s,onSelect:a,anchor:C,position:d,portal:D,onOpenChange:L=>{E.setAttribute("aria-expanded",L?"true":"false")}}),D||C.appendChild(O.element),O};return C.isConnected?M():requestAnimationFrame(()=>{O||M()}),E.addEventListener("click",D=>{D.stopPropagation(),M().toggle()}),{element:C,primaryButton:I,chevronButton:E,openMenu:()=>M().show(),closeMenu:()=>O?.hide(),toggleMenu:()=>M().toggle(),destroy:()=>{O?.destroy(),C.remove()}}}function wA(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=He(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=dc({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 li=we(()=>{"use strict";qe();en();ah()});var ys,Su=we(()=>{"use strict";qe();ys=(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 QA,Mh,Iu,Hu=we(()=>{"use strict";QA=()=>{},Mh=t=>{QA=t.webMcpToolTitle},Iu=t=>QA(t)});var Lo,ci,di,XA,JA,ZA,Th,Eh,kh=we(()=>{"use strict";qe();oi();Hu();Lo=require("lucide");to();ta();ci=new Map,di=t=>{let n=(t.startsWith(Lr)?t.slice(Lr.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)},XA=t=>t?.approval!==!1?t?.approval:void 0,JA=(t,e)=>{let n=XA(e)?.detailsDisplay??"collapsed";return ci.get(t)??n==="expanded"},ZA=(t,e,n)=>{let o=XA(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=Ke(e?Lo.ChevronUp:Lo.ChevronDown,14,"currentColor",2);a&&s.appendChild(a)}},Th=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=JA(t,n);ZA(o,s,n),r.style.display=s?"":"none"},Eh=(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=Ke(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 B=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");B.setAttribute("data-approval-status",n.status),n.status==="approved"?(B.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",B.style.color="var(--persona-palette-colors-success-700, #15803d)",B.textContent="Approved"):n.status==="denied"?(B.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",B.style.color="var(--persona-palette-colors-error-700, #b91c1c)",B.textContent="Denied"):n.status==="timeout"&&(B.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",B.style.color="var(--persona-palette-colors-warning-700, #b45309)",B.textContent="Timeout"),h.appendChild(B)}m.appendChild(h);let C=n.toolType==="webmcp"||n.toolName.startsWith(Lr)?Iu(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}:{}}),I=!n.toolName,E=S||(I?n.description:`The assistant wants to use \u201C${C??di(n.toolName)}\u201D.`),O=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(O.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(O.style.color=o.descriptionColor),O.textContent=E,m.appendChild(O),n.reason){let B=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");B.setAttribute("data-approval-reason","true"),o?.reasonColor?B.style.color=o.reasonColor:o?.descriptionColor&&(B.style.color=o.descriptionColor);let W=v("span","persona-font-medium");W.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,B.appendChild(W),B.appendChild(document.createTextNode(n.reason)),m.appendChild(B)}let M=o?.detailsDisplay??"collapsed",D=!!n.description&&!I,L=D||!!n.parameters;if(M!=="hidden"&&L){let B=JA(t.id,e),W=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");W.type="button",W.setAttribute("data-expand-header","true"),W.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(W.style.color=o.descriptionColor);let z=v("span");z.setAttribute("data-approval-details-label","true");let H=v("span","persona-inline-flex persona-items-center");H.setAttribute("data-approval-details-chevron","true"),W.append(z,H),ZA(W,B,e),m.appendChild(W);let w=v("div");if(w.setAttribute("data-approval-details","true"),w.style.display=B?"":"none",D){let k=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=n.description,w.appendChild(k)}if(n.parameters){let k=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&&(k.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(k.style.color=o.parameterTextColor),k.style.fontSize="0.75rem",k.style.lineHeight="1rem",k.textContent=cs(n.parameters),w.appendChild(k)}m.appendChild(w)}if(r){let B=v("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");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-border-none persona-cursor-pointer");W.type="button",W.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",W.style.color=o?.approveButtonTextColor??"#ffffff",W.setAttribute("data-approval-action","approve");let z=Ke(Lo.ShieldCheck,14,o?.approveButtonTextColor??"#ffffff",2);z&&(z.style.marginRight="4px",W.appendChild(z));let H=document.createTextNode(o?.approveLabel??"Approve");W.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 k=Ke(Lo.ShieldX,14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);k&&(k.style.marginRight="4px",w.appendChild(k));let R=document.createTextNode(o?.denyLabel??"Deny");w.appendChild(R),B.append(W,w),m.appendChild(B)}return a.append(l,m),s.appendChild(a),s}});var ui,dR,eM,pi,pR,uR,Lh,mR,fR,gR,Ph,tM=we(()=>{"use strict";qe();Hu();ui=require("lucide");to();oi();ta();ha();kh();dR=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),eM=(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))},pi=(t,e)=>{eM(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)},pR=t=>t?.approval!==!1?t?.approval:void 0,uR=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return ci.get(t)??n==="expanded"},Lh=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},mR=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Lr)?Iu(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??di(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},fR=t=>{let e=v("div","persona-approval-resolved"),n=Ke(ui.Ban,15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?di(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},gR=(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&&uR(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"),I=Ke(ui.ShieldCheck,16,"currentColor",2);I&&S.appendChild(I),C.appendChild(S);let E=mR(n,o);if(m){let W=v("span","persona-approval-toggle");W.setAttribute("aria-hidden","true");let z=Ke(ui.ChevronDown,14,"currentColor",2);z&&W.appendChild(z),E.append(" "),E.appendChild(W)}C.appendChild(E),l.appendChild(C);let O=v("div","persona-approval-body");if(m){let W=v("div","persona-approval-details");if(W.setAttribute("data-role","params"),W.hidden=!h,p){let z=v("p","persona-approval-desc");o?.descriptionColor&&(z.style.color=o.descriptionColor),z.textContent=n.description,W.appendChild(z)}if(u){let z=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(z.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(z.style.color=o.parameterTextColor),z.textContent=cs(n.parameters),W.appendChild(z)}O.appendChild(W)}if(n.reason){let W=v("p","persona-approval-reason");o?.reasonColor?W.style.color=o.reasonColor:o?.descriptionColor&&(W.style.color=o.descriptionColor);let z=v("span","persona-approval-reason-label");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,W.append(z,document.createTextNode(n.reason)),O.appendChild(W)}let M=v("div","persona-approval-actions"),D=null,L=W=>{o?.approveButtonColor&&(W.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(W.style.color=o.approveButtonTextColor)},B=v("button","persona-approval-deny");if(B.type="button",B.setAttribute("data-action","deny"),o?.denyButtonColor&&(B.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(B.style.color=o.denyButtonTextColor),B.append(o?.denyLabel??"Deny"),a){let W=v("div","persona-approval-split"),z=v("button","persona-approval-primary");z.type="button",z.setAttribute("data-action","always"),L(z),z.append(o?.approveLabel??"Always allow",Lh("\u23CE"));let H=v("button","persona-approval-caret");H.type="button",H.setAttribute("data-action","toggle-menu"),H.setAttribute("aria-label","More options"),L(H);let w=Ke(ui.ChevronDown,15,"currentColor",2);w&&H.appendChild(w),W.append(z,H),M.append(W,B),B.append(Lh("Esc"));let k=v("div","persona-approval-menu"),R=v("button","persona-approval-menu-item");R.type="button",R.append("Allow once",Lh("\u2318\u23CE")),k.appendChild(R),D=ms({anchor:W,content:k,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,D),R.addEventListener("click",()=>{pi(t,e.id),r()})}else{let W=v("button","persona-approval-primary persona-approval-primary--solo");W.type="button",W.setAttribute("data-action","allow"),L(W),W.append(o?.approveLabel??"Allow"),M.append(W,B)}return O.appendChild(M),l.appendChild(O),l.addEventListener("click",W=>{let z=W.target instanceof Element?W.target.closest("[data-action]"):null;if(!z)return;let H=z.getAttribute("data-action");if(H==="toggle-params"){let w=l.querySelector('[data-role="params"]');if(w){let k=w.hidden;w.hidden=!k,C.setAttribute("aria-expanded",k?"true":"false"),C.setAttribute("aria-label",k?b:g),ci.set(e.id,k)}return}if(H==="toggle-menu"){D?.toggle();return}if(H==="always"){pi(t,e.id),r({remember:!0});return}if(H==="allow"){pi(t,e.id),r();return}if(H==="deny"){pi(t,e.id),s();return}}),l},Ph=()=>{let t=dR();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=pR(a);if(l.status!=="pending"){if(pi(t,o.id),l.status==="approved"){let m=document.createElement("div");return m.style.display="none",m}return fR(l)}eM(t,o.id);let p=d?.enableAlwaysAllow===!0,u=gR(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=>{gx(h)||o.id===t.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),pi(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()])pi(t,o);t.latestPendingApprovalId=null}}}});var nM=we(()=>{"use strict";kh();tM();Hu()});var oM={};$n(oM,{approvalDetailsExpansionState:()=>ci,createApprovalBubble:()=>Eh,createBuiltInApprovalPlugin:()=>Ph,humanizeToolName:()=>di,initApprovalUi:()=>Mh,updateApprovalDetailsUI:()=>Th});var rM=we(()=>{"use strict";nM()});function Ea(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function aM(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 wR(t,e){return(e&&aM(t,e))??aM(t,Hh)??bR}function xR(t){return/^#[0-9a-fA-F]{6}$/.test(t)?`${t}50`:`color-mix(in srgb, ${t} 31%, transparent)`}function SR(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function AR(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 MR(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 TR(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 ER(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 kR(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function LR(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 PR(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 Ih(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");Ea(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=Ke(d?Ln.ChevronDown:Ln.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]"),I=o.timestampFormat??"relative";S.textContent=I==="relative"?SR(t.timestamp,n):AR(t.timestamp);let E=null;o.showSequenceNumbers!==!1&&(E=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),E.textContent=String(e+1));let O=wR(t.type,o.badgeColors),M=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");M.style.backgroundColor=O.bg,M.style.color=O.text,M.style.borderColor=xR(O.text),M.textContent=t.type;let D=o.descriptionFields??vR,L=MR(t.payload,D),B=null;L&&(B=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=L);let W=v("div","persona-flex-1 persona-min-w-0"),z=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=Ke(Ln.Clipboard,"12px","currentColor",1.5);return H&&z.appendChild(H),z.addEventListener("click",async w=>{w.stopPropagation(),await TR(ER(t)),z.innerHTML="";let k=Ke(Ln.Check,"12px","currentColor",1.5);k&&z.appendChild(k),setTimeout(()=>{z.innerHTML="";let R=Ke(Ln.Clipboard,"12px","currentColor",1.5);R&&z.appendChild(R)},1500)}),g.appendChild(b),g.appendChild(S),E&&g.appendChild(E),g.appendChild(M),B&&g.appendChild(B),g.appendChild(W),g.appendChild(z),h.appendChild(g),d&&h.appendChild(PR(t,a,l)),h}}function Rh(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");Ea(S,C?.panel);let I=[],E="",O="",M=null,D=[],L={},B=0,W=lu(),z=0,H=0,w=!1,k=null,R=!1,_=0,X=new Set,j=new Map,Q="",Z="",ie=null,se,pe,ue,xe,be=null,F=null,Ce=null;function Ee(){let J=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),re=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(Ea(re,C?.headerBar),a){F=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),F.style.cursor="help",be=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"),be.textContent="-- tok/s",Ce=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"),Ce.style.display="none",Ce.style.pointerEvents="none";let Wn=F,an=Ce,rt=()=>{if(!an.textContent)return;let Xt=Wn.getBoundingClientRect(),Qe=J.getBoundingClientRect();an.style.left=`${Xt.left-Qe.left}px`,an.style.top=`${Xt.bottom-Qe.top+4}px`,an.style.display="block"},_e=()=>{an.style.display="none"};F.addEventListener("mouseenter",rt),F.addEventListener("mouseleave",_e),F.appendChild(be)}let Le=v("div","persona-flex-1");se=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 Me=v("option","");Me.value="",Me.textContent="All events (0)",se.appendChild(Me),pe=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"),pe.type="button",pe.title="Copy All";let lt=Ke(Ln.ClipboardCopy,"12px","currentColor",1.5);lt&&pe.appendChild(lt);let jt=v("span","persona-event-copy-all persona-text-xs");jt.textContent="Copy All",pe.appendChild(jt),F&&re.appendChild(F),re.appendChild(Le),re.appendChild(se),re.appendChild(pe);let mt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ea(mt,C?.searchBar);let Ze=Ke(Ln.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");Ze&&et.appendChild(Ze),ue=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"),Ea(ue,C?.searchInput),ue.type="text",ue.placeholder="Search event payloads...",xe=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"),xe.type="button",xe.style.display="none";let wt=Ke(Ln.X,"12px","currentColor",2);return wt&&xe.appendChild(wt),mt.appendChild(et),mt.appendChild(ue),mt.appendChild(xe),J.appendChild(re),J.appendChild(mt),Ce&&J.appendChild(Ce),J}let Ve,ke=s.find(J=>J.renderEventStreamToolbar);ke?.renderEventStreamToolbar&&r?Ve=ke.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ee(),eventCount:e.getSize(),filteredCount:0,onFilterChange:re=>{E=re,Ge(),Pt()},onSearchChange:re=>{O=re,Ge(),Pt()}})??Ee():Ve=Ee();let Ie=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");Ie.style.display="none";function Te(){if(!a||!be||!F)return;let J=a(),re=kR(J);be.textContent=re;let Le=LR(J);Ce&&(Ce.textContent=Le,Le||(Ce.style.display="none")),F.setAttribute("aria-label",Le?`Throughput: ${re}, ${Le}`:`Throughput: ${re}`)}let bt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Ye=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Ye.style.height="100%";let Et=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");Ea(Et,C?.scrollIndicator),Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ue=l(u,"14px","currentColor",2);Ue&&Et.appendChild(Ue);let at=v("span","");at.textContent=m,Et.appendChild(at);let Ut=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ut.style.display="none",bt.appendChild(Ye),bt.appendChild(Ut),bt.appendChild(Et),S.setAttribute("tabindex","0"),S.appendChild(Ve),S.appendChild(Ie),S.appendChild(bt);function Ht(){let J=e.getAll(),re={};for(let mt of J)re[mt.type]=(re[mt.type]||0)+1;let Le=Object.keys(re).sort(),Me=Le.length!==D.length||!Le.every((mt,Ze)=>mt===D[Ze]),ut=!Me&&Le.some(mt=>re[mt]!==L[mt]),lt=J.length!==Object.values(L).reduce((mt,Ze)=>mt+Ze,0);if(!Me&&!ut&&!lt||(D=Le,L=re,!se))return;let jt=se.value;if(se.options[0].textContent=`All events (${J.length})`,Me){for(;se.options.length>1;)se.remove(1);for(let mt of Le){let Ze=v("option","");Ze.value=mt,Ze.textContent=`${mt} (${re[mt]||0})`,se.appendChild(Ze)}jt&&Le.includes(jt)?se.value=jt:jt&&(se.value="",E="")}else for(let mt=1;mt<se.options.length;mt++){let Ze=se.options[mt];Ze.textContent=`${Ze.value} (${re[Ze.value]||0})`}}function Qt(){let J=e.getAll();if(E&&(J=J.filter(re=>re.type===E)),O){let re=O.toLowerCase();J=J.filter(Le=>Le.type.toLowerCase().includes(re)||Le.payload.toLowerCase().includes(re))}return J}function _t(){return E!==""||O!==""}function Ge(){B=0,z=0,W.resume(),Et.style.display="none"}function bn(J){X.has(J)?X.delete(J):X.add(J),ie=J;let re=Ye.scrollTop,Le=W.isFollowing();R=!0,W.pause(),Pt(),Ye.scrollTop=re,Le&&W.resume(),R=!1}function Nt(){return Hr(Ye,50)}function Pt(){H=Date.now(),w=!1,Te(),Ht();let J=e.getEvictedCount();J>0?(Ie.textContent=`${J.toLocaleString()} older events truncated`,Ie.style.display=""):Ie.style.display="none",I=Qt();let re=I.length,Le=e.getSize()>0;re===0&&Le&&_t()?(Ut.textContent=O?`No events matching '${O}'`:"No events matching filter",Ut.style.display="",Ye.style.display="none"):(Ut.style.display="none",Ye.style.display=""),pe&&(pe.title=_t()?`Copy Filtered (${re})`:"Copy All"),p&&!W.isFollowing()&&re>B&&(z+=re-B,at.textContent=m?`${m}${z>0?` (${z})`:""}`:"",Et.style.display=""),B=re;let Me=e.getAll(),ut=Me.length>0?Me[0].timestamp:0,lt=new Set(I.map(Ze=>Ze.id));for(let Ze of X)lt.has(Ze)||X.delete(Ze);let jt=E!==Q||O!==Z,mt=j.size===0&&I.length>0;if(jt||mt||I.length===0){Ye.innerHTML="",j.clear();let Ze=document.createDocumentFragment();for(let et=0;et<I.length;et++){let wt=Ih(I[et],et,ut,h,X,bn,s,r);j.set(I[et].id,wt),Ze.appendChild(wt)}Ye.appendChild(Ze),Q=E,Z=O,ie=null}else{if(ie!==null){let et=j.get(ie);if(et&&et.parentNode===Ye){let wt=I.findIndex(Wn=>Wn.id===ie);if(wt>=0){let Wn=Ih(I[wt],wt,ut,h,X,bn,s,r);Ye.insertBefore(Wn,et),et.remove(),j.set(ie,Wn)}}ie=null}let Ze=new Set(I.map(et=>et.id));for(let[et,wt]of j)Ze.has(et)||(wt.remove(),j.delete(et));for(let et=0;et<I.length;et++){let wt=I[et];if(!j.has(wt.id)){let Wn=Ih(wt,et,ut,h,X,bn,s,r);j.set(wt.id,Wn),Ye.appendChild(Wn)}}}W.isFollowing()&&(Ye.scrollTop=Ye.scrollHeight)}function Kn(){if(Date.now()-H>=CR){k!==null&&(cancelAnimationFrame(k),k=null),Pt();return}w||(w=!0,k=requestAnimationFrame(()=>{k=null,Pt()}))}let nt=(J,re)=>{if(!pe)return;pe.innerHTML="";let Le=Ke(J,"12px","currentColor",1.5);Le&&pe.appendChild(Le);let Me=v("span","persona-text-xs");Me.textContent="Copy All",pe.appendChild(Me),setTimeout(()=>{pe.innerHTML="";let ut=Ke(Ln.ClipboardCopy,"12px","currentColor",1.5);ut&&pe.appendChild(ut);let lt=v("span","persona-text-xs");lt.textContent="Copy All",pe.appendChild(lt),pe.disabled=!1},re)},tn=async()=>{if(pe){pe.disabled=!0;try{let J;_t()?J=I:n?(J=await n(),J.length===0&&(J=e.getAll())):J=e.getAll();let re=J.map(Le=>{try{return JSON.parse(Le.payload)}catch{return Le.payload}});await navigator.clipboard.writeText(JSON.stringify(re,null,2)),nt(Ln.Check,1500)}catch{nt(Ln.X,1500)}}},dn=()=>{se&&(E=se.value,Ge(),Pt())},G=()=>{!ue||!xe||(xe.style.display=ue.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{O=ue.value,Ge(),Pt()},150))},ae=()=>{!ue||!xe||(ue.value="",O="",xe.style.display="none",M&&clearTimeout(M),Ge(),Pt())},A=()=>{if(R)return;let J=Ye.scrollTop,{action:re,nextLastScrollTop:Le}=cu({following:W.isFollowing(),currentScrollTop:J,lastScrollTop:_,nearBottom:Nt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});_=Le,re==="resume"?(W.resume(),z=0,Et.style.display="none"):re==="pause"&&(W.pause(),p&&(at.textContent=m,Et.style.display=""))},T=J=>{let re=du({following:W.isFollowing(),deltaY:J.deltaY,nearBottom:Nt(),resumeWhenNearBottom:!0});re==="pause"?(W.pause(),p&&(at.textContent=m,Et.style.display="")):re==="resume"&&(W.resume(),z=0,Et.style.display="none")},V=()=>{p&&(Ye.scrollTop=Ye.scrollHeight,W.resume(),z=0,Et.style.display="none")},U=J=>{let re=J.target;if(!re||re.closest("button"))return;let Le=re.closest("[data-event-id]");if(!Le)return;let Me=Le.getAttribute("data-event-id");Me&&bn(Me)},ee=J=>{if((J.metaKey||J.ctrlKey)&&J.key==="f"){J.preventDefault(),ue?.focus(),ue?.select();return}J.key==="Escape"&&(ue&&document.activeElement===ue?(ae(),ue.blur(),S.focus()):o&&o())};pe&&pe.addEventListener("click",tn),se&&se.addEventListener("change",dn),ue&&ue.addEventListener("input",G),xe&&xe.addEventListener("click",ae),Ye.addEventListener("scroll",A),Ye.addEventListener("wheel",T,{passive:!0}),Ye.addEventListener("click",U),Et.addEventListener("click",V),S.addEventListener("keydown",ee);function me(){M&&clearTimeout(M),k!==null&&(cancelAnimationFrame(k),k=null),w=!1,j.clear(),pe&&pe.removeEventListener("click",tn),se&&se.removeEventListener("change",dn),ue&&ue.removeEventListener("input",G),xe&&xe.removeEventListener("click",ae),Ye.removeEventListener("scroll",A),Ye.removeEventListener("wheel",T),Ye.removeEventListener("click",U),Et.removeEventListener("click",V),S.removeEventListener("keydown",ee)}return{element:S,update:Kn,destroy:me}}}var Ln,Hh,bR,vR,CR,lM=we(()=>{"use strict";qe();Ln=require("lucide");to();Yg();Hh={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)"}};Hh.execution_error=Hh.error;bR={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},vR=["flowName","stepName","reasoningText","text","name","tool","toolName"],CR=100});var fc,cM=we(()=>{"use strict";fc=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 gc,dM=we(()=>{"use strict";gc=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 Wh(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ru(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 DR(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function _R(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function uM(t){let e=mi(t,"result"),n=[mi(t,"tokens"),mi(t,"totalTokens"),e?mi(e,"tokens"):void 0,mi(t,"usage"),e?mi(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=fo(o.output)??fo(o.outputTokens)??fo(o.completionTokens);if(r!==void 0)return r}return fo(t.outputTokens)??fo(t.completionTokens)??(e?fo(e.outputTokens)??fo(e.completionTokens):void 0)}function NR(t){let e=mi(t,"result");return fo(t.executionTime)??fo(t.executionTimeMs)??fo(t.execution_time)??fo(t.duration)??(e?fo(e.executionTime)??fo(e.executionTimeMs):void 0)}function FR(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var IR,HR,RR,WR,BR,pM,mM,fo,mi,hc,fM=we(()=>{"use strict";IR=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),HR=new Set(["step_start","execution_start"]),RR=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),WR=new Set(["step_complete","agent_turn_complete"]),BR=new Set(["flow_complete","agent_complete"]),pM=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),mM=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,mi=(t,e)=>{let n=t[e];return mM(n)?n:void 0};hc=class{constructor(e=FR){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:Ru(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(!mM(n)){pM.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=OR(e,n),r=this.now();if(IR.has(o)){this.startRun(r);return}if(HR.has(o)){this.run||this.startRun(r);return}if(RR.has(o)){if(!_R(o,n))return;let s=DR(n);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+Wh(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ru(l,d),outputTokens:l,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(WR.has(o)){if(!this.run)return;let s=this.run,a=uM(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+Wh(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ru(d,p),outputTokens:d,durationMs:p,source:l?"usage":"estimate"};return}if(BR.has(o)){if(!this.run)return;let s=this.run,a=uM(n),l=a??s.exactOutputTokens+Wh(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ru(l,p),outputTokens:l,durationMs:p,source:d},this.run=null;return}if(pM.has(o)){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:NR(n)??o-e.startedAt}}});var gM=we(()=>{"use strict";lM();cM();dM();fM()});var hM={};$n(hM,{EventStreamBuffer:()=>fc,EventStreamStore:()=>gc,ThroughputTracker:()=>hc,createEventStreamView:()=>Rh});var yM=we(()=>{"use strict";gM()});var Oh,Fo,yc=we(()=>{"use strict";Oh=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)})}},Fo=new Oh});function ar(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function bM(t){let e=ar(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Wu(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 fi(t){let e=
|
|
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
|
|
239
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function fi(t){let e=bM(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 bs(t){switch(fi(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=bM(t.path);return e?e.toUpperCase():"File"}}}function bc(t){let e=t.markdown??"";return t.file?{filename:ar(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Wu(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}function vc(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 gi=we(()=>{"use strict"});function ka(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 "+Bu+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+Bu+(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=ai({icon:t.icon,label:t.label,className:Bu+(n?" persona-artifact-doc-copy-btn":"")}):o=yn({icon:t.icon,label:t.label,className:Bu+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Cc(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 Bu,Ou=we(()=>{"use strict";li();qe();Bu="persona-artifact-custom-action-btn"});function vM(t){let e=document.createElementNS(Dh,"svg");e.setAttribute("class",Dt("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Dh,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Dh,"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 Dh,CM=we(()=>{"use strict";qe();Dh="http://www.w3.org/2000/svg"});function wM(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)),ys(t,e,0)}var xM=we(()=>{"use strict";Su()});function La(t){t&&Nh.delete(t)}function VR(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?bs(e):t.artifactType==="component"?"Component":"Document"}function Pa(t,e,n){let o=VR(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=Nh.get(a);t.status!=="complete"&&l===void 0&&(l=MM(),Nh.set(a,l));let d=l===void 0?0:Math.max(0,MM()-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
|
+
`).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 zR(t){t.className=_h,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 hi(t,e,n){let o=t.querySelector(`:scope > .${_h}`);o||(o=v("span",_h),t.appendChild(o)),o.getAttribute(AM)!==e.label&&(zR(o),wM(o,e.label,n),o.setAttribute(AM,e.label));let r=t.querySelector(`:scope > .${SM}`),s=e.detail;s?(r||(r=v("span",SM),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var _h,SM,AM,Nh,MM,Du=we(()=>{"use strict";qe();gi();xM();_h="persona-artifact-status-label",SM="persona-artifact-status-detail",AM="data-artifact-status-label",Nh=new Map,MM=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()});function jR(t,e){let n=(t||"").trim().toLowerCase();if(n&&_u[n])return _u[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(_u[r])return _u[r]}}return null}function Nu(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 TM(t){return Nu(t,GR)}function QR(t){let e=Nu(t,YR);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 EM(t){let e=Nu(t,XR),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 ZR(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 Nu(d,JR))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"?TM(b):EM(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 eW(t,e){switch(e){case"html":return ZR(t);case"css":return EM(t);case"js":return TM(t);case"json":return QR(t)}}function tW(t){let e=NC(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=qR[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
|
-
`)),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
|
|
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 oW(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(gM());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 rW(t,e,n,o,r,s){let a=null,l=0,d=!1,p=new Set,u=()=>{p.forEach(O=>clearTimeout(O)),p.clear()},m=(O,M)=>{let D=setTimeout(()=>{p.delete(D),O()},M);p.add(D)},h=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||d)return;let O=oW(r,s,o);a=O.el,t.appendChild(a),l=Date.now(),o.label!==!1&&m(O.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),m(h,eW))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",I):e.removeEventListener("load",E)},S=()=>{if(d||(d=!0,C(),u(),!a))return;let O=Math.max(0,o.minVisibleMs-(Date.now()-l));O>0?m(b,O):b()};function I(O){if(n===null)return;let M=O.data;!M||M.persona!=="artifact-preview-ready"||M.token!==n||O.source===e.contentWindow&&S()}function E(){let O=M=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>M()):setTimeout(M,0)};O(()=>O(()=>S()))}return m(g,o.delayMs),m(S,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",I):e.addEventListener("load",E),()=>{d=!0,u(),C(),h()}}function _u(t,e){let{config:n}=e,o=e.registry??EM()??No,r=e.bodyLayout,s=n.markdown?jd(n.markdown):null,a=Gd(n.sanitize),l=t,d=!1,p=Q=>{let Z=So()!==null;s&&!Z&&!d&&(d=!0,Ji(()=>j(l)));let ie=s?s(Q):Er(Q);return s&&Z&&a?a(ie):ie},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,I=null,E=!1,O=()=>{C=null,S=null,I=null,E=!1},M=null,D=null,L=()=>{M=null,D=null},B=40,W=0,z=Q=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Q()):setTimeout(Q,0),H=Q=>Q.scrollHeight-Q.clientHeight-Q.scrollTop<=B,w=Q=>{if(!r)return;let Z=Q.scrollHeight-Q.clientHeight>1,ie=Q.scrollHeight-Q.clientHeight-Q.scrollTop;Q.classList.toggle("persona-artifact-fade-top",r.fadeTop&&Z&&Q.scrollTop>1),Q.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&Z&&ie>1)},k=Q=>{W||(W=z(()=>{W=0,Q.scrollTop=Q.scrollHeight,w(Q)}))},R=(Q,Z,ie,se)=>{let pe=!!r,ue=ie.id+"|"+(pe?"w":"p");if(!C||I!==ue||C.parentElement!==u){b(),L(),u.replaceChildren();let F=v("pre",QR+" persona-code-pre"),Ce=v("code","persona-code");if(F.appendChild(Ce),pe){let Ee=v("div","persona-artifact-source-window");if(Ee.appendChild(F),u.appendChild(Ee),!(r?.overflow==="clip")&&typeof Ee.addEventListener=="function"){let ke=()=>Ee.scrollHeight-Ee.clientHeight>1;Ee.addEventListener("scroll",()=>{H(Ee)&&(E=!1),w(Ee)},{passive:!0}),Ee.addEventListener("wheel",Ie=>{ke()&&Ie.deltaY<0&&(E=!0)},{passive:!0}),Ee.addEventListener("touchmove",()=>{ke()&&(E=!0)},{passive:!0})}C=Ee}else u.appendChild(F),C=F;S=Ce,I=ue}let xe=pe?C:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",se),xe.classList.toggle("persona-artifact-source-window--clip",se&&r?.overflow==="clip"));let be=xe?H(xe):!0;if(S.replaceChildren(AM(Q,Z?.language,Z?.path)),xe){let F=ie.status!=="complete";se&&F&&r?.followOutput&&!E&&be?k(xe):F||(E=!1),w(xe)}},_=Q=>{b(),O(),L(),u.replaceChildren();let Z=v("div",XR);Z.innerHTML=p(Q),u.appendChild(Z)},X=Q=>{let Z=Q.id,ie=n.features?.artifacts,se=La(Q,ie,"status-body");if(M&&D===Z&&M.parentElement===u){let xe=M.querySelector(".persona-artifact-status-view-text");xe&&hi(xe,se,ie);return}b(),O(),u.replaceChildren();let pe=v("div","persona-artifact-status-view"),ue=v("div","persona-artifact-status-view-text");hi(ue,se,ie),pe.appendChild(ue),u.appendChild(pe),M=pe,D=Z},j=Q=>{l=Q;let Z=e.resolveViewMode?.(Q)??r?.viewMode??"rendered",ie=Q.artifactType==="markdown"?Q.file:void 0,se=Q.status!=="complete";se||ka(Q.id);let pe=se?r?.streamingHeight:r?.completeHeight,ue=!!r&&typeof pe=="number";if(r?.streamingView==="status"&&se){X(Q);return}if(ie){let be=Hu(Q.markdown??""),F=fi(ie),Ce=n.features?.artifacts?.filePreview?.enabled!==!1;if(!se&&Z==="rendered"&&Ce&&(F==="html"||F==="svg")){let qe=Q.id+"\0"+be;if(m&&h===qe&&m.parentElement===u)return;O(),L(),b(),u.replaceChildren();let ke=n.features?.artifacts?.filePreview,Ie=ke?.iframeSandbox??"allow-scripts";!ke?.dangerouslyAllowSameOrigin&&Ie.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."),Ie=Ie.split(/\s+/).filter(je=>je&&je!=="allow-same-origin").join(" "));let Te=ZR(ke?.loading),vt=v("div","persona-artifact-frame"),Ye=v("iframe","persona-artifact-iframe");Ye.setAttribute("sandbox",Ie),Ye.setAttribute("data-artifact-id",Q.id);let Et=null;Te.enabled&&Te.injectReadySignal?(Et=tW(),Ye.srcdoc=be+nW(Et)):Ye.srcdoc=be,vt.appendChild(Ye),u.appendChild(vt),Te.enabled&&(g=rW(vt,Ye,Et,Te,Q.id,n)),m=vt,h=qe;return}if(b(),!se&&F==="markdown"&&Z==="rendered"){_(be);return}R(be,{language:ie.language,path:ie.path},Q,ue);return}if(Q.artifactType==="markdown"){if(Z==="source"){b(),R(Q.markdown??"",void 0,Q,ue);return}_(Q.markdown??"");return}b(),O(),L(),u.replaceChildren();let xe=Q.component?o.get(Q.component):void 0;if(xe){let F={message:{id:Q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ce=xe(Q.props??{},F);if(Ce){u.appendChild(Ce);return}}catch{}}u.appendChild(JR(Q))};return j(t),{el:u,update(Q){j(Q)},destroy(){b()}}}var Nh,QR,XR,eW,Nu=we(()=>{"use strict";Ue();hM();gi();Bu();MM();Kd();ei();Bf();hc();_h();Nh=!1;QR="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",XR="persona-text-sm persona-leading-relaxed persona-markdown-bubble";eW=220});function LM(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 PM=we(()=>{"use strict"});function Fh(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=T=>({start:T===!1?!1:typeof T=="object"&&T?T.start!==!1:!0,end:T===!1?!1:typeof T=="object"&&T?T.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 I=gn({icon:"x",label:a});I.addEventListener("click",()=>{g(),e.onDismiss?.()});let E="rendered",O=mu({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:T=>{E=T==="source"?"source":"rendered",K()}}),M=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,L=n?.documentToolbarShowCopyChevron===!0,B=n?.documentToolbarCopyMenuItems,W=!!(L&&B&&B.length>0),z=null,H,w=null;if(r&&(D||L)&&!W){if(H=D?ai({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let T=Ke(vs.ChevronDown,14,"currentColor",2);T&&H.appendChild(T)}}else r&&W?(w=yA({label:"Copy",icon:"copy",iconSize:14,iconOnly:!D,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(B??[]).map(T=>({id:T.id,label:T.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:T=>{xe(T)}}),z=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 k=r?gn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):gn({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||k.classList.add("persona-hidden");let R=r?gn({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):gn({icon:"x",label:a}),_=gn({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&_.classList.add("persona-hidden");let X=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),j=t.features?.artifacts?.toolbarActions??[],Q=()=>{let T=je.find(Le=>Le.id===lt)??je[je.length-1],V=T?.id??null,U=T?.artifactType==="markdown"?T.markdown??"":"",ee=T?JSON.stringify({component:T.component,props:T.props},null,2):"",{filename:me,mime:J,content:re}=yc({title:T?.title,markdown:T?.markdown??"",file:T?.file});return{markdown:U,jsonPayload:ee,id:V,file:T?.file,suggestedFilename:me,mime:J,content:re}},Z=()=>{let{suggestedFilename:T,mime:V,content:U}=Q();U&&bc({filename:T,mime:V,content:U})},ie=T=>{let{id:V,...U}=Q();return{actionId:T,artifactId:V,...U}},se=async()=>{let T=je.find(V=>V.id===lt)??je[je.length-1];try{return await navigator.clipboard.writeText(Cc(T)),!0}catch{return!1}},pe=null,ue=()=>{pe?.();let T=H.querySelector("svg"),V=Number(T?.getAttribute("width"))||16,U=Ke(vs.Check,V,"currentColor",2);if(!T||!U)return;T.replaceWith(U);let ee=H.querySelector("span");ee&&(ee.textContent="Copied");let me=setTimeout(()=>pe?.(),2e3);pe=()=>{clearTimeout(me),U.replaceWith(T),ee&&(ee.textContent="Copy"),pe=null}};H.addEventListener("click",async()=>{let T=n?.onDocumentToolbarCopyMenuSelect;if(T&&W){try{if(await T(ie("primary"))===!1){await se()&&ue();return}ue()}catch{}return}await se()&&ue()});async function xe(T){let V=n?.onDocumentToolbarCopyMenuSelect;try{if(V&&await V(ie(T))!==!1)return;if(T==="download"){Z();return}let{markdown:U,jsonPayload:ee}=Q();T==="markdown"||T==="md"?await navigator.clipboard.writeText(U):T==="json"||T==="source"?await navigator.clipboard.writeText(ee):await navigator.clipboard.writeText(U||ee),ue()}catch{}}k.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}K()}),R.addEventListener("click",()=>{g(),e.onDismiss?.()});let be=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(),z?M.append(z,k,R):M.append(H,k,R),M.insertBefore(X,R),M.insertBefore(_,R),C.append(O.element,be,M);else{let T=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");T.append(H,X,_,I),C.appendChild(S),C.appendChild(T)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let F=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&&F.style.setProperty("--persona-artifact-tab-fade-size",d);let Ce=t.features?.artifacts?.renderTabBar,Ee=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),qe=LM(F,{onSelect:T=>e.onSelect(je[T].id)}),ke=T=>{let V=T.scrollWidth-T.clientWidth,U=V>1,ee=Math.abs(T.scrollLeft);T.classList.toggle("persona-artifact-tab-fade-start",u&&U&&ee>1),T.classList.toggle("persona-artifact-tab-fade-end",m&&U&&ee<V-1)},Ie=0,Te=()=>{if(Ie)return;let T=()=>{Ie=0,ke(F)};Ie=typeof requestAnimationFrame=="function"?requestAnimationFrame(T):setTimeout(T,0)};F.addEventListener("scroll",()=>Te(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ke(F)).observe(F);let vt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ye=()=>{vt.scrollLeft=0},Et=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ye):setTimeout(Ye,0)};if(l){for(let T of[F,Ee])T.style.paddingLeft=l,T.style.paddingRight=l;vt.style.padding=l}b.appendChild(C),b.appendChild(F),b.appendChild(Ee),b.appendChild(vt);let je=[],lt=null,Vt=!1,It=!1,Gt=!0,Ot=!1,Ge=null,hn="",Dt=null,Lt=!1,jn=T=>T.artifactType==="markdown"&&!!T.file||r?E:"rendered",rt=T=>{r||(T&&!Lt?(C.insertBefore(O.element,S),Lt=!0):!T&&Lt&&(O.element.remove(),Lt=!1))},Zt=()=>lt&&je.find(T=>T.id===lt)||je[je.length-1],ln=()=>{let T=vc(Zt());if(!T){X.replaceChildren();return}let V=j.filter(U=>U.visible===void 0||U.visible(T)).map(U=>Ea(U,{documentChrome:r,onClick:()=>{let ee=vc(Zt());if(ee)try{Promise.resolve(U.onClick(ee)).catch(()=>{})}catch{}}}));X.replaceChildren(...V)},K=()=>{ln();let T=r&&je.length<=1,V=!!Ce;if(F.classList.toggle("persona-hidden",T||V),Ee.classList.toggle("persona-hidden",T||!V),V&&Ce){let me=je.map(J=>J.id).join("|")+" "+(lt??"");if(me!==hn){hn=me;let J=Ce({records:je,selectedId:lt,onSelect:e.onSelect});Ee.firstElementChild!==J&&Ee.replaceChildren(J)}}else{qe.beforeRender(),F.replaceChildren();let me=[],J=-1;for(let[re,Le]of je.entries()){let Me=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");Me.type="button";let mt=Le.artifactType==="markdown"?Le.file:void 0,ct=mt?ar(mt.path):Le.title||Le.id.slice(0,8),zt=mt?.path||Le.title||ct;Me.textContent=ct,Me.title=zt,Me.setAttribute("aria-label",zt),Le.id===lt&&(Me.classList.add("persona-bg-persona-container","persona-border-persona-border"),J=re),Me.addEventListener("click",()=>e.onSelect(Le.id)),F.appendChild(Me),me.push(Me)}if(qe.render(me,J),J>=0&<!==Ge){Ge=lt;let re=me[J];typeof re.scrollIntoView=="function"&&re.scrollIntoView({block:"nearest",inline:"nearest"})}ke(F)}let U=lt&&je.find(me=>me.id===lt)||je[je.length-1];if(!U){vt.replaceChildren(),Dt?.destroy(),Dt=null,rt(!1);return}let ee=U.artifactType==="markdown"?U.file:void 0;if(rt(!!ee&&fi(ee)!=="other"),r){let me=ee?bs(ee):U.artifactType==="markdown"?"MD":U.component??"Component",J=(U.title||"Document").trim(),re=ee?ar(ee.path):J.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";be.textContent=`${re} \xB7 ${me}`}else S.textContent=ee?ar(ee.path):s;Dt?(Dt.el.parentElement!==vt&&vt.replaceChildren(Dt.el),Dt.update(U)):(Dt=_u(U,{config:t,resolveViewMode:jn}),vt.replaceChildren(Dt.el)),vt.classList.toggle("persona-artifact-content-flush",!!vt.querySelector(".persona-code-pre"))},ae=()=>{let T=je.length>0;if(b.classList.toggle("persona-hidden",!T),h){let ee=((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;T&&ee&&Vt?(h.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},A=()=>{Ot=!1,K(),ae()};return{element:b,backdrop:h,update(T){let V=T.selectedId??T.artifacts[T.artifacts.length-1]?.id??null,U=V!==lt;je=T.artifacts,lt=V,je.length>0&&(Vt=!0),Ot=!0,Gt&&A(),U&&Ye()},setMobileOpen(T){Vt=T,!T&&h?(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ae()},setExpanded(T){T!==It&&(It=T,Et());let V=Ke(T?vs.Minimize:vs.Maximize,16,"currentColor",2);V&&_.replaceChildren(V);let U=T?"Collapse artifacts panel":"Expand artifacts panel";_.setAttribute("aria-label",U),_.title=U},setExpandToggleVisible(T){_.classList.toggle("persona-hidden",!T)},setCopyButtonVisible(T){r||H.classList.toggle("persona-hidden",!T)},setRefreshButtonVisible(T){k.classList.toggle("persona-hidden",!T)},setCustomActions(T){j=T,ln()},setTabFade(T){let V=p(T);V.start===u&&V.end===m||(u=V.start,m=V.end,ke(F))},setRenderTabBar(T){T!==Ce&&(Ce=T,hn="",K())},setVisible(T){T!==Gt&&(Gt=T,T&&Ot&&A())},destroy(){Dt?.destroy(),Dt=null}}}var vs,IM=we(()=>{"use strict";Ue();gi();Wu();Nu();vs=require("lucide");eo();li();PM()});function HM(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?ar(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?bs(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}:{}},I=La(S,C,"card");hi(b,I,C)}else s&&ka(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 I={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let E of C)try{if(E.visible===void 0||E.visible(I)){let O=Ea(E);O.setAttribute("data-artifact-custom-action",E.id),O.className=`${O.className} persona-flex-shrink-0`,u.append(O)}}catch{}}let S=ai({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",s),u.append(S)}return u}var wc,$h=we(()=>{"use strict";gi();Bu();li();Wu();wc=(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:()=>HM(t,e)});if(l)return l}return HM(t,e)}});function Vh(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=Cs.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function zh(t){return Cs.has(t)}function sW(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 RM(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?ar(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?bs(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function iW(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 mW(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:WM,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let I of a)I.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(dW,Math.max(cW,aW+p*lW))),m=Math.round(u*uW),h=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,g=h?h.animate([{opacity:0},{opacity:1}],{duration:BM,delay:m,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${d}px`}],{duration:u,easing:pW});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+BM)+120)},WM)}function fW(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 gW(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 OM(t,e){let n=sW(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=fW(o),d=o?.inlineActions??[],p=gW(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=se=>wc(iW(se),e),C=null,S=se=>{C?.destroy(),C=null,g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(xc),g.replaceChildren(b(se)),Cs.set(g,pe=>{g.replaceChildren(b(pe))})};if(u&&n.status==="complete")return S(n),g;let I=_u(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>m??p.viewMode});C=I;let E=v("div","persona-artifact-inline-body");E.appendChild(I.el);let O=se=>{let pe=se.status!=="complete",ue=pe?p.streamingHeight:p.completeHeight,xe=typeof ue=="number";xe?g.style.setProperty(xc,`${ue}px`):g.style.removeProperty(xc);let be=!!I.el.querySelector(".persona-code-pre"),F=!!I.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");E.classList.toggle("persona-artifact-content-flush",be),E.classList.toggle("persona-artifact-inline-body--sized",xe&&F),E.classList.toggle("persona-artifact-inline-body--cap",!pe&&!F&&typeof p.completeHeight=="number")},M=n.status,D=(se,pe)=>{M!=="complete"&&se.status==="complete"?(typeof p.completeHeight=="number"?g.style.setProperty(xc,`${p.completeHeight}px`):g.style.removeProperty(xc),kM(E,pe?.suppressTransition?"none":p.transition,se.id,()=>{I.update(se),O(se)})):I.update(se),O(se),M=se.status};O(n);let L=p.overflow==="clip"&&a&&!!n.id;if(L&&(E.setAttribute("data-expand-artifact-inline",n.id),E.setAttribute("role","button"),E.setAttribute("tabindex","0"),E.classList.add("persona-cursor-pointer"),E.setAttribute("aria-label",`Open ${RM(n).title} in panel`)),!r)return g.appendChild(E),Cs.set(g,D),g;let B=v("div","persona-artifact-inline-chrome");B.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let W=v("div","persona-artifact-inline-chrome-lead"),z=v("span","persona-flex persona-items-center persona-flex-shrink-0"),H=Ke(DM.FileText,16,"currentColor",2);H&&z.appendChild(H);let w=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),k=v("span","persona-artifact-inline-type");W.append(z,w,k);let R=v("div","persona-artifact-inline-chrome-actions"),_=v("span","persona-flex persona-items-center persona-gap-1"),X=()=>m??p.viewMode,j=l?mu({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:X(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:se=>{let pe=se==="source"?"source":"rendered";pe!==X()&&(m=pe,I.update(h),O(h))}}):null,Q=s?gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Q&&n.id&&Q.setAttribute("data-copy-artifact",n.id);let Z=a?gn({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Z&&n.id&&Z.setAttribute("data-expand-artifact-inline",n.id),R.appendChild(_),j&&R.appendChild(j.element),Q&&R.appendChild(Q),Z&&R.appendChild(Z),B.append(W,R),g.append(B,E);let ie=se=>{let{title:pe,typeLabel:ue}=RM(se);w.textContent=pe,w.title=pe,L&&E.setAttribute("aria-label",`Open ${pe} in panel`);let xe=se.status!=="complete";if(xe){k.classList.contains("persona-artifact-inline-status")||(k.className="persona-artifact-inline-status",k.removeAttribute("data-preserve-animation"),k.replaceChildren());let be=La(se,o,"inline-chrome");hi(k,be,o)}else ka(se.id),k.className="persona-artifact-inline-type",k.removeAttribute("data-preserve-animation"),k.replaceChildren(),k.textContent=ue;if(Q&&Q.classList.toggle("persona-hidden",xe),j){let be=se.artifactType==="markdown"?se.file:void 0,F=!1;if(!xe&&be&&p.viewMode!=="source"){let Ce=fi(be);Ce==="markdown"?F=!0:(Ce==="html"||Ce==="svg")&&(F=o?.filePreview?.enabled!==!1)}j.element.classList.toggle("persona-hidden",!F),j.setSelected(X())}if(_.replaceChildren(),!xe&&d.length>0){let be=vc(se);if(be)for(let F of d)try{if(F.visible===void 0||F.visible(be)){let Ce=Ea(F,{documentChrome:!0});Ce.setAttribute("data-artifact-custom-action",F.id),Ce.classList.add("persona-flex-shrink-0"),_.appendChild(Ce)}}catch{}}};return ie(n),Cs.set(g,(se,pe)=>{if(u&&M!=="complete"&&se.status==="complete"){let ue=g.isConnected?g.getBoundingClientRect().height:0;M="complete";let xe=se,be=!1,F=Ce=>{xe=Ce,be=!0};Cs.set(g,F),mW(g,ue,{swap:()=>{S(xe),be=!1,Cs.set(g,F)},onSettled:()=>{be?S(xe):Cs.set(g,Ce=>{g.replaceChildren(b(Ce))})}});return}(se.status!=="complete"||se.id!==h.id)&&(m=null),h=se,D(se,pe),ie(se)}),g}var DM,Cs,WM,aW,lW,cW,dW,pW,BM,uW,xc,qh,_M=we(()=>{"use strict";Ue();gi();Bu();Wu();li();DM=require("lucide");eo();Nu();$h();Cs=new WeakMap;WM=180,aW=240,lW=.8,cW=300,dW=500,pW="cubic-bezier(0.2, 0, 0, 1)",BM=240,uW=.35;xc="--persona-artifact-inline-body-height";qh=(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:()=>OM(t,e)});if(l)return l}return OM(t,e)}});var NM=we(()=>{"use strict";IM();_M();$h();Nu();gi();_h();ei();hp()});var FM={};Fn(FM,{PersonaArtifactCard:()=>wc,PersonaArtifactInline:()=>qh,__provideMarkdownParsers:()=>Rf,__setIconsExtraLoader:()=>lg,artifactCopyText:()=>Cc,createArtifactPane:()=>Fh,downloadInfoFor:()=>yc,hasLiveInlineArtifactBlock:()=>zh,initArtifactsUi:()=>Dh,triggerArtifactDownload:()=>bc,updateInlineArtifactBlocks:()=>Vh});var $M=we(()=>{"use strict";NM()});var qu,JM,ZM=we(()=>{"use strict";Ue();qu={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"}},JM=(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=qu[a]??qu.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 I=b.type??"text",E;I==="textarea"?(E=document.createElement("textarea"),E.rows=3):(E=document.createElement("input"),E.type=I),E.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",E.id=`${e.id}-${a}-${b.name}`,E.name=b.name,E.placeholder=b.placeholder??"",b.required&&(E.required=!0),C.appendChild(E),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),I={};S.forEach((E,O)=>{I[O]=E}),I.type=a,g.disabled=!0,h.textContent="Submitting\u2026";try{let E=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let O=await E.json();h.textContent=O.message??"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await o.sendMessage(String(O.nextPrompt))}catch(E){h.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})}});var eT={};Fn(eT,{enhanceWithForms:()=>JM,formDefinitions:()=>qu});var tT=we(()=>{"use strict";ZM()});function uT(){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 mT=we(()=>{"use strict"});var fT,gT=we(()=>{"use strict";fT=`
|
|
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 kM(t,e,n){let o=t.length<=UR?jR(e,n):null,r=o?eW(t,o):[{type:"plain",value:t}];return tW(r)}var qR,UR,_u,KR,GR,YR,XR,JR,LM=we(()=>{"use strict";qe();qR={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"},UR=15e4,_u={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"};KR=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"]),GR=[{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=>KR.has(t)?"keyword":"plain"}];YR=[{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"}];XR=[{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}];JR=[{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 PM,Fh,IM,$h=we(()=>{"use strict";PM=null,Fh=t=>{PM=t.componentRegistry},IM=()=>PM});function wc(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Wu(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}function nW(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function HM(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"||Vh||s){o();return}Vh=!0;let a=nW(n);t.style.setProperty("view-transition-name",a);let l=()=>{Vh=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}function sW(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 iW(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 lW(){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 cW(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 dW(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(vM());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 pW(t,e,n,o,r,s){let a=null,l=0,d=!1,p=new Set,u=()=>{p.forEach(O=>clearTimeout(O)),p.clear()},m=(O,M)=>{let D=setTimeout(()=>{p.delete(D),!(typeof document>"u")&&O()},M);p.add(D)},h=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||d)return;let O=dW(r,s,o);a=O.el,t.appendChild(a),l=Date.now(),o.label!==!1&&m(O.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),m(h,aW))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",I):e.removeEventListener("load",E)},S=()=>{if(d||(d=!0,C(),u(),!a))return;let O=Math.max(0,o.minVisibleMs-(Date.now()-l));O>0?m(b,O):b()};function I(O){if(n===null)return;let M=O.data;!M||M.persona!=="artifact-preview-ready"||M.token!==n||O.source===e.contentWindow&&S()}function E(){let O=M=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>M()):setTimeout(M,0)};O(()=>O(()=>S()))}return m(g,o.delayMs),m(S,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",I):e.addEventListener("load",E),()=>{d=!0,u(),C(),h()}}function Fu(t,e){let{config:n}=e,o=e.registry??IM()??Fo,r=e.bodyLayout,s=n.markdown?Kd(n.markdown):null,a=Yd(n.sanitize),l=t,d=!1,p=Q=>{let Z=Ao()!==null;s&&!Z&&!d&&(d=!0,Zi(()=>j(l)));let ie=s?s(Q):kr(Q);return s&&Z&&a?a(ie):ie},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,I=null,E=!1,O=()=>{C=null,S=null,I=null,E=!1},M=null,D=null,L=()=>{M=null,D=null},B=40,W=0,z=Q=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Q()):setTimeout(Q,0),H=Q=>Q.scrollHeight-Q.clientHeight-Q.scrollTop<=B,w=Q=>{if(!r)return;let Z=Q.scrollHeight-Q.clientHeight>1,ie=Q.scrollHeight-Q.clientHeight-Q.scrollTop;Q.classList.toggle("persona-artifact-fade-top",r.fadeTop&&Z&&Q.scrollTop>1),Q.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&Z&&ie>1)},k=Q=>{W||(W=z(()=>{W=0,Q.scrollTop=Q.scrollHeight,w(Q)}))},R=(Q,Z,ie,se)=>{let pe=!!r,ue=ie.id+"|"+(pe?"w":"p");if(!C||I!==ue||C.parentElement!==u){b(),L(),u.replaceChildren();let F=v("pre",oW+" persona-code-pre"),Ce=v("code","persona-code");if(F.appendChild(Ce),pe){let Ee=v("div","persona-artifact-source-window");if(Ee.appendChild(F),u.appendChild(Ee),!(r?.overflow==="clip")&&typeof Ee.addEventListener=="function"){let ke=()=>Ee.scrollHeight-Ee.clientHeight>1;Ee.addEventListener("scroll",()=>{H(Ee)&&(E=!1),w(Ee)},{passive:!0}),Ee.addEventListener("wheel",Ie=>{ke()&&Ie.deltaY<0&&(E=!0)},{passive:!0}),Ee.addEventListener("touchmove",()=>{ke()&&(E=!0)},{passive:!0})}C=Ee}else u.appendChild(F),C=F;S=Ce,I=ue}let xe=pe?C:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",se),xe.classList.toggle("persona-artifact-source-window--clip",se&&r?.overflow==="clip"));let be=xe?H(xe):!0;if(S.replaceChildren(kM(Q,Z?.language,Z?.path)),xe){let F=ie.status!=="complete";se&&F&&r?.followOutput&&!E&&be?k(xe):F||(E=!1),w(xe)}},_=Q=>{b(),O(),L(),u.replaceChildren();let Z=v("div",rW);Z.innerHTML=p(Q),u.appendChild(Z)},X=Q=>{let Z=Q.id,ie=n.features?.artifacts,se=Pa(Q,ie,"status-body");if(M&&D===Z&&M.parentElement===u){let xe=M.querySelector(".persona-artifact-status-view-text");xe&&hi(xe,se,ie);return}b(),O(),u.replaceChildren();let pe=v("div","persona-artifact-status-view"),ue=v("div","persona-artifact-status-view-text");hi(ue,se,ie),pe.appendChild(ue),u.appendChild(pe),M=pe,D=Z},j=Q=>{l=Q;let Z=e.resolveViewMode?.(Q)??r?.viewMode??"rendered",ie=Q.artifactType==="markdown"?Q.file:void 0,se=Q.status!=="complete";se||La(Q.id);let pe=se?r?.streamingHeight:r?.completeHeight,ue=!!r&&typeof pe=="number";if(r?.streamingView==="status"&&se){X(Q);return}if(ie){let be=Wu(Q.markdown??""),F=fi(ie),Ce=n.features?.artifacts?.filePreview?.enabled!==!1;if(!se&&Z==="rendered"&&Ce&&(F==="html"||F==="svg")){let Ve=Q.id+"\0"+be;if(m&&h===Ve&&m.parentElement===u)return;O(),L(),b(),u.replaceChildren();let ke=n.features?.artifacts?.filePreview,Ie=ke?.iframeSandbox??"allow-scripts";!ke?.dangerouslyAllowSameOrigin&&Ie.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."),Ie=Ie.split(/\s+/).filter(Ue=>Ue&&Ue!=="allow-same-origin").join(" "));let Te=iW(ke?.loading),bt=v("div","persona-artifact-frame"),Ye=v("iframe","persona-artifact-iframe");Ye.setAttribute("sandbox",Ie),Ye.setAttribute("data-artifact-id",Q.id);let Et=null;Te.enabled&&Te.injectReadySignal?(Et=lW(),Ye.srcdoc=be+cW(Et)):Ye.srcdoc=be,bt.appendChild(Ye),u.appendChild(bt),Te.enabled&&(g=pW(bt,Ye,Et,Te,Q.id,n)),m=bt,h=Ve;return}if(b(),!se&&F==="markdown"&&Z==="rendered"){_(be);return}R(be,{language:ie.language,path:ie.path},Q,ue);return}if(Q.artifactType==="markdown"){if(Z==="source"){b(),R(Q.markdown??"",void 0,Q,ue);return}_(Q.markdown??"");return}b(),O(),L(),u.replaceChildren();let xe=Q.component?o.get(Q.component):void 0;if(xe){let F={message:{id:Q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ce=xe(Q.props??{},F);if(Ce){u.appendChild(Ce);return}}catch{}}u.appendChild(sW(Q))};return j(t),{el:u,update(Q){j(Q)},destroy(){b()}}}var Vh,oW,rW,aW,$u=we(()=>{"use strict";qe();CM();gi();Du();LM();Gd();ei();Df();yc();$h();Vh=!1;oW="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",rW="persona-text-sm persona-leading-relaxed persona-markdown-bubble";aW=220});function RM(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 WM=we(()=>{"use strict"});function zh(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=T=>({start:T===!1?!1:typeof T=="object"&&T?T.start!==!1:!0,end:T===!1?!1:typeof T=="object"&&T?T.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 I=yn({icon:"x",label:a});I.addEventListener("click",()=>{g(),e.onDismiss?.()});let E="rendered",O=gu({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:T=>{E=T==="source"?"source":"rendered",G()}}),M=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,L=n?.documentToolbarShowCopyChevron===!0,B=n?.documentToolbarCopyMenuItems,W=!!(L&&B&&B.length>0),z=null,H,w=null;if(r&&(D||L)&&!W){if(H=D?ai({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let T=Ke(vs.ChevronDown,14,"currentColor",2);T&&H.appendChild(T)}}else r&&W?(w=CA({label:"Copy",icon:"copy",iconSize:14,iconOnly:!D,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(B??[]).map(T=>({id:T.id,label:T.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:T=>{xe(T)}}),z=w.element,H=w.primaryButton):r?H=yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(H=yn({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&H.classList.add("persona-hidden"));let k=r?yn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yn({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||k.classList.add("persona-hidden");let R=r?yn({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):yn({icon:"x",label:a}),_=yn({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&_.classList.add("persona-hidden");let X=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),j=t.features?.artifacts?.toolbarActions??[],Q=()=>{let T=Ue.find(Le=>Le.id===at)??Ue[Ue.length-1],V=T?.id??null,U=T?.artifactType==="markdown"?T.markdown??"":"",ee=T?JSON.stringify({component:T.component,props:T.props},null,2):"",{filename:me,mime:J,content:re}=bc({title:T?.title,markdown:T?.markdown??"",file:T?.file});return{markdown:U,jsonPayload:ee,id:V,file:T?.file,suggestedFilename:me,mime:J,content:re}},Z=()=>{let{suggestedFilename:T,mime:V,content:U}=Q();U&&vc({filename:T,mime:V,content:U})},ie=T=>{let{id:V,...U}=Q();return{actionId:T,artifactId:V,...U}},se=async()=>{let T=Ue.find(V=>V.id===at)??Ue[Ue.length-1];try{return await navigator.clipboard.writeText(wc(T)),!0}catch{return!1}},pe=null,ue=()=>{pe?.();let T=H.querySelector("svg"),V=Number(T?.getAttribute("width"))||16,U=Ke(vs.Check,V,"currentColor",2);if(!T||!U)return;T.replaceWith(U);let ee=H.querySelector("span");ee&&(ee.textContent="Copied");let me=setTimeout(()=>pe?.(),2e3);pe=()=>{clearTimeout(me),U.replaceWith(T),ee&&(ee.textContent="Copy"),pe=null}};H.addEventListener("click",async()=>{let T=n?.onDocumentToolbarCopyMenuSelect;if(T&&W){try{if(await T(ie("primary"))===!1){await se()&&ue();return}ue()}catch{}return}await se()&&ue()});async function xe(T){let V=n?.onDocumentToolbarCopyMenuSelect;try{if(V&&await V(ie(T))!==!1)return;if(T==="download"){Z();return}let{markdown:U,jsonPayload:ee}=Q();T==="markdown"||T==="md"?await navigator.clipboard.writeText(U):T==="json"||T==="source"?await navigator.clipboard.writeText(ee):await navigator.clipboard.writeText(U||ee),ue()}catch{}}k.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}G()}),R.addEventListener("click",()=>{g(),e.onDismiss?.()});let be=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(),z?M.append(z,k,R):M.append(H,k,R),M.insertBefore(X,R),M.insertBefore(_,R),C.append(O.element,be,M);else{let T=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");T.append(H,X,_,I),C.appendChild(S),C.appendChild(T)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let F=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&&F.style.setProperty("--persona-artifact-tab-fade-size",d);let Ce=t.features?.artifacts?.renderTabBar,Ee=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Ve=RM(F,{onSelect:T=>e.onSelect(Ue[T].id)}),ke=T=>{let V=T.scrollWidth-T.clientWidth,U=V>1,ee=Math.abs(T.scrollLeft);T.classList.toggle("persona-artifact-tab-fade-start",u&&U&&ee>1),T.classList.toggle("persona-artifact-tab-fade-end",m&&U&&ee<V-1)},Ie=0,Te=()=>{if(Ie)return;let T=()=>{Ie=0,ke(F)};Ie=typeof requestAnimationFrame=="function"?requestAnimationFrame(T):setTimeout(T,0)};F.addEventListener("scroll",()=>Te(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ke(F)).observe(F);let bt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ye=()=>{bt.scrollLeft=0},Et=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ye):setTimeout(Ye,0)};if(l){for(let T of[F,Ee])T.style.paddingLeft=l,T.style.paddingRight=l;bt.style.padding=l}b.appendChild(C),b.appendChild(F),b.appendChild(Ee),b.appendChild(bt);let Ue=[],at=null,Ut=!1,Ht=!1,Qt=!0,_t=!1,Ge=null,bn="",Nt=null,Pt=!1,Kn=T=>T.artifactType==="markdown"&&!!T.file||r?E:"rendered",nt=T=>{r||(T&&!Pt?(C.insertBefore(O.element,S),Pt=!0):!T&&Pt&&(O.element.remove(),Pt=!1))},tn=()=>at&&Ue.find(T=>T.id===at)||Ue[Ue.length-1],dn=()=>{let T=Cc(tn());if(!T){X.replaceChildren();return}let V=j.filter(U=>U.visible===void 0||U.visible(T)).map(U=>ka(U,{documentChrome:r,onClick:()=>{let ee=Cc(tn());if(ee)try{Promise.resolve(U.onClick(ee)).catch(()=>{})}catch{}}}));X.replaceChildren(...V)},G=()=>{dn();let T=r&&Ue.length<=1,V=!!Ce;if(F.classList.toggle("persona-hidden",T||V),Ee.classList.toggle("persona-hidden",T||!V),V&&Ce){let me=Ue.map(J=>J.id).join("|")+" "+(at??"");if(me!==bn){bn=me;let J=Ce({records:Ue,selectedId:at,onSelect:e.onSelect});Ee.firstElementChild!==J&&Ee.replaceChildren(J)}}else{Ve.beforeRender(),F.replaceChildren();let me=[],J=-1;for(let[re,Le]of Ue.entries()){let Me=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");Me.type="button";let ut=Le.artifactType==="markdown"?Le.file:void 0,lt=ut?ar(ut.path):Le.title||Le.id.slice(0,8),jt=ut?.path||Le.title||lt;Me.textContent=lt,Me.title=jt,Me.setAttribute("aria-label",jt),Le.id===at&&(Me.classList.add("persona-bg-persona-container","persona-border-persona-border"),J=re),Me.addEventListener("click",()=>e.onSelect(Le.id)),F.appendChild(Me),me.push(Me)}if(Ve.render(me,J),J>=0&&at!==Ge){Ge=at;let re=me[J];typeof re.scrollIntoView=="function"&&re.scrollIntoView({block:"nearest",inline:"nearest"})}ke(F)}let U=at&&Ue.find(me=>me.id===at)||Ue[Ue.length-1];if(!U){bt.replaceChildren(),Nt?.destroy(),Nt=null,nt(!1);return}let ee=U.artifactType==="markdown"?U.file:void 0;if(nt(!!ee&&fi(ee)!=="other"),r){let me=ee?bs(ee):U.artifactType==="markdown"?"MD":U.component??"Component",J=(U.title||"Document").trim(),re=ee?ar(ee.path):J.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";be.textContent=`${re} \xB7 ${me}`}else S.textContent=ee?ar(ee.path):s;Nt?(Nt.el.parentElement!==bt&&bt.replaceChildren(Nt.el),Nt.update(U)):(Nt=Fu(U,{config:t,resolveViewMode:Kn}),bt.replaceChildren(Nt.el)),bt.classList.toggle("persona-artifact-content-flush",!!bt.querySelector(".persona-code-pre"))},ae=()=>{let T=Ue.length>0;if(b.classList.toggle("persona-hidden",!T),h){let ee=((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;T&&ee&&Ut?(h.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},A=()=>{_t=!1,G(),ae()};return{element:b,backdrop:h,update(T){let V=T.selectedId??T.artifacts[T.artifacts.length-1]?.id??null,U=V!==at;Ue=T.artifacts,at=V,Ue.length>0&&(Ut=!0),_t=!0,Qt&&A(),U&&Ye()},setMobileOpen(T){Ut=T,!T&&h?(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ae()},setExpanded(T){T!==Ht&&(Ht=T,Et());let V=Ke(T?vs.Minimize:vs.Maximize,16,"currentColor",2);V&&_.replaceChildren(V);let U=T?"Collapse artifacts panel":"Expand artifacts panel";_.setAttribute("aria-label",U),_.title=U},setExpandToggleVisible(T){_.classList.toggle("persona-hidden",!T)},setCopyButtonVisible(T){r||H.classList.toggle("persona-hidden",!T)},setRefreshButtonVisible(T){k.classList.toggle("persona-hidden",!T)},setCustomActions(T){j=T,dn()},setTabFade(T){let V=p(T);V.start===u&&V.end===m||(u=V.start,m=V.end,ke(F))},setRenderTabBar(T){T!==Ce&&(Ce=T,bn="",G())},setVisible(T){T!==Qt&&(Qt=T,T&&_t&&A())},destroy(){Nt?.destroy(),Nt=null}}}var vs,BM=we(()=>{"use strict";qe();gi();Ou();$u();vs=require("lucide");to();li();WM()});function OM(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?ar(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?bs(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}:{}},I=Pa(S,C,"card");hi(b,I,C)}else s&&La(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 I={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let E of C)try{if(E.visible===void 0||E.visible(I)){let O=ka(E);O.setAttribute("data-artifact-custom-action",E.id),O.className=`${O.className} persona-flex-shrink-0`,u.append(O)}}catch{}}let S=ai({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",s),u.append(S)}return u}var xc,qh=we(()=>{"use strict";gi();Du();li();Ou();xc=(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:()=>OM(t,e)});if(l)return l}return OM(t,e)}});function Uh(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=Cs.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function jh(t){return Cs.has(t)}function uW(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 DM(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?ar(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?bs(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function mW(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 CW(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:_M,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let I of a)I.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(yW,Math.max(hW,fW+p*gW))),m=Math.round(u*vW),h=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,g=h?h.animate([{opacity:0},{opacity:1}],{duration:NM,delay:m,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${d}px`}],{duration:u,easing:bW});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+NM)+120)},_M)}function wW(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 xW(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 FM(t,e){let n=uW(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=wW(o),d=o?.inlineActions??[],p=xW(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=se=>xc(mW(se),e),C=null,S=se=>{C?.destroy(),C=null,g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Sc),g.replaceChildren(b(se)),Cs.set(g,pe=>{g.replaceChildren(b(pe))})};if(u&&n.status==="complete")return S(n),g;let I=Fu(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>m??p.viewMode});C=I;let E=v("div","persona-artifact-inline-body");E.appendChild(I.el);let O=se=>{let pe=se.status!=="complete",ue=pe?p.streamingHeight:p.completeHeight,xe=typeof ue=="number";xe?g.style.setProperty(Sc,`${ue}px`):g.style.removeProperty(Sc);let be=!!I.el.querySelector(".persona-code-pre"),F=!!I.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");E.classList.toggle("persona-artifact-content-flush",be),E.classList.toggle("persona-artifact-inline-body--sized",xe&&F),E.classList.toggle("persona-artifact-inline-body--cap",!pe&&!F&&typeof p.completeHeight=="number")},M=n.status,D=(se,pe)=>{M!=="complete"&&se.status==="complete"?(typeof p.completeHeight=="number"?g.style.setProperty(Sc,`${p.completeHeight}px`):g.style.removeProperty(Sc),HM(E,pe?.suppressTransition?"none":p.transition,se.id,()=>{I.update(se),O(se)})):I.update(se),O(se),M=se.status};O(n);let L=p.overflow==="clip"&&a&&!!n.id;if(L&&(E.setAttribute("data-expand-artifact-inline",n.id),E.setAttribute("role","button"),E.setAttribute("tabindex","0"),E.classList.add("persona-cursor-pointer"),E.setAttribute("aria-label",`Open ${DM(n).title} in panel`)),!r)return g.appendChild(E),Cs.set(g,D),g;let B=v("div","persona-artifact-inline-chrome");B.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let W=v("div","persona-artifact-inline-chrome-lead"),z=v("span","persona-flex persona-items-center persona-flex-shrink-0"),H=Ke($M.FileText,16,"currentColor",2);H&&z.appendChild(H);let w=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),k=v("span","persona-artifact-inline-type");W.append(z,w,k);let R=v("div","persona-artifact-inline-chrome-actions"),_=v("span","persona-flex persona-items-center persona-gap-1"),X=()=>m??p.viewMode,j=l?gu({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:X(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:se=>{let pe=se==="source"?"source":"rendered";pe!==X()&&(m=pe,I.update(h),O(h))}}):null,Q=s?yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Q&&n.id&&Q.setAttribute("data-copy-artifact",n.id);let Z=a?yn({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Z&&n.id&&Z.setAttribute("data-expand-artifact-inline",n.id),R.appendChild(_),j&&R.appendChild(j.element),Q&&R.appendChild(Q),Z&&R.appendChild(Z),B.append(W,R),g.append(B,E);let ie=se=>{let{title:pe,typeLabel:ue}=DM(se);w.textContent=pe,w.title=pe,L&&E.setAttribute("aria-label",`Open ${pe} in panel`);let xe=se.status!=="complete";if(xe){k.classList.contains("persona-artifact-inline-status")||(k.className="persona-artifact-inline-status",k.removeAttribute("data-preserve-animation"),k.replaceChildren());let be=Pa(se,o,"inline-chrome");hi(k,be,o)}else La(se.id),k.className="persona-artifact-inline-type",k.removeAttribute("data-preserve-animation"),k.replaceChildren(),k.textContent=ue;if(Q&&Q.classList.toggle("persona-hidden",xe),j){let be=se.artifactType==="markdown"?se.file:void 0,F=!1;if(!xe&&be&&p.viewMode!=="source"){let Ce=fi(be);Ce==="markdown"?F=!0:(Ce==="html"||Ce==="svg")&&(F=o?.filePreview?.enabled!==!1)}j.element.classList.toggle("persona-hidden",!F),j.setSelected(X())}if(_.replaceChildren(),!xe&&d.length>0){let be=Cc(se);if(be)for(let F of d)try{if(F.visible===void 0||F.visible(be)){let Ce=ka(F,{documentChrome:!0});Ce.setAttribute("data-artifact-custom-action",F.id),Ce.classList.add("persona-flex-shrink-0"),_.appendChild(Ce)}}catch{}}};return ie(n),Cs.set(g,(se,pe)=>{if(u&&M!=="complete"&&se.status==="complete"){let ue=g.isConnected?g.getBoundingClientRect().height:0;M="complete";let xe=se,be=!1,F=Ce=>{xe=Ce,be=!0};Cs.set(g,F),CW(g,ue,{swap:()=>{S(xe),be=!1,Cs.set(g,F)},onSettled:()=>{be?S(xe):Cs.set(g,Ce=>{g.replaceChildren(b(Ce))})}});return}(se.status!=="complete"||se.id!==h.id)&&(m=null),h=se,D(se,pe),ie(se)}),g}var $M,Cs,_M,fW,gW,hW,yW,bW,NM,vW,Sc,Kh,VM=we(()=>{"use strict";qe();gi();Du();Ou();li();$M=require("lucide");to();$u();qh();Cs=new WeakMap;_M=180,fW=240,gW=.8,hW=300,yW=500,bW="cubic-bezier(0.2, 0, 0, 1)",NM=240,vW=.35;Sc="--persona-artifact-inline-body-height";Kh=(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:()=>FM(t,e)});if(l)return l}return FM(t,e)}});var zM=we(()=>{"use strict";BM();VM();qh();$u();gi();$h();ei();bp()});var qM={};$n(qM,{PersonaArtifactCard:()=>xc,PersonaArtifactInline:()=>Kh,__provideMarkdownParsers:()=>Bf,__setIconsExtraLoader:()=>dg,artifactCopyText:()=>wc,createArtifactPane:()=>zh,downloadInfoFor:()=>bc,hasLiveInlineArtifactBlock:()=>jh,initArtifactsUi:()=>Fh,triggerArtifactDownload:()=>vc,updateInlineArtifactBlocks:()=>Uh});var UM=we(()=>{"use strict";zM()});var ju,nT,oT=we(()=>{"use strict";qe();ju={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"}},nT=(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=ju[a]??ju.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 I=b.type??"text",E;I==="textarea"?(E=document.createElement("textarea"),E.rows=3):(E=document.createElement("input"),E.type=I),E.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",E.id=`${e.id}-${a}-${b.name}`,E.name=b.name,E.placeholder=b.placeholder??"",b.required&&(E.required=!0),C.appendChild(E),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),I={};S.forEach((E,O)=>{I[O]=E}),I.type=a,g.disabled=!0,h.textContent="Submitting\u2026";try{let E=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let O=await E.json();h.textContent=O.message??"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await o.sendMessage(String(O.nextPrompt))}catch(E){h.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})}});var rT={};$n(rT,{enhanceWithForms:()=>nT,formDefinitions:()=>ju});var sT=we(()=>{"use strict";oT()});function hT(){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 yT=we(()=>{"use strict"});var bT,vT=we(()=>{"use strict";bT=`
|
|
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 oy(t){if(!t)return Uu;let e={...Uu};for(let n of UW){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var UW,Uu,ry=we(()=>{"use strict";UW=["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"],Uu={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 Ec(t){if(!t)return Tc;let e={...Tc};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function cr(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var Tc,kc=we(()=>{"use strict";ry();Tc={...Uu,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 jW(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function iy(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function KW(t,e){let n=iy(t,e),o=jW(e);if(n>=o)return"today";if(n>=o-sy)return"yesterday";if(n>=o-7*sy)return"previous-7-days";if(n>=o-30*sy)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function GW(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(iy(e,n));return cr(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function hT(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=KW(a.updatedAt,e),d=s[s.length-1];if(d&&d.key===l){d.items.push(a);continue}s.push({key:l,label:GW(l,a.updatedAt,e,n),items:[a]})}return s}function yT(t,e,n){let o=Math.max(0,e-iy(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return cr(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return cr(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return cr(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?cr(n.relativeWeeks,{value:l}):cr(n.relativeYears,{value:Math.floor(a/365)})}function bT(t,e){return t===1?e.messageCountLabelOne:cr(e.messageCountLabel,{count:t})}var sy,ay=we(()=>{"use strict";kc();sy=864e5});function ws(t,e=20){let n=document.createElementNS(ju,"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(ju,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=QW[t];if(o){let r=document.createElementNS(ju,"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 YW[t]){let s=document.createElementNS(ju,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var ju,YW,QW,ly=we(()=>{"use strict";ju="http://www.w3.org/2000/svg",YW={"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:[]},QW={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function JW(t){let e=q("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return XW.test(t)?e.appendChild(q("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function vT(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=ws("star",11);return g.setAttribute("fill","currentColor"),g.setAttribute("stroke-width","1"),q("span",{className:"persona-history-row-star"},g,q("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,d=q("div",{className:"persona-history-row-head"},q("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,q("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:yT(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?q("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=q("button",{className:Bt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":ZW(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?JW(t.avatar):null,q("div",{className:"persona-history-row-body"},d,p,q("span",{className:"persona-history-row-count persona-history-sr-only",text:bT(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let m=t.showDelete?cy({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:eB(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return q("li",{className:Bt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,m,t.menuOpen&&t.showDelete?tB(t):null,t.error?nB(t.error,n,e.id):null)}function tB(t){let{conversation:e,copy:n}=t;return dy({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Lc(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function cy(t){let e=q("button",{className:Bt("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(ws("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 dy(t){let e=q("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=q("button",{className:Bt("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 nB(t,e,n){let o=q("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),q("div",{className:"persona-history-row-error",attrs:{role:"alert"}},q("span",{text:t.message}),o)}var XW,ZW,eB,Lc,CT=we(()=>{"use strict";Ue();ly();ay();XW=/^(https?:|\/|data:)/i;ZW=t=>`row:${t}`,eB=t=>`menu:${t}`,Lc=t=>`menu-item:${t}`});function oB(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 wT(t){if(dp(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=oB(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function rB(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 sB(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 Ku(t,e,n,o){let r=q("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 Pc(t,e,n,o,r){return q("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},q("p",{className:"persona-history-state-title",text:e}),q("p",{className:"persona-history-state-description",text:n}),o)}function iB(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>q("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},q("div",{className:"persona-history-skeleton-head"},q("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),q("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),q("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return q("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function xT(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return iB(n);if(e.kind==="empty"){let l=rB(t.identityStatus,n);return l?Pc("identity",l.title,l.description,t.onRetry?Ku(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Pc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?cr(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Pc("rate_limited",n.rateLimitedTitle,l,t.onRetry?Ku(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Pc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Ku(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=sB(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Pc("error",r,s,e.retryable&&t.onRetry?Ku(a,"state-retry",o,t.onRetry):null,!0)}var ST=we(()=>{"use strict";Ue();kc();Wl()});function Gu(t){return`${t.state}:${"reason"in t?t.reason:""}`}function MT(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 fB(t){return t.state==="verified"||t.state==="browser_only"}function gB(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function py(t){let e=Ec(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??aB,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=Gu(u),h=null,g=!1,b=!1,C=0,S=t.presentation,I=t.collapsible!==!1,E=t.collapsed===!0,O=t.railSide==="right",M=t.renderDom!==!1,D=new Map,L=null,B=uT(),W=N=>{!M&&t.onAnnounce?t.onAnnounce(N):B.announce(N)},z=()=>d!==null,H=`${r}-body`,w=q("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),k=()=>S==="rail"&&I,R,_=()=>{if(t.railBrand){if(!k()){w.classList.remove("persona-history-back--branded");return}if(R===void 0){let N=t.railBrand(!0);R=N?q("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},N):null}R&&(w.classList.add("persona-history-back--branded"),w.appendChild(R))}},X=()=>{let N=k(),de=S==="rail";w.setAttribute("data-persona-history-focus",N?"collapse":"close"),w.setAttribute("aria-label",N?E?e.expandLabel:e.collapseLabel:de?e.closeLabel:e.backLabel),N?(w.setAttribute("aria-expanded",E?"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(ws(N?"panel-left":de?"x":"arrow-left")),_()};X(),w.addEventListener("click",()=>{k()?t.onToggleCollapse?.():t.onClose()});let j=q("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),Q=q("span",{className:"persona-history-scope-title"}),Z=q("p",{className:"persona-history-scope"},q("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},ws("monitor",14)),Q),ie=q("div",{className:"persona-history-heading-group"},j),se=!1,pe,ue=()=>{let N=S==="rail",de=N?t.renderRailHeader:void 0,De=null,Xe=de!==void 0;if(de)try{De=de({collapsed:E,defaultTitle:e.viewTitle})}catch(ve){Xe=!1,se||(se=!0,console.warn("[persona] history rail renderHeader threw",ve))}if(!Xe&&N&&t.railBrand){if(pe===void 0){let ve=t.railBrand(!1);pe=ve?q("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},q("span",{className:"persona-history-brand-mark"},ve),q("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}pe&&(Xe=!0,De=pe)}j.classList.toggle("persona-history-sr-only",Xe),ie.replaceChildren(j),De&&ie.appendChild(De)};ue();let xe=q("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});xe.appendChild(ws("plus")),xe.addEventListener("click",()=>{cn()});let be=[w,xe].map(N=>t.attachTooltip?.({anchor:N,text:()=>N.getAttribute("aria-label")??"",...N===w&&t.collapseShortcut?{hint:()=>k()?t.collapseShortcut.hint:""}:{}})),F=q("div",{className:"persona-history-topbar"}),Ce=null,Ee=()=>{let N=S==="rail",de=N?O?"rail-right":"rail":"panel";de!==Ce&&(Ce=de,de==="rail"?F.append(ie,w):F.append(w,ie),N?xe.remove():F.appendChild(xe),Ge.classList.toggle("persona-history-view--rail-right",de==="rail-right"))},qe=q("div",{className:"persona-history-scope-alert"}),ke=`${r}-scope`,Ie=ws("plus",18),Te=q("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},Ie,q("span",{text:e.newConversationLabel}));Te.addEventListener("click",()=>{cn()});let vt=q("div",{className:"persona-history-list-region"}),Ye=t.showDeleteAll!==!1,Et=!!t.provider.resetDevice,je=t.listActions??[],lt=Ye||Et||je.length>0?cy({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${vi}`,open:!1,inert:!0,iconSize:16,onToggle:()=>Ci(vi)}):null,Vt=q("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),It=q("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":vi}},Vt,t.showScopeStatus?Z:null,lt),Gt=q("div",{className:"persona-history-body",attrs:{id:H}},t.showScopeStatus?qe:null,Te,It,vt),Ot=t.headerPlacement??"inline";Ot==="external"&&F.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Ge=q("div",{className:Bt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},B.element,Ot==="inline"?F:null,Gt),hn=()=>{Ge.classList.toggle("persona-history-view--rail-collapsed",E&&k())};hn(),Ee();let Dt=(N,de)=>{let De=`${r}-s${de}`,Xe=q("div",{className:Bt("persona-history-nav",N.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":N.id,...N.title?{"aria-labelledby":De}:{"aria-label":N.id}}});N.title&&Xe.appendChild(q("h3",{className:"persona-history-group-heading",text:N.title,attrs:{id:De}}));for(let ve of N.items){let Be=ve.iconNode?.()??null,Fo=q("button",{className:Bt("persona-history-nav-item",Be&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":ve.label,"data-persona-rail-item":ve.id}},Be?q("span",{className:"persona-history-nav-icon"},Be):null,q("span",{className:"persona-history-nav-label persona-history-truncate",text:ve.label}),ve.badge?q("span",{className:"persona-history-nav-badge",text:ve.badge}):null);Fo.addEventListener("click",()=>ve.onSelect()),Xe.appendChild(Fo)}return Xe},Lt=null,jn=null,rt=()=>{!Lt||!M||S!=="rail"||E===jn||(jn=E,t.railSections.forEach((N,de)=>{if(!N.render)return;let De=Lt[de],Xe=N.title?De.firstElementChild:null,ve=null;try{ve=N.render(E)}catch(Be){N.render=void 0,console.warn("[persona] history rail section threw",N.id,Be)}De.replaceChildren(...Xe?[Xe]:[],...ve?[ve]:[]),De.hidden=!ve}))},Zt=()=>{let N=t.railSections;if(Ge.classList.toggle("persona-history-view--has-nav",S==="rail"&&!!N?.some(de=>de.placement==="above-conversations")),!!N?.length){if(S!=="rail"){Lt?.forEach(de=>de.remove());return}Lt??(Lt=N.map(Dt));for(let de of["above-conversations","below-conversations","footer"]){let De=de==="above-conversations"?It.parentNode===Gt?It:vt:null;N.forEach((Xe,ve)=>{Xe.placement===de&&Gt.insertBefore(Lt[ve],De)})}rt()}};Zt(),Wp(Ge,"persona-history-view",fT);let ln=(N,de)=>{let De=Ge.ownerDocument.defaultView?.getComputedStyle(Ge).getPropertyValue(N),Xe=Number.parseFloat(De??"");return Number.isFinite(Xe)&&Xe>=0?Xe:de},K=(N,de)=>Ge.ownerDocument.defaultView?.getComputedStyle(Ge).getPropertyValue(N).trim()||de,ae=null,A=()=>{ae!==null&&(clearTimeout(ae),ae=null),Ge.removeEventListener("animationend",A),Ge.classList.remove("persona-history-view--enter")};Ge.addEventListener("animationend",A),ae=setTimeout(()=>{ae=setTimeout(A,ln("--persona-history-enter-ms",lB)+60)},0);let T=null,V=()=>{T!==null&&(clearTimeout(T),T=null),F.classList.remove("persona-history-topbar--shell-enter")},U=()=>{V(),F.classList.add("persona-history-topbar--shell-enter"),T=setTimeout(V,AT+60)};Ot==="external"&&(T=setTimeout(V,AT+60));let ee=[],me=null,J=()=>{if(me)return me;if(b||uB()||typeof Ge.animate!="function")return A(),null;let N=Ge.ownerDocument.defaultView?.getComputedStyle(Gt).opacity||"1";A(),Ge.style.pointerEvents="none",Le.style.pointerEvents="none";let de={duration:ln("--persona-history-exit-ms",cB),easing:K("--persona-history-exit-easing",dB),fill:"forwards"},De=pB[S];return ee=[Gt.animate([{opacity:N,transform:"none"},{opacity:0,transform:`translateX(${De}px)`}],de)],me=Promise.all(ee.map(mB)).then(()=>{}),me},re=(N,de)=>{N&&(de?N.setAttribute("aria-disabled","true"):N.removeAttribute("aria-disabled"))},Le=F,Me=null,mt=()=>{let N=t.slots?.header;if(!N)return;let de=`${S}|${Gu(u)}|${d?`${d.kind}:${"conversationId"in d?d.conversationId:""}`:""}`;if(de===Me)return;Me=de;let De=N({identityStatus:u,pendingAction:d,copy:e,defaultRenderer:()=>F})??F;De!==Le&&(Le.replaceWith(De),Le=De)},ct=null,zt=()=>{if(!t.showScopeStatus)return;let N=Gu(u);if(N===ct)return;ct=N;let de=MT(u,e);Q.textContent=de.title;let De=fB(u);if(Z.hidden=!De,qe.replaceChildren(...De?[]:[q("span",{className:"persona-history-scope-alert-title",text:de.title})],q("span",{className:"persona-history-scope-description",text:de.description,attrs:{id:ke}})),qe.setAttribute("data-persona-history-scope-tone",De?"ambient":"attention"),De?Z.setAttribute("aria-describedby",ke):Z.removeAttribute("aria-describedby"),de.pending?qe.setAttribute("role","status"):qe.removeAttribute("role"),qe.setAttribute("data-persona-history-identity",u.state),Z.setAttribute("data-persona-history-identity",u.state),gB(u)){let Xe=q("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});Xe.addEventListener("click",()=>{z()||Ae("refresh")}),qe.appendChild(Xe)}},ft=N=>d?d.kind==="open"&&d.conversationId===N?"opening":d.kind==="delete"&&d.conversationId===N?"deleting":null:null,Je=()=>{let N=document.activeElement;return!(N instanceof HTMLElement)||!Ge.contains(N)?null:N.getAttribute("data-persona-history-focus")},et=N=>{if(g&&h){g=!1;let de=Ge.querySelector(`[data-persona-history-focus="${Lc(h)}"]`);if(de){de.focus();return}}N&&Ge.querySelector(`[data-persona-history-focus="${N}"]`)?.focus()},xt=()=>{if(!L)return null;let N=q("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),de=L;return N.addEventListener("click",()=>{z()||de.retry()}),q("div",{className:"persona-history-row-error",attrs:{role:"alert"}},q("span",{text:de.message}),N)},Hn=()=>hT(s,n(),e,t.grouping).map((N,de)=>{let De=`${r}-g${de}`,Xe=q("ul",{className:"persona-history-list",attrs:{"aria-labelledby":De}});for(let ve of N.items){let Be=()=>vT({conversation:ve,active:ve.id===p,pending:ft(ve.id),busy:z(),menuOpen:h===ve.id,error:D.get(ve.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{Rn(ve.id)},onToggleMenu:()=>Ci(ve.id),onCloseMenu:_r=>We(_r),onDelete:()=>{gt(ve.id)}}),$o=t.slots?.conversation?.({conversation:ve,active:ve.id===p,pending:ft(ve.id),open:()=>Rn(ve.id),requestDelete:()=>gt(ve.id),defaultRenderer:Be})??Be();Xe.appendChild($o instanceof HTMLLIElement?$o:q("li",{className:"persona-history-item"},$o))}return q("div",{className:"persona-history-group",attrs:{"data-persona-history-group":N.key}},q("h3",{className:Bt("persona-history-group-heading",N.key==="recent"&&"persona-history-sr-only"),text:N.label,attrs:{id:De}}),Xe)}),rn=()=>{if(!a)return null;let N=d?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",de=q("button",{className:"persona-history-secondary persona-history-load-more",text:N?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...N?{"aria-busy":"true","aria-disabled":"true"}:{},...z()&&!N?{"aria-disabled":"true"}:{}}});return de.addEventListener("click",()=>{z()||Ae("load-more")}),de},st=()=>{let N=Je(),de=[xt()],De=s.length>0;if(De&&(de.push(...Hn()),de.push(rn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&De)){let ve=l,Be=ve.kind==="loading"?void 0:()=>Ae("refresh"),Fo=ve.kind==="new_conversation_required"?()=>cn():void 0,$o=()=>xT({state:ve,copy:e,identityStatus:u,busy:z(),...Be?{onRetry:()=>{Be()}}:{},...Fo?{onStartNew:()=>{Fo()}}:{}}),_r=t.slots?.state?.({state:ve,identityStatus:u,copy:e,...Be?{retry:Be}:{},...Fo?{startNewConversation:Fo}:{},defaultRenderer:$o});de.push(_r??$o())}vt.replaceChildren(...de.filter(ve=>!!ve)),et(N)},Fe=()=>{let N=l.kind==="loading"&&s.length===0,de=[],De=()=>de.length===0?Lc(vi):`${Lc(vi)}-${de.length}`;if(!N)for(let Xe of je)de.push({label:Xe.label,focusKey:De(),danger:Xe.danger===!0,onSelect:()=>{Xe.onSelect({conversations:[...s]})}});return Ye&&!(s.length===0&&(l.kind==="empty"||N))&&de.push({label:e.clearHistoryLabel,focusKey:De(),danger:!0,onSelect:()=>{Oa()}}),Et&&!N&&de.push({label:e.resetIdentityLabel,focusKey:De(),danger:!0,onSelect:()=>{Da()}}),de},Yt=()=>{if(re(Te,z()),re(xe,z()),lt){let N=Fe(),de=l.kind==="loading"&&s.length===0;lt.hidden=N.length===0&&!de,re(lt,z()||N.length===0),lt.setAttribute("aria-expanded",h===vi?"true":"false");let De=It.querySelector(".persona-history-menu");if(h!==vi||N.length===0)De?.remove();else{let Xe=dy({label:e.listOptionsLabel,items:N,onCloseMenu:ve=>We(ve)});De?De.replaceWith(Xe):It.appendChild(Xe)}}It.hidden=S!=="rail"&&(!lt||lt.hidden)&&(!t.showScopeStatus||Z.hidden)},Qe,Pe=()=>{let N=t.onActiveConversationChange;if(!N)return;let de=s.find(Xe=>Xe.id===p)??null,De=de?`${de.id}\0${de.title}\0${de.starred?1:0}`:"";De!==Qe&&(Qe=De,N(de))},le=()=>{if(!b){if(Pe(),!M){t.onModelChange?.();return}mt(),zt(),Yt(),st(),rt()}},We=N=>{if(!h)return;let de=h;h=null,g=!1,le(),N?.restoreFocus&&Ge.querySelector(`[data-persona-history-focus="menu:${de}"]`)?.focus()},Ci=N=>{if(h===N){We({restoreFocus:!0});return}h=N,g=!0,le()},Dr=N=>{if(!h)return;let de=N.target;de instanceof Node&&Ge.contains(de)&&de.closest?.(`[data-persona-history-item="${h}"]`)||We()};document.addEventListener("pointerdown",Dr,!0);let Lo=N=>{N.key!=="Escape"||!h||(N.stopPropagation(),We({restoreFocus:!0}))};Ge.addEventListener("keydown",Lo);async function Ae(N){if(b)return;let de=++C,De=N==="load-more"?a:null;if(!(N==="load-more"&&!De)){d={kind:N==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:N},N!=="load-more"&&(D.clear(),L=null),We(),le();try{let Xe=await t.provider.list({limit:o,context:t.context,...De?{cursor:De}:{},...t.targetId?{targetId:t.targetId}:{}});if(b||de!==C)return;s=De?[...s,...Xe.items]:Xe.items,a=Xe.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(Xe){if(b||de!==C)return;l=wT(Xe)}finally{!b&&de===C&&(d=null,le())}}}let $e=N=>{s=s.filter(de=>de.id!==N),D.delete(N),p===N&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function Rn(N){if(!(z()||b)){D.delete(N),We(),d={kind:"open",conversationId:N},le();try{if(await t.onSelect(N),b)return;p=N}catch{if(b)return;D.set(N,{message:e.openFailedLabel,retry:()=>{Rn(N)}})}finally{b||(d=null,le())}}}async function gt(N){if(z()||b)return"cancelled";D.delete(N),d={kind:"delete",conversationId:N},le();try{let de=await t.onRequestDeleteConversation(N);return b||de==="deleted"&&($e(N),W(e.conversationRemovedNotice)),de}catch(de){return b||(dp(de)&&de.code==="not_found"?$e(N):D.set(N,{message:e.deleteFailedLabel,retry:()=>{gt(N)}})),"cancelled"}finally{b||(d=null,le())}}async function cn(){if(!(z()||b)){L=null,We(),d={kind:"start-new"},le();try{if(await t.onStartNew(),b)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(b)return;L={message:e.errorDescription,retry:()=>{cn()}}}finally{b||(d=null,le())}}}async function Oa(){if(z()||b)return"cancelled";L=null,We(),d={kind:"clear"},le();try{let N=await t.onRequestClearHistory();return b||N==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},W(e.historyClearedNotice)),N}catch{return b||(L={message:e.errorDescription,retry:()=>{Oa()}}),"cancelled"}finally{b||(d=null,le())}}let Ln={outcome:"cancelled"};async function Da(){if(z()||b||!t.onRequestResetIdentity)return Ln;L=null,We(),d={kind:"reset"},le();try{let N=await t.onRequestResetIdentity();return b||N.outcome==="reset"&&(W(N.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),d=null,await Ae("refresh")),N}catch{return b||(L={message:e.errorDescription,retry:()=>{Da()}}),Ln}finally{!b&&d?.kind==="reset"&&(d=null,le())}}let Ju=t.provider.subscribeIdentityStatus(N=>{if(b)return;let de=Gu(N),De=de!==m;u=N,m=de,le(),De&&N.state!=="verifying"&&W(MT(N,e).title)}),Zu=t.provider.subscribeAvailability?.(N=>{if(!b){if(N){Ae("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},le()}});return le(),Ae("initial"),{element:Ge,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:d,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{z()||await Ae("refresh")},loadMore:async()=>{z()||await Ae("load-more")},openConversation:N=>Rn(N),startNewConversation:()=>cn(),requestDeleteConversation:N=>gt(N),requestClearConversationHistory:()=>Oa(),requestResetHistoryIdentity:()=>Da()},setDomRenderEnabled:N=>{N!==M&&(M=N,N&&le())},refresh:()=>{Ae("refresh")},setPresentation:N=>{if(N===S)return;A(),S=N,Me=null;let de=N==="rail";Ge.classList.toggle("persona-history-view--panel",!de),Ge.classList.toggle("persona-history-view--rail",de),Ge.setAttribute("data-persona-history-presentation",N),X(),hn(),Ee(),ue(),Zt(),le()},setCollapsed:N=>{N!==E&&(E=N,hn(),X(),ue(),rt())},setRailSide:N=>{O=N==="right",Ee()},getHeaderElement:()=>Le,setHeaderPlacement:N=>{if(N===Ot)return;Ot=N;let de=N==="external";if(F.classList.toggle("persona-history-topbar--shell",de),de){U(),Le.remove();return}V(),Ge.insertBefore(Le,Gt)},setActiveConversationId:N=>{p!==N&&(p=N,le())},applyConversationSummary:N=>{let de=s.findIndex(De=>De.id===N.id);de!==-1&&(s[de]=N,le())},removeConversationSummary:N=>{s.some(de=>de.id===N)&&($e(N),le())},setNewConversationRequired:N=>{N?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),le()},playExit:J,destroy:()=>{b=!0,C+=1,A(),V(),be.forEach(N=>N?.destroy()),Le.remove(),ee.forEach(N=>N.cancel()),ee=[],Ju(),Zu?.(),document.removeEventListener("pointerdown",Dr,!0),Ge.removeEventListener("keydown",Lo),B.destroy(),Ge.remove(),Ge.replaceChildren()}}}var aB,vi,lB,AT,cB,dB,pB,uB,mB,TT=we(()=>{"use strict";ga();Ue();mT();gT();kc();ay();ly();CT();ST();Wl();aB=25,vi="persona:list-options",lB=180,AT=120,cB=160,dB="cubic-bezier(0.4, 0, 1, 1)",pB={panel:20,rail:12},uB=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,mB=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var uy=we(()=>{"use strict";TT();kc()});var ET={};Fn(ET,{HISTORY_VIEW_COPY_DEFAULTS:()=>Tc,createHistoryView:()=>py,resolveHistoryViewCopy:()=>Ec});var kT=we(()=>{"use strict";uy();uy()});var JB={};Fn(JB,{createThemePreview:()=>eE});module.exports=w0(JB);Kd();Bf();var hC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,yC=t=>t.includes("|"),bC=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())},k0=t=>`| ${t.join(" | ")} |`,L0=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,P0=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),vC=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
1141
|
-
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!
|
|
1142
|
-
`):t};var CC="var(--persona-md-table-scroll-fade, 24px)",wC=new WeakSet;function SC(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 xC(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":CC),t.style.setProperty("--persona-fade-r",r<=1?"0px":CC)}function Of(t){wC.has(t)||(wC.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&xC(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(xC)}ei();ea();Zn();var{setLoader:w1,load:$0}=Ft({fallbackImport:()=>Promise.resolve().then(()=>(HC(),IC))});var RC=$0;function Ao(t){return t==="card"?"collapsed":t}function ta(t){return t.split(";",1)[0].trim().toLowerCase()}function V0(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(ta(r)===e)return{mode:Ao(s),selector:ta(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(ta(r)===o)return{mode:Ao(s),selector:o}}function z0(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:Ao(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?ta(e.file.mimeType):void 0,d=l?V0(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:Ao(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:Ao(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:Ao(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:Ao(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Ao(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function os(t,e){return z0(t,e).mode}function Sl(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 q0="agent_",U0="flow_";function WC(t){return t.startsWith(q0)?{kind:"agentId",agentId:t}:t.startsWith(U0)?{kind:"flowId",flowId:t}:null}function BC(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=WC(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=WC(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 Jd(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function na(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function OC(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var rs=require("partial-json");Ue();var _f="ask_user_question",Al=8,oa="data-persona-ask-sheet-for",j0="Other",K0="Other\u2026",NC="Type your own answer here",FC="Send",G0="Next",Y0="Back",Q0="Submit all",X0="Skip",J0=3,Nf="data-ask-current-index",Ff="data-ask-question-count",$C="data-ask-answers",$f="data-ask-grouped",VC="data-ask-layout",Z0=t=>t.layout==="pills"?"pills":"rows",eL=t=>t.getAttribute(VC)==="pills"?"pills":"rows",_C=!1,zC=t=>t.replace(/["\\]/g,"\\$&"),ti=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===_f,Vf=t=>t?.features?.askUserQuestion??{},ra=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,rs.parse)(r,rs.STR|rs.OBJ|rs.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ml=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Al&&!_C&&(_C=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Al}.`)),e.slice(0,Al)},tL=t=>Ml(t)[0]??null,nL=(t,e)=>Ml(t)[e]??null,oL=(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))},qC=(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},rL=(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=qC(n,o,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},sL=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},iL=(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<J0;u++)s.appendChild(sL(o));return s}if(d.forEach((u,m)=>{s.appendChild(rL(u,m,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?j0:K0;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??NC,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??u),h.appendChild(g),m.appendChild(h);let b=qC(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},UC=(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??NC,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??FC,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},aL=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??FC,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},lL=(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??Y0,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??X0,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??Q0:n.nextLabel??G0,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ni=t=>{let e=t.getAttribute($C);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},jC=(t,e)=>{t.setAttribute($C,JSON.stringify(e))},Mo=t=>{let e=Number(t.getAttribute(Nf)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},cL=(t,e)=>{t.setAttribute(Nf,String(Math.max(0,Math.floor(e))))},sa=t=>{let e=Number(t.getAttribute(Ff)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ss=t=>t.getAttribute($f)==="true",dL=(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},pL=(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)))},Zd=(t,e)=>{let{payload:n}=ra(e),o=Ml(n),r=ni(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},KC=t=>{let e=ni(t),n=Mo(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="")},GC=t=>{if(!ss(t))return;let e=ni(t),n=Mo(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}},zf=(t,e,n)=>{let o=Vf(n),r=eL(t),{payload:s,complete:a}=ra(e),l=ss(t),d=Mo(t),p=sa(t),u=l?nL(s,d):tL(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 E=typeof u?.question=="string"?u.question:"";b.textContent=E,b.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let E=iL(u,o,a,r);C.replaceWith(E)}if(r!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(UC(o,r))}let S=t.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!S?t.appendChild(aL(o)):(!m||l)&&S&&S.remove(),t.setAttribute("data-multi-select",m?"true":"false");let I=t.querySelector('[data-ask-nav-row="true"]');if(l){let E=lL(d,p,o);I?I.replaceWith(E):t.appendChild(E)}else I&&I.remove();KC(t),GC(t)},uL=(t,e,n)=>{let o=Vf(e),r=Z0(o),s=t.toolCall.id,a=Ml(n),l=Math.max(1,a.length),d=l>1,p=dL(t,a),u=d?pL(t,l):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(oa,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(Ff,String(l)),m.setAttribute(Nf,String(u)),m.setAttribute($f,d?"true":"false"),m.setAttribute(VC,r),jC(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`),oL(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(UC(o,r)),zf(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},mL=(t,e,n)=>{let{payload:o}=ra(e),r=Math.max(1,Ml(o).length);r>sa(t)&&(t.setAttribute(Ff,String(r)),r>1&&!ss(t)&&t.setAttribute($f,"true")),zf(t,e,n)};var ep=(t,e,n)=>{if(!n||!ti(t)||Vf(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${oa}]`).forEach(p=>{p.getAttribute(oa)!==r&&p.remove()});let a=n.querySelector(`[${oa}="${zC(r)}"]`);if(a){mL(a,t,e);return}let{payload:l}=ra(t),d=uL(t,e,l);n.appendChild(d)},ia=(t,e)=>{if(!t)return;let n=e?`[${oa}="${zC(e)}"]`:`[${oa}]`;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)})},qf=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),is=(t,e)=>{let n=ni(t),o=Mo(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,jC(t,n),KC(t),GC(t)},tp=(t,e,n,o)=>{let r=sa(t),s=Math.max(0,Math.min(r-1,o));cL(t,s),zf(t,e,n)};var as="suggest_replies";var fL={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},QC={name:as,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:fL,origin:"sdk",annotations:{readOnlyHint:!0}},XC=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Tl=t=>t.variant==="tool"&&t.toolCall?.name===as,gL=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},JC=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Tl(n))continue;let o=gL(n.toolCall?.args);return o.length>0?o:null}return null},YC=new Set,hL=(t,e,n)=>{let o=`${t}:${e}:${n}`;YC.has(o)||(YC.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},ls=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&&hL(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 yL={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Al,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},bL={name:_f,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:yL,origin:"sdk",annotations:{readOnlyHint:!0}},np=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(bL),ls(t).expose&&e.push(QC),e};oi();var iw="4.21.1";var ds=iw;var la="[Image]";function aw(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function ip(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function nr(t){return{type:"text",text:t}}function lw(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var cw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],SL=["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"],Lr=[...cw,...SL];function AL(t){return cw.includes(t)||t.startsWith("image/")}function ap(t){return AL(t.type)}function dw(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function pw(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ap(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 uw(t,e=Lr,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 ML(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function mw(t,e){let n=ML(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 TL=["user","assistant","system"],EL=0;function fw(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function lp(t){return typeof t=="string"?t:void 0}function kL(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?nr(e.text):null;case"image":return typeof e.image=="string"?lw(e.image,{mimeType:lp(e.mimeType),alt:lp(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?dw(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...lp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...lp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function LL(t,e){let n=fw(e),o=t.map(a=>fw(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:EL+h;s=l+1}return r.map(a=>new Date(a).toISOString())}function gw(t,e){let n=LL(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!TL.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(kL).filter(u=>u!==null),p=aw(d);o.push({id:r.id,role:a,content:p||(ip(d)?la:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Pl(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 Il(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 PL="https://api.runtype.com/v1/dispatch",hw="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)}},yw=32768,jf=49152,bw=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:typeof e.flowId=="string"?e.flowId: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:""}},vw=t=>"reason"in t?t.reason:void 0,Cw="The identity proof was not admitted; account history is unavailable",ww="The identity proof was rejected",xw="The request carried no visitor credential",Sw="The stored visitor belongs to a different signed-in user",Kf=(t,e)=>t instanceof at&&t.code===e;function IL(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 Gf=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 HL(t){switch(t){case"json":return rw;case"regex-json":return ow;case"xml":return sw;default:return nw}}var Aw=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function RL(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=Aw(n);if(!Aw(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Ll(t);return Ll(e)!==null&&a===null?e:t}var Hl=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??PL,this.headers={"Content-Type":"application/json","X-Persona-Version":ds,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??HL(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 RC().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:TC,getToolDisplayTitle:Yd,loadPolyfill:kC});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=BC(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$/,"")||hw}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":ds,"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&&vw(n)===vw(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":ds},body:JSON.stringify(d)});if(p.status===400&&o){let m={...d};delete m.durableRecovery,p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ds},body:JSON.stringify(m)})}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??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...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(!Kf(r,"not_found")&&!Kf(r,"visitor_required")&&!Kf(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":ds},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",Cw);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",ww);if(r.includes("visitor token required"))throw new at("visitor_token_missing",xw);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",Sw);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",Cw);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",ww)):r.includes("visitor token required")?new at("visitor_token_missing",xw):r.includes("visitor_identity_mismatch")?new at("visitor_identity_mismatch",Sw):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":ds,...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(bw),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}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:bw(r),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>yw)throw new at("payload_too_large",`displayContent exceeds the ${yw} character limit`);o+=p}if(o>jf)throw new at("payload_too_large",`Display projection batch exceeds the ${jf} 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<=jf,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=OC();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(Gf).map(b=>{let C=u?Pl(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":ds,...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?EC(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(/\/+$/,"")||hw}/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=[...np(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(Gf).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=[...np(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(Gf).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=[...np(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=K=>{let ae=K.reasoning?{...K.reasoning,chunks:[...K.reasoning.chunks]}:void 0,A=K.toolCall?{...K.toolCall,chunks:K.toolCall.chunks?[...K.toolCall.chunks]:void 0}:void 0,T=K.tools?K.tools.map(V=>({...V,chunks:V.chunks?[...V.chunks]:void 0})):void 0;return{...K,reasoning:ae,toolCall:A,tools:T}},h=K=>{if(K.role!=="assistant"||K.variant)return!0;let ae=Array.isArray(K.contentParts)&&K.contentParts.length>0,A=typeof K.rawContent=="string"&&K.rawContent.trim()!=="";return typeof K.content=="string"&&K.content.trim()!==""||ae||A||!!K.stopReason},g=K=>{h(K)&&n({type:"message",message:m(K)})},b=null,C=null,S={current:null},I={current:null},E=null,O="",M=new Map,D=new Map,L=new Map,B=new Map,W=new Map,z={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=K=>{if(K==null)return null;try{return String(K)}catch{return null}},k=K=>w(K.stepId??K.step_id??K.step??K.parentId??K.flowStepId??K.flow_step_id),R=K=>w(K.callId??K.call_id??K.requestId??K.request_id??K.toolCallId??K.tool_call_id??K.stepId??K.step_id),_=o,X=!1,j=()=>{if(b)return b;let K,ae="",A=E;return!X&&_?(K=_,X=!0,ae=r??""):_&&A?K=`${_}_${A}`:K=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:K,role:"assistant",content:ae,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},g(b),b},Q=(K,ae)=>{z.lastId=ae,K&&z.byStep.set(K,ae)},Z=(K,ae)=>{let A=K.reasoningId??K.id,T=k(K);if(A){let U=String(A);return Q(T,U),U}if(T){let U=z.byStep.get(T);if(U)return z.lastId=U,U}if(z.lastId&&!ae)return z.lastId;if(!ae)return null;let V=`reason-${u()}`;return Q(T,V),V},ie=K=>{let ae=B.get(K);if(ae)return ae;let A={id:`reason-${K}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:K,status:"streaming",chunks:[]}};return B.set(K,A),g(A),A},se=(K,ae)=>{H.lastId=ae,K&&H.byCall.set(K,ae)},pe=new Set,ue=new Map,xe=new Set,be=new Map,F=K=>{if(!K)return!1;let ae=K.replace(/_+/g,"_").replace(/^_|_$/g,"");return ae==="emit_artifact_markdown"||ae==="emit_artifact_component"},Ce=(K,ae)=>{let A=K.toolId??K.id,T=R(K);if(A){let U=String(A);return se(T,U),U}if(T){let U=H.byCall.get(T);if(U)return H.lastId=U,U}if(H.lastId&&!ae)return H.lastId;if(!ae)return null;let V=`tool-${u()}`;return se(T,V),V},Ee=K=>{let ae=W.get(K);if(ae)return ae;let A={id:`tool-${K}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:K,status:"pending"}};return W.set(K,A),g(A),A},qe=K=>{if(typeof K=="number"&&Number.isFinite(K))return K;if(typeof K=="string"){let ae=Number(K);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let A=Date.parse(K);if(!Number.isNaN(A))return A}return Date.now()},ke=K=>{if(typeof K=="string")return K;if(K==null)return"";try{return JSON.stringify(K)}catch{return String(K)}},Ie=new Map,Te=new Map,vt=new Map,Ye=(K,ae,A)=>{let T=vt.get(K);T||(T=[],vt.set(K,T));let V=0,U=T.length;for(;V<U;){let me=V+U>>>1;T[me].seq<ae?V=me+1:U=me}T[V]?.seq===ae?T[V]={seq:ae,text:A}:T.splice(V,0,{seq:ae,text:A});let ee="";for(let me=0;me<T.length;me++)ee+=T[me].text;return ee},Et=(K,ae)=>{let A=ke(ae),T=Te.get(K.id),V=RL(T,A);K.rawContent=V;let U=Ie.get(K.id),ee=Me=>{let mt=K.content??"";Me.trim()!==""&&(mt.trim().length===0||Me.startsWith(mt)||Me.trimStart().startsWith(mt.trim()))&&(K.content=Me)},me=()=>{if(U){let Me=U.close?.();Me instanceof Promise&&Me.catch(()=>{})}Ie.delete(K.id),Te.delete(K.id),K.streaming=!1,g(K)};if(!U){ee(A),me();return}let J=Ll(V);if(J!==null&&J.trim()!==""){ee(J),me();return}let re=Me=>{let mt=typeof Me=="string"?Me:Me?.text??null;if(mt!==null&&mt.trim()!=="")return mt;let ct=U.getExtractedText();return ct!==null&&ct.trim()!==""?ct:A},Le;try{Le=U.processChunk(V)}catch{ee(A),me();return}if(Le instanceof Promise){Le.then(Me=>{ee(re(Me)),me()}).catch(()=>{ee(A),me()});return}ee(re(Le)),me()},je=null,lt=(K,ae,A,T)=>{K.rawContent=ae,Ie.has(K.id)||Ie.set(K.id,this.createStreamParser());let V=Ie.get(K.id),U=ae.trim().startsWith("{")||ae.trim().startsWith("[");if(U&&Te.set(K.id,ae),V.__isPlainTextParser===!0){K.content=T!==void 0?ae:K.content+A,Te.delete(K.id),Ie.delete(K.id),K.rawContent=void 0,g(K);return}let me=V.processChunk(ae);if(me instanceof Promise)me.then(J=>{let re=typeof J=="string"?J:J?.text??null;re!==null&&re.trim()!==""?(K.content=re,g(K)):!U&&!ae.trim().startsWith("<")&&(K.content=T!==void 0?ae:K.content+A,Te.delete(K.id),Ie.delete(K.id),K.rawContent=void 0,g(K))}).catch(()=>{K.content=T!==void 0?ae:K.content+A,Te.delete(K.id),Ie.delete(K.id),K.rawContent=void 0,g(K)});else{let J=typeof me=="string"?me:me?.text??null;J!==null&&J.trim()!==""?(K.content=J,g(K)):!U&&!ae.trim().startsWith("<")&&(K.content=T!==void 0?ae:K.content+A,Te.delete(K.id),Ie.delete(K.id),K.rawContent=void 0,g(K))}},Vt=(K,ae)=>{let A=ae??K.content;if(A==null||A===""){K.streaming=!1,g(K);return}let V=Te.get(K.id)??ke(A);K.rawContent=V;let U=Ie.get(K.id),ee=null,me=!1;if(U&&(ee=U.getExtractedText(),ee===null&&(ee=Ll(V)),ee===null)){let J=U.processChunk(V);J instanceof Promise?(me=!0,J.then(re=>{let Le=typeof re=="string"?re:re?.text??null;Le!==null&&(K.content=Le,K.streaming=!1,Ie.delete(K.id),Te.delete(K.id),g(K))}).catch(()=>{})):ee=typeof J=="string"?J:J?.text??null}if(!me){ee!==null&&ee.trim()!==""?K.content=ee:Te.has(K.id)||(K.content=ke(A));let J=Ie.get(K.id);if(J){let re=J.close?.();re instanceof Promise&&re.catch(()=>{}),Ie.delete(K.id)}Te.delete(K.id),K.streaming=!1,g(K)}},It=(K,ae,A)=>{let T=D.get(K);if(T)return T;let V={id:`nested-${ae}-${K}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...A?{variant:A}:{},...A==="reasoning"?{reasoning:{id:K,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ae}};return D.set(K,V),g(V),V},Gt=[],Ot,Ge=new Map,hn=0,Dt="agent",Lt=!1,jn=null,rt=null,Zt=new Map,ln=this.config.iterationDisplay??"separate";for(Ot=()=>{for(let K=0;K<Gt.length;K++){let ae=Gt[K].payloadType,A=Gt[K].payload;if(!Lt&&Dt!=="flow"&&typeof A.stepType=="string"&&(Dt="flow"),ae==="reasoning_start"){let T=typeof A.id=="string"?A.id:null,V=typeof A.parentToolCallId=="string"&&A.parentToolCallId?A.parentToolCallId:null;if(T&&V){M.set(T,V),It(T,V,"reasoning");continue}let U=Z(A,!0)??`reason-${u()}`,ee=ie(U);ee.reasoning=ee.reasoning??{id:U,status:"streaming",chunks:[]},ee.reasoning.startedAt=ee.reasoning.startedAt??qe(A.startedAt??A.timestamp),ee.reasoning.completedAt=void 0,ee.reasoning.durationMs=void 0,(A.scope==="loop"||A.scope==="turn")&&(ee.reasoning.scope=A.scope),ee.streaming=!0,ee.reasoning.status="streaming",g(ee)}else if(ae==="reasoning_delta"){let T=typeof A.id=="string"?A.id:null;if(T&&M.has(T)&&D.has(T)){let me=D.get(T),J=A.reasoningText??A.text??A.delta??"";J&&A.hidden!==!0&&me.reasoning&&(me.reasoning.chunks.push(String(J)),g(me));continue}let V=Z(A,!1)??Z(A,!0)??`reason-${u()}`,U=ie(V);U.reasoning=U.reasoning??{id:V,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??qe(A.startedAt??A.timestamp);let ee=A.reasoningText??A.text??A.delta??"";if(ee&&A.hidden!==!0){let me=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(me!==void 0){let J=Ye(V,me,String(ee));U.reasoning.chunks=[J]}else U.reasoning.chunks.push(String(ee))}if(U.reasoning.status=A.done?"complete":"streaming",A.done){U.reasoning.completedAt=qe(A.completedAt??A.timestamp);let me=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-me)}U.streaming=U.reasoning.status!=="complete",g(U)}else if(ae==="reasoning_complete"){let T=typeof A.id=="string"?A.id:null;if(T&&M.has(T)&&D.has(T)){let J=D.get(T);if(J.reasoning){let re=typeof A.text=="string"?A.text:"";re&&J.reasoning.chunks.length===0&&J.reasoning.chunks.push(re),J.reasoning.status="complete",J.streaming=!1,g(J)}M.delete(T),D.delete(T);continue}let V=Z(A,!1)??Z(A,!0)??`reason-${u()}`,U=typeof A.text=="string"?A.text:"";!B.get(V)&&(U||A.scope==="loop")&&ie(V);let ee=B.get(V);if(ee?.reasoning){(A.scope==="loop"||A.scope==="turn")&&(ee.reasoning.scope=A.scope),U&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push(U),ee.reasoning.status="complete",ee.reasoning.completedAt=qe(A.completedAt??A.timestamp);let J=ee.reasoning.startedAt??Date.now();ee.reasoning.durationMs=Math.max(0,(ee.reasoning.completedAt??Date.now())-J),ee.streaming=!1,g(ee)}let me=k(A);me&&z.byStep.delete(me)}else if(ae==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof A.iteration=="number"&&(hn=A.iteration);let T=(typeof A.toolCallId=="string"?A.toolCallId:void 0)??Ce(A,!0)??`tool-${u()}`,V=A.toolName??A.name;if(F(V)){pe.add(T);continue}se(R(A),T);let U=Ee(T),ee=U.toolCall??{id:T,status:"pending"};ee.name=V??ee.name,ee.status="running",A.parameters!==void 0?ee.args=A.parameters:A.args!==void 0&&(ee.args=A.args),ee.startedAt=ee.startedAt??qe(A.startedAt??A.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,U.toolCall=ee,U.streaming=!0,A.executionId&&(U.agentMetadata={executionId:A.executionId,iteration:A.iteration}),g(U)}else if(ae==="tool_output_delta"){let T=Ce(A,!1)??Ce(A,!0)??`tool-${u()}`;if(pe.has(T))continue;let V=Ee(T),U=V.toolCall??{id:T,status:"running"};U.startedAt=U.startedAt??qe(A.startedAt??A.timestamp);let ee=A.text??A.delta??A.message??"";ee&&(U.chunks=U.chunks??[],U.chunks.push(String(ee))),U.status="running",V.toolCall=U,V.streaming=!0;let me=A.agentContext;(me||A.executionId)&&(V.agentMetadata=V.agentMetadata??{executionId:me?.executionId??A.executionId,iteration:me?.iteration??A.iteration}),g(V)}else if(ae==="tool_complete"){let T=Ce(A,!1)??Ce(A,!0)??`tool-${u()}`;if(pe.has(T)){pe.delete(T);continue}let V=Ee(T),U=V.toolCall??{id:T,status:"running"};U.status="complete",A.result!==void 0&&(U.result=A.result),typeof A.duration=="number"&&(U.duration=A.duration),U.completedAt=qe(A.completedAt??A.timestamp);let ee=A.duration??A.executionTime;if(typeof ee=="number")U.durationMs=ee;else{let re=U.startedAt??Date.now();U.durationMs=Math.max(0,(U.completedAt??Date.now())-re)}V.toolCall=U,V.streaming=!1;let me=A.agentContext;(me||A.executionId)&&(V.agentMetadata=V.agentMetadata??{executionId:me?.executionId??A.executionId,iteration:me?.iteration??A.iteration}),g(V);let J=R(A);J&&H.byCall.delete(J)}else if(ae==="await"&&A.toolName){let T=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,V=T??A.toolId??`local-${u()}`,U=Ee(V),ee=A.toolName,me=A.origin==="webmcp"&&!Zi(ee)?`webmcp:${ee}`:ee,J=Zi(me),re=U.toolCall??{id:V,status:"pending"};re.name=me,re.args=A.parameters,re.status=J?"running":"complete",re.chunks=re.chunks??[],re.startedAt=re.startedAt??qe(A.startedAt??A.timestamp??A.awaitedAt),J?(re.completedAt=void 0,re.duration=void 0,re.durationMs=void 0):re.completedAt=re.completedAt??re.startedAt,U.toolCall=re,U.streaming=!1,U.agentMetadata={...U.agentMetadata,executionId:A.executionId??U.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(U)}else if(ae==="text_start"){let T=typeof A.id=="string"?A.id:null,V=typeof A.parentToolCallId=="string"&&A.parentToolCallId?A.parentToolCallId:null;if(T&&V){M.set(T,V);continue}let U=b;U&&(Dt==="flow"?(Vt(U),je=U):(U.streaming=!1,g(U)),b=null),E=typeof A.id=="string"?A.id:E,O=""}else if(ae==="text_delta"){let T=typeof A.id=="string"?A.id:null,V=T?M.get(T):void 0;if(T&&V){let me=typeof A.delta=="string"?A.delta:"",J=(L.get(T)??"")+me;if(L.set(T,J),J.trim()==="")continue;let re=It(T,V);re.agentMetadata={...re.agentMetadata,executionId:A.executionId,parentToolId:V},lt(re,J,me,void 0);continue}if(E=typeof A.id=="string"?A.id:E,Dt==="flow"){let me=typeof A.delta=="string"?A.delta:"";if(O+=me,O.trim()==="")continue;let J=j();J.agentMetadata={executionId:A.executionId,iteration:A.iteration},lt(J,O,me,void 0),C=J;continue}let U=typeof A.delta=="string"?A.delta:"";O+=U;let ee=j();ee.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:jn??void 0,agentName:rt?.agentName},lt(ee,O,U,void 0),C=ee}else if(ae==="text_complete"){let T=typeof A.id=="string"?A.id:null;if(T&&M.has(T)){let U=D.get(T);U&&Vt(U),M.delete(T),L.delete(T),D.delete(T);continue}let V=b;V&&(Dt==="flow"?(Vt(V),je=V):((V.content??"")===""&&typeof A.text=="string"&&(V.content=A.text),V.streaming=!1,g(V)),b=null),E=null,O=""}else if(ae==="step_complete"){let T=A.stepType,V=A.executionType;if(T==="tool"||V==="context")continue;if(A.success===!1){let U=A.error,ee=typeof U=="string"&&U!==""?U:U!=null&&typeof U=="object"&&Reflect.has(U,"message")?String(U.message??"Step failed"):"Step failed";n({type:"error",error:new Error(ee)});let me=b;me&&me.streaming&&(me.streaming=!1,g(me)),n({type:"status",status:"idle"});continue}{let U=je;je=null;let ee=A.stopReason,me=A.result?.response;if(U)ee&&(U.stopReason=ee),me!=null?Et(U,me):U.streaming!==!1&&(Ie.delete(U.id),Te.delete(U.id),U.streaming=!1,g(U));else{let J=me!=null&&me!=="";if(J||ee){let re=j();ee&&(re.stopReason=ee),J?Vt(re,me):(re.streaming=!1,g(re))}}continue}}else if(ae==="execution_start")Dt=A.kind==="flow"?"flow":"agent",Lt=!0,Dt==="agent"&&(rt={executionId:A.executionId,agentId:A.agentId??"virtual",agentName:A.agentName??"",status:"running",currentIteration:0,maxTurns:A.maxTurns??1,startedAt:qe(A.startedAt)});else if(ae==="turn_start"){let T=typeof A.iteration=="number"?A.iteration:hn;if(T!==hn){if(rt&&(rt.currentIteration=T),ln==="separate"&&T>1){let V=b;V&&(V.streaming=!1,g(V),Zt.set(T-1,V),b=null)}hn=T}jn=typeof A.id=="string"?A.id:null,C=null}else if(ae==="tool_input_delta"){let T=A.toolCallId??H.lastId;if(T){let V=W.get(T);V?.toolCall&&(V.toolCall.chunks=V.toolCall.chunks??[],V.toolCall.chunks.push(A.delta??""),g(V))}}else{if(ae==="tool_input_complete")continue;if(ae==="turn_complete"){let T=A.stopReason,V=b??C;if(T&&V!==null){let U=A.id;(!U||V.agentMetadata?.turnId===U)&&(V.stopReason=T,g(V))}jn===A.id&&(jn=null)}else if(ae==="media_start"){let T=String(A.id);Ge.set(T,{mediaType:typeof A.mediaType=="string"?A.mediaType:void 0,role:typeof A.role=="string"?A.role:void 0,toolCallId:A.toolCallId,parts:[]})}else if(ae==="media_delta"){let T=Ge.get(String(A.id));T&&typeof A.delta=="string"&&T.parts.push(A.delta)}else if(ae==="media_complete"){let T=String(A.id),V=Ge.get(T);Ge.delete(T);let U=(typeof A.mediaType=="string"?A.mediaType:void 0)??V?.mediaType??"application/octet-stream",ee=typeof A.data=="string"?A.data:void 0,me=typeof A.url=="string"?A.url:V&&V.parts.length>0?V.parts.join(""):void 0,J=null;if(ee)J={type:"media",data:ee,mediaType:U};else if(me){let mt=U.toLowerCase();J={type:mt==="image"||mt.startsWith("image/")?"image-url":"file-url",url:me,mediaType:U}}let re=A.toolCallId??V?.toolCallId,Le=J?[J]:[],Me=[];for(let mt of Le){if(!mt||typeof mt!="object")continue;let ct=mt,zt=typeof ct.type=="string"?ct.type:void 0,ft=typeof ct.mediaType=="string"?ct.mediaType.toLowerCase():"",Je=null,et="";if(zt==="media"){let xt=typeof ct.data=="string"?ct.data:void 0;if(!xt)continue;et=ft.length>0?ft:"application/octet-stream",Je=`data:${et};base64,${xt}`}else if(zt==="image-url"){let xt=typeof ct.url=="string"?ct.url:void 0;if(!xt)continue;et=ft,Je=xt}else if(zt==="file-url"){let xt=typeof ct.url=="string"?ct.url:void 0;if(!xt)continue;et=ft,Je=xt}else continue;if(Je)if(zt==="image-url"||et.startsWith("image/"))Me.push({type:"image",image:Je,...et.includes("/")?{mimeType:et}:{}});else if(et.startsWith("audio/"))Me.push({type:"audio",audio:Je,mimeType:et});else if(et.startsWith("video/"))Me.push({type:"video",video:Je,mimeType:et});else{let xt=et||"application/octet-stream";Me.push({type:"file",data:Je,mimeType:xt,filename:IL(xt)})}}if(Me.length>0){let mt=u(),ct=re,ft={id:`agent-media-${typeof ct=="string"&&ct.length>0?`${ct}-${mt}`:String(mt)}`,role:"assistant",content:"",contentParts:Me,createdAt:new Date().toISOString(),streaming:!1,sequence:mt,agentMetadata:{executionId:A.executionId,iteration:typeof A.iteration=="number"?A.iteration:hn}};g(ft);let Je=b;Je&&(Je.streaming=!1,g(Je)),b=null,S.current=null}}else if(ae==="execution_complete"){let T=A.kind??Dt;T==="agent"&&rt&&(rt.status=A.success?"complete":"error",rt.completedAt=qe(A.completedAt),rt.stopReason=A.stopReason);let V=b;V&&(T==="flow"&&V.streaming!==!1?Vt(V):(V.streaming=!1,g(V)),b=null),E=null,O="",je=null,n({type:"status",status:"idle",terminal:!0})}else if(ae==="execution_error"){let T=typeof A.error=="string"?A.error:A.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(ae!=="ping"){if(ae==="approval_start"){let T=A.approvalId??`approval-${u()}`,V={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:T,status:"pending",agentId:rt?.agentId??"virtual",executionId:A.executionId??rt?.executionId??"",toolName:A.toolName??"",toolType:A.toolType,description:A.description??`Execute ${A.toolName??"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(V)}else if(ae==="step_await"&&A.awaitReason==="approval_required"){let T=A.approvalId??`approval-${u()}`,V={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:T,status:"pending",agentId:rt?.agentId??"virtual",executionId:A.executionId??rt?.executionId??"",toolName:A.toolName??"",toolType:A.toolType,description:A.description??`Execute ${A.toolName??"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(V)}else if(ae==="approval_complete"){let T=A.approvalId;if(T){let U={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:T,status:A.decision??"approved",agentId:rt?.agentId??"virtual",executionId:A.executionId??rt?.executionId??"",toolName:A.toolName??"",description:A.description??"",resolvedAt:Date.now()}};g(U)}}else if(ae==="artifact_start"||ae==="artifact_delta"||ae==="artifact_update"||ae==="artifact_complete"){if(ae==="artifact_start"){let T=A.artifactType,V=String(A.id),U=typeof A.title=="string"?A.title:void 0,ee=A.file,me;ee&&typeof ee=="object"&&!Array.isArray(ee)&&typeof ee.path=="string"&&typeof ee.mimeType=="string"&&(me={path:ee.path,mimeType:ee.mimeType,...typeof ee.language=="string"?{language:ee.language}:{}}),n({type:"artifact_start",id:V,artifactType:T,title:U,component:typeof A.component=="string"?A.component:void 0,...me?{file:me}:{}});let J=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?{...A.props}:void 0;if(be.set(V,{markdown:"",title:U,file:me,...J?{props:J}:{}}),!xe.has(V)){xe.add(V);let re=os(this.config.features?.artifacts,{artifactType:T,...me?{file:me}:{}}),Le=typeof A.component=="string"?A.component:void 0,Me={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Sl(re,{artifactId:V,title:U,artifactType:T,status:"streaming",...me?{file:me}:{},...Le?{component:Le}:{}})};ue.set(V,Me),g(Me)}}else if(ae==="artifact_delta"){let T=String(A.id),V=typeof A.delta=="string"?A.delta:String(A.delta??"");n({type:"artifact_delta",id:T,artDelta:V});let U=be.get(T);U&&(U.markdown+=V)}else if(ae==="artifact_update"){let T=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:T,component:typeof A.component=="string"?A.component:void 0});let V=be.get(String(A.id));V&&(V.props={...V.props??{},...T})}else if(ae==="artifact_complete"){let T=String(A.id);n({type:"artifact_complete",id:T});let V=ue.get(T);if(V){V.streaming=!1;try{let U=JSON.parse(V.rawContent??"{}");if(U.props){U.props.status="complete";let ee=be.get(T);ee?.markdown&&(U.props.markdown=ee.markdown),ee?.file&&(U.props.file=ee.file),U.component==="PersonaArtifactInline"&&ee?.props&&Object.keys(ee.props).length>0&&(U.props.componentProps=ee.props)}V.rawContent=JSON.stringify(U)}catch{}be.delete(T),g(V),ue.delete(T)}}}else if(ae==="transcript_insert"){let T=A.message;if(!T||typeof T!="object")continue;let V=String(T.id??`msg-${u()}`),U=T.role,me={id:V,role:U==="user"?"user":U==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:u()};if(g(me),me.rawContent)try{let re=JSON.parse(me.rawContent)?.props?.artifactId;typeof re=="string"&&xe.add(re)}catch{}b=null,S.current=null,Ie.delete(V),Te.delete(V)}else if(ae==="error"){if(A.recoverable===!1&&A.error!=null&&A.error!==""){let T=typeof A.error=="string"?A.error:A.error?.message!=null?String(A.error.message):"Execution error";n({type:"error",error:new Error(T)});let V=b;V&&V.streaming&&(V.streaming=!1,g(V)),n({type:"status",status:"idle"})}}else if(ae==="step_error"||ae==="dispatch_error"||ae==="flow_error"){let T=null;if(A.error instanceof Error)T=A.error;else if(ae==="dispatch_error"){let V=A.message??A.error;V!=null&&V!==""&&(T=new Error(String(V)))}else{let V=A.error;typeof V=="string"&&V!==""?T=new Error(V):V!=null&&typeof V=="object"&&Reflect.has(V,"message")&&(T=new Error(String(V.message??V)))}if(T){n({type:"error",error:T});let V=b;V&&V.streaming&&(V.streaming=!1,g(V)),n({type:"status",status:"idle"})}}}}}Gt.length=0};;){let{done:K,value:ae}=await s.read();if(K)break;l+=a.decode(ae,{stream:!0});let A=l.split(`
|
|
1140
|
+
`});function iy(t){if(!t)return Ku;let e={...Ku};for(let n of JW){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var JW,Ku,ay=we(()=>{"use strict";JW=["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"],Ku={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 kc(t){if(!t)return Ec;let e={...Ec};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function cr(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var Ec,Lc=we(()=>{"use strict";ay();Ec={...Ku,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 ZW(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function cy(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function eB(t,e){let n=cy(t,e),o=ZW(e);if(n>=o)return"today";if(n>=o-ly)return"yesterday";if(n>=o-7*ly)return"previous-7-days";if(n>=o-30*ly)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function tB(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(cy(e,n));return cr(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function CT(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=eB(a.updatedAt,e),d=s[s.length-1];if(d&&d.key===l){d.items.push(a);continue}s.push({key:l,label:tB(l,a.updatedAt,e,n),items:[a]})}return s}function wT(t,e,n){let o=Math.max(0,e-cy(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return cr(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return cr(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return cr(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?cr(n.relativeWeeks,{value:l}):cr(n.relativeYears,{value:Math.floor(a/365)})}function xT(t,e){return t===1?e.messageCountLabelOne:cr(e.messageCountLabel,{count:t})}var ly,dy=we(()=>{"use strict";Lc();ly=864e5});function ws(t,e=20){let n=document.createElementNS(Gu,"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(Gu,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=oB[t];if(o){let r=document.createElementNS(Gu,"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 nB[t]){let s=document.createElementNS(Gu,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var Gu,nB,oB,py=we(()=>{"use strict";Gu="http://www.w3.org/2000/svg",nB={"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:[]},oB={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function sB(t){let e=q("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return rB.test(t)?e.appendChild(q("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function ST(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=ws("star",11);return g.setAttribute("fill","currentColor"),g.setAttribute("stroke-width","1"),q("span",{className:"persona-history-row-star"},g,q("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,d=q("div",{className:"persona-history-row-head"},q("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,q("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:wT(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?q("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=q("button",{className:Dt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":iB(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?sB(t.avatar):null,q("div",{className:"persona-history-row-body"},d,p,q("span",{className:"persona-history-row-count persona-history-sr-only",text:xT(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let m=t.showDelete?uy({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:aB(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return q("li",{className:Dt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,m,t.menuOpen&&t.showDelete?lB(t):null,t.error?cB(t.error,n,e.id):null)}function lB(t){let{conversation:e,copy:n}=t;return my({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Pc(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function uy(t){let e=q("button",{className:Dt("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(ws("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 my(t){let e=q("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=q("button",{className:Dt("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 cB(t,e,n){let o=q("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),q("div",{className:"persona-history-row-error",attrs:{role:"alert"}},q("span",{text:t.message}),o)}var rB,iB,aB,Pc,AT=we(()=>{"use strict";qe();py();dy();rB=/^(https?:|\/|data:)/i;iB=t=>`row:${t}`,aB=t=>`menu:${t}`,Pc=t=>`menu-item:${t}`});function dB(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 MT(t){if(up(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=dB(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function pB(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 uB(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 Yu(t,e,n,o){let r=q("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 Ic(t,e,n,o,r){return q("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},q("p",{className:"persona-history-state-title",text:e}),q("p",{className:"persona-history-state-description",text:n}),o)}function mB(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>q("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},q("div",{className:"persona-history-skeleton-head"},q("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),q("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),q("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return q("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function TT(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return mB(n);if(e.kind==="empty"){let l=pB(t.identityStatus,n);return l?Ic("identity",l.title,l.description,t.onRetry?Yu(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Ic("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?cr(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Ic("rate_limited",n.rateLimitedTitle,l,t.onRetry?Yu(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Ic("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Yu(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=uB(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Ic("error",r,s,e.retryable&&t.onRetry?Yu(a,"state-retry",o,t.onRetry):null,!0)}var ET=we(()=>{"use strict";qe();Lc();Bl()});function Qu(t){return`${t.state}:${"reason"in t?t.reason:""}`}function LT(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 wB(t){return t.state==="verified"||t.state==="browser_only"}function xB(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function fy(t){let e=kc(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??fB,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=Qu(u),h=null,g=!1,b=!1,C=0,S=t.presentation,I=t.collapsible!==!1,E=t.collapsed===!0,O=t.railSide==="right",M=t.renderDom!==!1,D=new Map,L=null,B=hT(),W=N=>{!M&&t.onAnnounce?t.onAnnounce(N):B.announce(N)},z=()=>d!==null,H=`${r}-body`,w=q("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),k=()=>S==="rail"&&I,R,_=()=>{if(t.railBrand){if(!k()){w.classList.remove("persona-history-back--branded");return}if(R===void 0){let N=t.railBrand(!0);R=N?q("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},N):null}R&&(w.classList.add("persona-history-back--branded"),w.appendChild(R))}},X=()=>{let N=k(),de=S==="rail";w.setAttribute("data-persona-history-focus",N?"collapse":"close"),w.setAttribute("aria-label",N?E?e.expandLabel:e.collapseLabel:de?e.closeLabel:e.backLabel),N?(w.setAttribute("aria-expanded",E?"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(ws(N?"panel-left":de?"x":"arrow-left")),_()};X(),w.addEventListener("click",()=>{k()?t.onToggleCollapse?.():t.onClose()});let j=q("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),Q=q("span",{className:"persona-history-scope-title"}),Z=q("p",{className:"persona-history-scope"},q("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},ws("monitor",14)),Q),ie=q("div",{className:"persona-history-heading-group"},j),se=!1,pe,ue=()=>{let N=S==="rail",de=N?t.renderRailHeader:void 0,Oe=null,Je=de!==void 0;if(de)try{Oe=de({collapsed:E,defaultTitle:e.viewTitle})}catch(ve){Je=!1,se||(se=!0,console.warn("[persona] history rail renderHeader threw",ve))}if(!Je&&N&&t.railBrand){if(pe===void 0){let ve=t.railBrand(!1);pe=ve?q("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},q("span",{className:"persona-history-brand-mark"},ve),q("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}pe&&(Je=!0,Oe=pe)}j.classList.toggle("persona-history-sr-only",Je),ie.replaceChildren(j),Oe&&ie.appendChild(Oe)};ue();let xe=q("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});xe.appendChild(ws("plus")),xe.addEventListener("click",()=>{pn()});let be=[w,xe].map(N=>t.attachTooltip?.({anchor:N,text:()=>N.getAttribute("aria-label")??"",...N===w&&t.collapseShortcut?{hint:()=>k()?t.collapseShortcut.hint:""}:{}})),F=q("div",{className:"persona-history-topbar"}),Ce=null,Ee=()=>{let N=S==="rail",de=N?O?"rail-right":"rail":"panel";de!==Ce&&(Ce=de,de==="rail"?F.append(ie,w):F.append(w,ie),N?xe.remove():F.appendChild(xe),Ge.classList.toggle("persona-history-view--rail-right",de==="rail-right"))},Ve=q("div",{className:"persona-history-scope-alert"}),ke=`${r}-scope`,Ie=ws("plus",18),Te=q("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},Ie,q("span",{text:e.newConversationLabel}));Te.addEventListener("click",()=>{pn()});let bt=q("div",{className:"persona-history-list-region"}),Ye=t.showDeleteAll!==!1,Et=!!t.provider.resetDevice,Ue=t.listActions??[],at=Ye||Et||Ue.length>0?uy({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${vi}`,open:!1,inert:!0,iconSize:16,onToggle:()=>Ci(vi)}):null,Ut=q("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),Ht=q("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":vi}},Ut,t.showScopeStatus?Z:null,at),Qt=q("div",{className:"persona-history-body",attrs:{id:H}},t.showScopeStatus?Ve:null,Te,Ht,bt),_t=t.headerPlacement??"inline";_t==="external"&&F.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Ge=q("div",{className:Dt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},B.element,_t==="inline"?F:null,Qt),bn=()=>{Ge.classList.toggle("persona-history-view--rail-collapsed",E&&k())};bn(),Ee();let Nt=(N,de)=>{let Oe=`${r}-s${de}`,Je=q("div",{className:Dt("persona-history-nav",N.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":N.id,...N.title?{"aria-labelledby":Oe}:{"aria-label":N.id}}});N.title&&Je.appendChild(q("h3",{className:"persona-history-group-heading",text:N.title,attrs:{id:Oe}}));for(let ve of N.items){let Be=ve.iconNode?.()??null,$o=q("button",{className:Dt("persona-history-nav-item",Be&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":ve.label,"data-persona-rail-item":ve.id}},Be?q("span",{className:"persona-history-nav-icon"},Be):null,q("span",{className:"persona-history-nav-label persona-history-truncate",text:ve.label}),ve.badge?q("span",{className:"persona-history-nav-badge",text:ve.badge}):null);$o.addEventListener("click",()=>ve.onSelect()),Je.appendChild($o)}return Je},Pt=null,Kn=null,nt=()=>{!Pt||!M||S!=="rail"||E===Kn||(Kn=E,t.railSections.forEach((N,de)=>{if(!N.render)return;let Oe=Pt[de],Je=N.title?Oe.firstElementChild:null,ve=null;try{ve=N.render(E)}catch(Be){N.render=void 0,console.warn("[persona] history rail section threw",N.id,Be)}Oe.replaceChildren(...Je?[Je]:[],...ve?[ve]:[]),Oe.hidden=!ve}))},tn=()=>{let N=t.railSections;if(Ge.classList.toggle("persona-history-view--has-nav",S==="rail"&&!!N?.some(de=>de.placement==="above-conversations")),!!N?.length){if(S!=="rail"){Pt?.forEach(de=>de.remove());return}Pt??(Pt=N.map(Nt));for(let de of["above-conversations","below-conversations","footer"]){let Oe=de==="above-conversations"?Ht.parentNode===Qt?Ht:bt:null;N.forEach((Je,ve)=>{Je.placement===de&&Qt.insertBefore(Pt[ve],Oe)})}nt()}};tn(),Op(Ge,"persona-history-view",bT);let dn=(N,de)=>{let Oe=Ge.ownerDocument.defaultView?.getComputedStyle(Ge).getPropertyValue(N),Je=Number.parseFloat(Oe??"");return Number.isFinite(Je)&&Je>=0?Je:de},G=(N,de)=>Ge.ownerDocument.defaultView?.getComputedStyle(Ge).getPropertyValue(N).trim()||de,ae=null,A=()=>{ae!==null&&(clearTimeout(ae),ae=null),Ge.removeEventListener("animationend",A),Ge.classList.remove("persona-history-view--enter")};Ge.addEventListener("animationend",A),ae=setTimeout(()=>{ae=setTimeout(A,dn("--persona-history-enter-ms",gB)+60)},0);let T=null,V=()=>{T!==null&&(clearTimeout(T),T=null),F.classList.remove("persona-history-topbar--shell-enter")},U=()=>{V(),F.classList.add("persona-history-topbar--shell-enter"),T=setTimeout(V,kT+60)};_t==="external"&&(T=setTimeout(V,kT+60));let ee=[],me=null,J=()=>{if(me)return me;if(b||vB()||typeof Ge.animate!="function")return A(),null;let N=Ge.ownerDocument.defaultView?.getComputedStyle(Qt).opacity||"1";A(),Ge.style.pointerEvents="none",Le.style.pointerEvents="none";let de={duration:dn("--persona-history-exit-ms",hB),easing:G("--persona-history-exit-easing",yB),fill:"forwards"},Oe=bB[S];return ee=[Qt.animate([{opacity:N,transform:"none"},{opacity:0,transform:`translateX(${Oe}px)`}],de)],me=Promise.all(ee.map(CB)).then(()=>{}),me},re=(N,de)=>{N&&(de?N.setAttribute("aria-disabled","true"):N.removeAttribute("aria-disabled"))},Le=F,Me=null,ut=()=>{let N=t.slots?.header;if(!N)return;let de=`${S}|${Qu(u)}|${d?`${d.kind}:${"conversationId"in d?d.conversationId:""}`:""}`;if(de===Me)return;Me=de;let Oe=N({identityStatus:u,pendingAction:d,copy:e,defaultRenderer:()=>F})??F;Oe!==Le&&(Le.replaceWith(Oe),Le=Oe)},lt=null,jt=()=>{if(!t.showScopeStatus)return;let N=Qu(u);if(N===lt)return;lt=N;let de=LT(u,e);Q.textContent=de.title;let Oe=wB(u);if(Z.hidden=!Oe,Ve.replaceChildren(...Oe?[]:[q("span",{className:"persona-history-scope-alert-title",text:de.title})],q("span",{className:"persona-history-scope-description",text:de.description,attrs:{id:ke}})),Ve.setAttribute("data-persona-history-scope-tone",Oe?"ambient":"attention"),Oe?Z.setAttribute("aria-describedby",ke):Z.removeAttribute("aria-describedby"),de.pending?Ve.setAttribute("role","status"):Ve.removeAttribute("role"),Ve.setAttribute("data-persona-history-identity",u.state),Z.setAttribute("data-persona-history-identity",u.state),xB(u)){let Je=q("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});Je.addEventListener("click",()=>{z()||Ae("refresh")}),Ve.appendChild(Je)}},mt=N=>d?d.kind==="open"&&d.conversationId===N?"opening":d.kind==="delete"&&d.conversationId===N?"deleting":null:null,Ze=()=>{let N=document.activeElement;return!(N instanceof HTMLElement)||!Ge.contains(N)?null:N.getAttribute("data-persona-history-focus")},et=N=>{if(g&&h){g=!1;let de=Ge.querySelector(`[data-persona-history-focus="${Pc(h)}"]`);if(de){de.focus();return}}N&&Ge.querySelector(`[data-persona-history-focus="${N}"]`)?.focus()},wt=()=>{if(!L)return null;let N=q("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),de=L;return N.addEventListener("click",()=>{z()||de.retry()}),q("div",{className:"persona-history-row-error",attrs:{role:"alert"}},q("span",{text:de.message}),N)},Wn=()=>CT(s,n(),e,t.grouping).map((N,de)=>{let Oe=`${r}-g${de}`,Je=q("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Oe}});for(let ve of N.items){let Be=()=>ST({conversation:ve,active:ve.id===p,pending:mt(ve.id),busy:z(),menuOpen:h===ve.id,error:D.get(ve.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{Bn(ve.id)},onToggleMenu:()=>Ci(ve.id),onCloseMenu:Nr=>We(Nr),onDelete:()=>{ft(ve.id)}}),Vo=t.slots?.conversation?.({conversation:ve,active:ve.id===p,pending:mt(ve.id),open:()=>Bn(ve.id),requestDelete:()=>ft(ve.id),defaultRenderer:Be})??Be();Je.appendChild(Vo instanceof HTMLLIElement?Vo:q("li",{className:"persona-history-item"},Vo))}return q("div",{className:"persona-history-group",attrs:{"data-persona-history-group":N.key}},q("h3",{className:Dt("persona-history-group-heading",N.key==="recent"&&"persona-history-sr-only"),text:N.label,attrs:{id:Oe}}),Je)}),an=()=>{if(!a)return null;let N=d?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",de=q("button",{className:"persona-history-secondary persona-history-load-more",text:N?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...N?{"aria-busy":"true","aria-disabled":"true"}:{},...z()&&!N?{"aria-disabled":"true"}:{}}});return de.addEventListener("click",()=>{z()||Ae("load-more")}),de},rt=()=>{let N=Ze(),de=[wt()],Oe=s.length>0;if(Oe&&(de.push(...Wn()),de.push(an())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Oe)){let ve=l,Be=ve.kind==="loading"?void 0:()=>Ae("refresh"),$o=ve.kind==="new_conversation_required"?()=>pn():void 0,Vo=()=>TT({state:ve,copy:e,identityStatus:u,busy:z(),...Be?{onRetry:()=>{Be()}}:{},...$o?{onStartNew:()=>{$o()}}:{}}),Nr=t.slots?.state?.({state:ve,identityStatus:u,copy:e,...Be?{retry:Be}:{},...$o?{startNewConversation:$o}:{},defaultRenderer:Vo});de.push(Nr??Vo())}bt.replaceChildren(...de.filter(ve=>!!ve)),et(N)},_e=()=>{let N=l.kind==="loading"&&s.length===0,de=[],Oe=()=>de.length===0?Pc(vi):`${Pc(vi)}-${de.length}`;if(!N)for(let Je of Ue)de.push({label:Je.label,focusKey:Oe(),danger:Je.danger===!0,onSelect:()=>{Je.onSelect({conversations:[...s]})}});return Ye&&!(s.length===0&&(l.kind==="empty"||N))&&de.push({label:e.clearHistoryLabel,focusKey:Oe(),danger:!0,onSelect:()=>{Da()}}),Et&&!N&&de.push({label:e.resetIdentityLabel,focusKey:Oe(),danger:!0,onSelect:()=>{_a()}}),de},Xt=()=>{if(re(Te,z()),re(xe,z()),at){let N=_e(),de=l.kind==="loading"&&s.length===0;at.hidden=N.length===0&&!de,re(at,z()||N.length===0),at.setAttribute("aria-expanded",h===vi?"true":"false");let Oe=Ht.querySelector(".persona-history-menu");if(h!==vi||N.length===0)Oe?.remove();else{let Je=my({label:e.listOptionsLabel,items:N,onCloseMenu:ve=>We(ve)});Oe?Oe.replaceWith(Je):Ht.appendChild(Je)}}Ht.hidden=S!=="rail"&&(!at||at.hidden)&&(!t.showScopeStatus||Z.hidden)},Qe,Pe=()=>{let N=t.onActiveConversationChange;if(!N)return;let de=s.find(Je=>Je.id===p)??null,Oe=de?`${de.id}\0${de.title}\0${de.starred?1:0}`:"";Oe!==Qe&&(Qe=Oe,N(de))},le=()=>{if(!b){if(Pe(),!M){t.onModelChange?.();return}ut(),jt(),Xt(),rt(),nt()}},We=N=>{if(!h)return;let de=h;h=null,g=!1,le(),N?.restoreFocus&&Ge.querySelector(`[data-persona-history-focus="menu:${de}"]`)?.focus()},Ci=N=>{if(h===N){We({restoreFocus:!0});return}h=N,g=!0,le()},_r=N=>{if(!h)return;let de=N.target;de instanceof Node&&Ge.contains(de)&&de.closest?.(`[data-persona-history-item="${h}"]`)||We()};document.addEventListener("pointerdown",_r,!0);let Po=N=>{N.key!=="Escape"||!h||(N.stopPropagation(),We({restoreFocus:!0}))};Ge.addEventListener("keydown",Po);async function Ae(N){if(b)return;let de=++C,Oe=N==="load-more"?a:null;if(!(N==="load-more"&&!Oe)){d={kind:N==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:N},N!=="load-more"&&(D.clear(),L=null),We(),le();try{let Je=await t.provider.list({limit:o,context:t.context,...Oe?{cursor:Oe}:{},...t.targetId?{targetId:t.targetId}:{}});if(b||de!==C)return;s=Oe?[...s,...Je.items]:Je.items,a=Je.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(Je){if(b||de!==C)return;l=MT(Je)}finally{!b&&de===C&&(d=null,le())}}}let Ne=N=>{s=s.filter(de=>de.id!==N),D.delete(N),p===N&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function Bn(N){if(!(z()||b)){D.delete(N),We(),d={kind:"open",conversationId:N},le();try{if(await t.onSelect(N),b)return;p=N}catch{if(b)return;D.set(N,{message:e.openFailedLabel,retry:()=>{Bn(N)}})}finally{b||(d=null,le())}}}async function ft(N){if(z()||b)return"cancelled";D.delete(N),d={kind:"delete",conversationId:N},le();try{let de=await t.onRequestDeleteConversation(N);return b||de==="deleted"&&(Ne(N),W(e.conversationRemovedNotice)),de}catch(de){return b||(up(de)&&de.code==="not_found"?Ne(N):D.set(N,{message:e.deleteFailedLabel,retry:()=>{ft(N)}})),"cancelled"}finally{b||(d=null,le())}}async function pn(){if(!(z()||b)){L=null,We(),d={kind:"start-new"},le();try{if(await t.onStartNew(),b)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(b)return;L={message:e.errorDescription,retry:()=>{pn()}}}finally{b||(d=null,le())}}}async function Da(){if(z()||b)return"cancelled";L=null,We(),d={kind:"clear"},le();try{let N=await t.onRequestClearHistory();return b||N==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},W(e.historyClearedNotice)),N}catch{return b||(L={message:e.errorDescription,retry:()=>{Da()}}),"cancelled"}finally{b||(d=null,le())}}let Pn={outcome:"cancelled"};async function _a(){if(z()||b||!t.onRequestResetIdentity)return Pn;L=null,We(),d={kind:"reset"},le();try{let N=await t.onRequestResetIdentity();return b||N.outcome==="reset"&&(W(N.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),d=null,await Ae("refresh")),N}catch{return b||(L={message:e.errorDescription,retry:()=>{_a()}}),Pn}finally{!b&&d?.kind==="reset"&&(d=null,le())}}let em=t.provider.subscribeIdentityStatus(N=>{if(b)return;let de=Qu(N),Oe=de!==m;u=N,m=de,le(),Oe&&N.state!=="verifying"&&W(LT(N,e).title)}),tm=t.provider.subscribeAvailability?.(N=>{if(!b){if(N){Ae("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},le()}});return le(),Ae("initial"),{element:Ge,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:d,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{z()||await Ae("refresh")},loadMore:async()=>{z()||await Ae("load-more")},openConversation:N=>Bn(N),startNewConversation:()=>pn(),requestDeleteConversation:N=>ft(N),requestClearConversationHistory:()=>Da(),requestResetHistoryIdentity:()=>_a()},setDomRenderEnabled:N=>{N!==M&&(M=N,N&&le())},refresh:()=>{Ae("refresh")},setPresentation:N=>{if(N===S)return;A(),S=N,Me=null;let de=N==="rail";Ge.classList.toggle("persona-history-view--panel",!de),Ge.classList.toggle("persona-history-view--rail",de),Ge.setAttribute("data-persona-history-presentation",N),X(),bn(),Ee(),ue(),tn(),le()},setCollapsed:N=>{N!==E&&(E=N,bn(),X(),ue(),nt())},setRailSide:N=>{O=N==="right",Ee()},getHeaderElement:()=>Le,setHeaderPlacement:N=>{if(N===_t)return;_t=N;let de=N==="external";if(F.classList.toggle("persona-history-topbar--shell",de),de){U(),Le.remove();return}V(),Ge.insertBefore(Le,Qt)},setActiveConversationId:N=>{p!==N&&(p=N,le())},applyConversationSummary:N=>{let de=s.findIndex(Oe=>Oe.id===N.id);de!==-1&&(s[de]=N,le())},removeConversationSummary:N=>{s.some(de=>de.id===N)&&(Ne(N),le())},setNewConversationRequired:N=>{N?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),le()},playExit:J,destroy:()=>{b=!0,C+=1,A(),V(),be.forEach(N=>N?.destroy()),Le.remove(),ee.forEach(N=>N.cancel()),ee=[],em(),tm?.(),document.removeEventListener("pointerdown",_r,!0),Ge.removeEventListener("keydown",Po),B.destroy(),Ge.remove(),Ge.replaceChildren()}}}var fB,vi,gB,kT,hB,yB,bB,vB,CB,PT=we(()=>{"use strict";ha();qe();yT();vT();Lc();dy();py();AT();ET();Bl();fB=25,vi="persona:list-options",gB=180,kT=120,hB=160,yB="cubic-bezier(0.4, 0, 1, 1)",bB={panel:20,rail:12},vB=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,CB=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var gy=we(()=>{"use strict";PT();Lc()});var IT={};$n(IT,{HISTORY_VIEW_COPY_DEFAULTS:()=>Ec,createHistoryView:()=>fy,resolveHistoryViewCopy:()=>kc});var HT=we(()=>{"use strict";gy();gy()});var s1={};$n(s1,{createThemePreview:()=>rE});module.exports=M0(s1);Gd();Df();var bC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,vC=t=>t.includes("|"),CC=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())},H0=t=>`| ${t.join(" | ")} |`,R0=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,W0=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),wC=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
1141
|
+
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!vC(r)||bC.test(r)||!bC.test(s))continue;let a=CC(r).length;if(a<1)continue;let l=R0(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()===""||!vC(p))break;let u=H0(W0(CC(p),a));e[d]!==u&&(e[d]=u,n=!0)}o=d-1}return n?e.join(`
|
|
1142
|
+
`):t};var xC="var(--persona-md-table-scroll-fade, 24px)",SC=new WeakSet;function MC(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 AC(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":xC),t.style.setProperty("--persona-fade-r",r<=1?"0px":xC)}function _f(t){SC.has(t)||(SC.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&AC(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(AC)}ei();ta();eo();var{setLoader:k1,load:j0}=zt({fallbackImport:()=>Promise.resolve().then(()=>(WC(),RC))});var BC=j0;function Mo(t){return t==="card"?"collapsed":t}function na(t){return t.split(";",1)[0].trim().toLowerCase()}function K0(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(na(r)===e)return{mode:Mo(s),selector:na(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(na(r)===o)return{mode:Mo(s),selector:o}}function G0(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?na(e.file.mimeType):void 0,d=l?K0(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 os(t,e){return G0(t,e).mode}function Al(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 Y0="agent_",Q0="flow_";function OC(t){return t.startsWith(Y0)?{kind:"agentId",agentId:t}:t.startsWith(Q0)?{kind:"flowId",flowId:t}:null}function DC(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=OC(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=OC(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 ep(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function oa(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function _C(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var rs=require("partial-json");qe();var Ff="ask_user_question",Ml=8,ra="data-persona-ask-sheet-for",X0="Other",J0="Other\u2026",$C="Type your own answer here",VC="Send",Z0="Next",eL="Back",tL="Submit all",nL="Skip",oL=3,$f="data-ask-current-index",Vf="data-ask-question-count",zC="data-ask-answers",zf="data-ask-grouped",qC="data-ask-layout",rL=t=>t.layout==="pills"?"pills":"rows",sL=t=>t.getAttribute(qC)==="pills"?"pills":"rows",FC=!1,UC=t=>t.replace(/["\\]/g,"\\$&"),ti=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Ff,qf=t=>t?.features?.askUserQuestion??{},sa=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,rs.parse)(r,rs.STR|rs.OBJ|rs.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Tl=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Ml&&!FC&&(FC=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ml}.`)),e.slice(0,Ml)},iL=t=>Tl(t)[0]??null,aL=(t,e)=>Tl(t)[e]??null,lL=(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))},jC=(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},cL=(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=jC(n,o,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},dL=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},pL=(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<oL;u++)s.appendChild(dL(o));return s}if(d.forEach((u,m)=>{s.appendChild(cL(u,m,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?X0:J0;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??$C,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??u),h.appendChild(g),m.appendChild(h);let b=jC(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},KC=(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??$C,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??VC,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},uL=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??VC,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},mL=(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??eL,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??nL,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??tL:n.nextLabel??Z0,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ni=t=>{let e=t.getAttribute(zC);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},GC=(t,e)=>{t.setAttribute(zC,JSON.stringify(e))},To=t=>{let e=Number(t.getAttribute($f)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},fL=(t,e)=>{t.setAttribute($f,String(Math.max(0,Math.floor(e))))},ia=t=>{let e=Number(t.getAttribute(Vf)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ss=t=>t.getAttribute(zf)==="true",gL=(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},hL=(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)))},tp=(t,e)=>{let{payload:n}=sa(e),o=Tl(n),r=ni(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},YC=t=>{let e=ni(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="")},QC=t=>{if(!ss(t))return;let e=ni(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}},Uf=(t,e,n)=>{let o=qf(n),r=sL(t),{payload:s,complete:a}=sa(e),l=ss(t),d=To(t),p=ia(t),u=l?aL(s,d):iL(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 E=typeof u?.question=="string"?u.question:"";b.textContent=E,b.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let E=pL(u,o,a,r);C.replaceWith(E)}if(r!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(KC(o,r))}let S=t.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!S?t.appendChild(uL(o)):(!m||l)&&S&&S.remove(),t.setAttribute("data-multi-select",m?"true":"false");let I=t.querySelector('[data-ask-nav-row="true"]');if(l){let E=mL(d,p,o);I?I.replaceWith(E):t.appendChild(E)}else I&&I.remove();YC(t),QC(t)},yL=(t,e,n)=>{let o=qf(e),r=rL(o),s=t.toolCall.id,a=Tl(n),l=Math.max(1,a.length),d=l>1,p=gL(t,a),u=d?hL(t,l):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ra,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(Vf,String(l)),m.setAttribute($f,String(u)),m.setAttribute(zf,d?"true":"false"),m.setAttribute(qC,r),GC(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`),lL(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(KC(o,r)),Uf(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},bL=(t,e,n)=>{let{payload:o}=sa(e),r=Math.max(1,Tl(o).length);r>ia(t)&&(t.setAttribute(Vf,String(r)),r>1&&!ss(t)&&t.setAttribute(zf,"true")),Uf(t,e,n)};var np=(t,e,n)=>{if(!n||!ti(t)||qf(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${ra}]`).forEach(p=>{p.getAttribute(ra)!==r&&p.remove()});let a=n.querySelector(`[${ra}="${UC(r)}"]`);if(a){bL(a,t,e);return}let{payload:l}=sa(t),d=yL(t,e,l);n.appendChild(d)},aa=(t,e)=>{if(!t)return;let n=e?`[${ra}="${UC(e)}"]`:`[${ra}]`;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)})},jf=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),is=(t,e)=>{let n=ni(t),o=To(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,GC(t,n),YC(t),QC(t)},op=(t,e,n,o)=>{let r=ia(t),s=Math.max(0,Math.min(r-1,o));fL(t,s),Uf(t,e,n)};var as="suggest_replies";var vL={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},JC={name:as,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:vL,origin:"sdk",annotations:{readOnlyHint:!0}},ZC=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),El=t=>t.variant==="tool"&&t.toolCall?.name===as,CL=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},ew=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!El(n))continue;let o=CL(n.toolCall?.args);return o.length>0?o:null}return null},XC=new Set,wL=(t,e,n)=>{let o=`${t}:${e}:${n}`;XC.has(o)||(XC.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},ls=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&&wL(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 xL={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ml,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},SL={name:Ff,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:xL,origin:"sdk",annotations:{readOnlyHint:!0}},rp=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(SL),ls(t).expose&&e.push(JC),e};oi();var cw="4.22.0";var ds=cw;var ca="[Image]";function dw(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function lp(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function nr(t){return{type:"text",text:t}}function pw(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var uw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],PL=["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"],Pr=[...uw,...PL];function IL(t){return uw.includes(t)||t.startsWith("image/")}function cp(t){return IL(t.type)}function mw(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function fw(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;cp(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 gw(t,e=Pr,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 HL(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function hw(t,e){let n=HL(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 RL=["user","assistant","system"],WL=0;function yw(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function dp(t){return typeof t=="string"?t:void 0}function BL(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?nr(e.text):null;case"image":return typeof e.image=="string"?pw(e.image,{mimeType:dp(e.mimeType),alt:dp(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?mw(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...dp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...dp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function OL(t,e){let n=yw(e),o=t.map(a=>yw(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:WL+h;s=l+1}return r.map(a=>new Date(a).toISOString())}function bw(t,e){let n=OL(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!RL.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(BL).filter(u=>u!==null),p=dw(d);o.push({id:r.id,role:a,content:p||(lp(d)?ca:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Il(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 Hl(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 DL="https://api.runtype.com/v1/dispatch",vw="https://api.runtype.com",st=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Cw=32768,Gf=49152,ww=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:typeof e.flowId=="string"?e.flowId: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:""}},xw=t=>"reason"in t?t.reason:void 0,Sw="The identity proof was not admitted; account history is unavailable",Aw="The identity proof was rejected",Mw="The request carried no visitor credential",Tw="The stored visitor belongs to a different signed-in user",Yf=(t,e)=>t instanceof st&&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 Qf=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 NL(t){switch(t){case"json":return aw;case"regex-json":return iw;case"xml":return lw;default:return sw}}var Ew=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function FL(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=Ew(n);if(!Ew(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Pl(t);return Pl(e)!==null&&a===null?e:t}var Rl=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??DL,this.headers={"Content-Type":"application/json","X-Persona-Version":ds,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??NL(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 BC().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:kC,getToolDisplayTitle:Qd,loadPolyfill:PC});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=DC(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$/,"")||vw}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 st("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":ds,"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&&xw(n)===xw(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":ds},body:JSON.stringify(d)});if(p.status===400&&o){let m={...d};delete m.durableRecovery,p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ds},body:JSON.stringify(m)})}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 st("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 st("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&m.error==="visitor_required"?new st("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new st("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??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...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(!Yf(r,"not_found")&&!Yf(r,"visitor_required")&&!Yf(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 st("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 st("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":ds},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 st("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 st("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 st("proof_not_admitted",Sw);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 st("invalid_identity_proof",Aw);if(r.includes("visitor token required"))throw new st("visitor_token_missing",Mw);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new st("visitor_identity_mismatch",Tw);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new st("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new st("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new st("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 st("proof_not_admitted",Sw);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 st("invalid_identity_proof",Aw)):r.includes("visitor token required")?new st("visitor_token_missing",Mw):r.includes("visitor_identity_mismatch")?new st("visitor_identity_mismatch",Tw):new st("unauthorized",o||"History request was not authorized")}return new st("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 st("identity_contract_violation","Server reported an ignored identity proof on a success response"):new st("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new st("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 st("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":ds,...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 st("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 st("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(ww),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}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:ww(r),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>Cw)throw new st("payload_too_large",`displayContent exceeds the ${Cw} character limit`);o+=p}if(o>Gf)throw new st("payload_too_large",`Display projection batch exceeds the ${Gf} 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<=Gf,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=_C();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(Qf).map(b=>{let C=u?Il(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":ds,...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 st("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 st)&&!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?LC(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(/\/+$/,"")||vw}/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=[...rp(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(Qf).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=[...rp(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(Qf).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=[...rp(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=G=>{let ae=G.reasoning?{...G.reasoning,chunks:[...G.reasoning.chunks]}:void 0,A=G.toolCall?{...G.toolCall,chunks:G.toolCall.chunks?[...G.toolCall.chunks]:void 0}:void 0,T=G.tools?G.tools.map(V=>({...V,chunks:V.chunks?[...V.chunks]:void 0})):void 0;return{...G,reasoning:ae,toolCall:A,tools:T}},h=G=>{if(G.role!=="assistant"||G.variant)return!0;let ae=Array.isArray(G.contentParts)&&G.contentParts.length>0,A=typeof G.rawContent=="string"&&G.rawContent.trim()!=="";return typeof G.content=="string"&&G.content.trim()!==""||ae||A||!!G.stopReason},g=G=>{h(G)&&n({type:"message",message:m(G)})},b=null,C=null,S={current:null},I={current:null},E=null,O="",M=new Map,D=new Map,L=new Map,B=new Map,W=new Map,z={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=G=>{if(G==null)return null;try{return String(G)}catch{return null}},k=G=>w(G.stepId??G.step_id??G.step??G.parentId??G.flowStepId??G.flow_step_id),R=G=>w(G.callId??G.call_id??G.requestId??G.request_id??G.toolCallId??G.tool_call_id??G.stepId??G.step_id),_=o,X=!1,j=()=>{if(b)return b;let G,ae="",A=E;return!X&&_?(G=_,X=!0,ae=r??""):_&&A?G=`${_}_${A}`:G=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:G,role:"assistant",content:ae,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},g(b),b},Q=(G,ae)=>{z.lastId=ae,G&&z.byStep.set(G,ae)},Z=(G,ae)=>{let A=G.reasoningId??G.id,T=k(G);if(A){let U=String(A);return Q(T,U),U}if(T){let U=z.byStep.get(T);if(U)return z.lastId=U,U}if(z.lastId&&!ae)return z.lastId;if(!ae)return null;let V=`reason-${u()}`;return Q(T,V),V},ie=G=>{let ae=B.get(G);if(ae)return ae;let A={id:`reason-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:G,status:"streaming",chunks:[]}};return B.set(G,A),g(A),A},se=(G,ae)=>{H.lastId=ae,G&&H.byCall.set(G,ae)},pe=new Set,ue=new Map,xe=new Set,be=new Map,F=G=>{if(!G)return!1;let ae=G.replace(/_+/g,"_").replace(/^_|_$/g,"");return ae==="emit_artifact_markdown"||ae==="emit_artifact_component"},Ce=(G,ae)=>{let A=G.toolId??G.id,T=R(G);if(A){let U=String(A);return se(T,U),U}if(T){let U=H.byCall.get(T);if(U)return H.lastId=U,U}if(H.lastId&&!ae)return H.lastId;if(!ae)return null;let V=`tool-${u()}`;return se(T,V),V},Ee=G=>{let ae=W.get(G);if(ae)return ae;let A={id:`tool-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:G,status:"pending"}};return W.set(G,A),g(A),A},Ve=G=>{if(typeof G=="number"&&Number.isFinite(G))return G;if(typeof G=="string"){let ae=Number(G);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let A=Date.parse(G);if(!Number.isNaN(A))return A}return Date.now()},ke=G=>{if(typeof G=="string")return G;if(G==null)return"";try{return JSON.stringify(G)}catch{return String(G)}},Ie=new Map,Te=new Map,bt=new Map,Ye=(G,ae,A)=>{let T=bt.get(G);T||(T=[],bt.set(G,T));let V=0,U=T.length;for(;V<U;){let me=V+U>>>1;T[me].seq<ae?V=me+1:U=me}T[V]?.seq===ae?T[V]={seq:ae,text:A}:T.splice(V,0,{seq:ae,text:A});let ee="";for(let me=0;me<T.length;me++)ee+=T[me].text;return ee},Et=(G,ae)=>{let A=ke(ae),T=Te.get(G.id),V=FL(T,A);G.rawContent=V;let U=Ie.get(G.id),ee=Me=>{let ut=G.content??"";Me.trim()!==""&&(ut.trim().length===0||Me.startsWith(ut)||Me.trimStart().startsWith(ut.trim()))&&(G.content=Me)},me=()=>{if(U){let Me=U.close?.();Me instanceof Promise&&Me.catch(()=>{})}Ie.delete(G.id),Te.delete(G.id),G.streaming=!1,g(G)};if(!U){ee(A),me();return}let J=Pl(V);if(J!==null&&J.trim()!==""){ee(J),me();return}let re=Me=>{let ut=typeof Me=="string"?Me:Me?.text??null;if(ut!==null&&ut.trim()!=="")return ut;let lt=U.getExtractedText();return lt!==null&<.trim()!==""?lt:A},Le;try{Le=U.processChunk(V)}catch{ee(A),me();return}if(Le instanceof Promise){Le.then(Me=>{ee(re(Me)),me()}).catch(()=>{ee(A),me()});return}ee(re(Le)),me()},Ue=null,at=(G,ae,A,T)=>{G.rawContent=ae,Ie.has(G.id)||Ie.set(G.id,this.createStreamParser());let V=Ie.get(G.id),U=ae.trim().startsWith("{")||ae.trim().startsWith("[");if(U&&Te.set(G.id,ae),V.__isPlainTextParser===!0){G.content=T!==void 0?ae:G.content+A,Te.delete(G.id),Ie.delete(G.id),G.rawContent=void 0,g(G);return}let me=V.processChunk(ae);if(me instanceof Promise)me.then(J=>{let re=typeof J=="string"?J:J?.text??null;re!==null&&re.trim()!==""?(G.content=re,g(G)):!U&&!ae.trim().startsWith("<")&&(G.content=T!==void 0?ae:G.content+A,Te.delete(G.id),Ie.delete(G.id),G.rawContent=void 0,g(G))}).catch(()=>{G.content=T!==void 0?ae:G.content+A,Te.delete(G.id),Ie.delete(G.id),G.rawContent=void 0,g(G)});else{let J=typeof me=="string"?me:me?.text??null;J!==null&&J.trim()!==""?(G.content=J,g(G)):!U&&!ae.trim().startsWith("<")&&(G.content=T!==void 0?ae:G.content+A,Te.delete(G.id),Ie.delete(G.id),G.rawContent=void 0,g(G))}},Ut=(G,ae)=>{let A=ae??G.content;if(A==null||A===""){G.streaming=!1,g(G);return}let V=Te.get(G.id)??ke(A);G.rawContent=V;let U=Ie.get(G.id),ee=null,me=!1;if(U&&(ee=U.getExtractedText(),ee===null&&(ee=Pl(V)),ee===null)){let J=U.processChunk(V);J instanceof Promise?(me=!0,J.then(re=>{let Le=typeof re=="string"?re:re?.text??null;Le!==null&&(G.content=Le,G.streaming=!1,Ie.delete(G.id),Te.delete(G.id),g(G))}).catch(()=>{})):ee=typeof J=="string"?J:J?.text??null}if(!me){ee!==null&&ee.trim()!==""?G.content=ee:Te.has(G.id)||(G.content=ke(A));let J=Ie.get(G.id);if(J){let re=J.close?.();re instanceof Promise&&re.catch(()=>{}),Ie.delete(G.id)}Te.delete(G.id),G.streaming=!1,g(G)}},Ht=(G,ae,A)=>{let T=D.get(G);if(T)return T;let V={id:`nested-${ae}-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...A?{variant:A}:{},...A==="reasoning"?{reasoning:{id:G,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ae}};return D.set(G,V),g(V),V},Qt=[],_t,Ge=new Map,bn=0,Nt="agent",Pt=!1,Kn=null,nt=null,tn=new Map,dn=this.config.iterationDisplay??"separate";for(_t=()=>{for(let G=0;G<Qt.length;G++){let ae=Qt[G].payloadType,A=Qt[G].payload;if(!Pt&&Nt!=="flow"&&typeof A.stepType=="string"&&(Nt="flow"),ae==="reasoning_start"){let T=typeof A.id=="string"?A.id:null,V=typeof A.parentToolCallId=="string"&&A.parentToolCallId?A.parentToolCallId:null;if(T&&V){M.set(T,V),Ht(T,V,"reasoning");continue}let U=Z(A,!0)??`reason-${u()}`,ee=ie(U);ee.reasoning=ee.reasoning??{id:U,status:"streaming",chunks:[]},ee.reasoning.startedAt=ee.reasoning.startedAt??Ve(A.startedAt??A.timestamp),ee.reasoning.completedAt=void 0,ee.reasoning.durationMs=void 0,(A.scope==="loop"||A.scope==="turn")&&(ee.reasoning.scope=A.scope),ee.streaming=!0,ee.reasoning.status="streaming",g(ee)}else if(ae==="reasoning_delta"){let T=typeof A.id=="string"?A.id:null;if(T&&M.has(T)&&D.has(T)){let me=D.get(T),J=A.reasoningText??A.text??A.delta??"";J&&A.hidden!==!0&&me.reasoning&&(me.reasoning.chunks.push(String(J)),g(me));continue}let V=Z(A,!1)??Z(A,!0)??`reason-${u()}`,U=ie(V);U.reasoning=U.reasoning??{id:V,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??Ve(A.startedAt??A.timestamp);let ee=A.reasoningText??A.text??A.delta??"";if(ee&&A.hidden!==!0){let me=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(me!==void 0){let J=Ye(V,me,String(ee));U.reasoning.chunks=[J]}else U.reasoning.chunks.push(String(ee))}if(U.reasoning.status=A.done?"complete":"streaming",A.done){U.reasoning.completedAt=Ve(A.completedAt??A.timestamp);let me=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-me)}U.streaming=U.reasoning.status!=="complete",g(U)}else if(ae==="reasoning_complete"){let T=typeof A.id=="string"?A.id:null;if(T&&M.has(T)&&D.has(T)){let J=D.get(T);if(J.reasoning){let re=typeof A.text=="string"?A.text:"";re&&J.reasoning.chunks.length===0&&J.reasoning.chunks.push(re),J.reasoning.status="complete",J.streaming=!1,g(J)}M.delete(T),D.delete(T);continue}let V=Z(A,!1)??Z(A,!0)??`reason-${u()}`,U=typeof A.text=="string"?A.text:"";!B.get(V)&&(U||A.scope==="loop")&&ie(V);let ee=B.get(V);if(ee?.reasoning){(A.scope==="loop"||A.scope==="turn")&&(ee.reasoning.scope=A.scope),U&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push(U),ee.reasoning.status="complete",ee.reasoning.completedAt=Ve(A.completedAt??A.timestamp);let J=ee.reasoning.startedAt??Date.now();ee.reasoning.durationMs=Math.max(0,(ee.reasoning.completedAt??Date.now())-J),ee.streaming=!1,g(ee)}let me=k(A);me&&z.byStep.delete(me)}else if(ae==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof A.iteration=="number"&&(bn=A.iteration);let T=(typeof A.toolCallId=="string"?A.toolCallId:void 0)??Ce(A,!0)??`tool-${u()}`,V=A.toolName??A.name;if(F(V)){pe.add(T);continue}se(R(A),T);let U=Ee(T),ee=U.toolCall??{id:T,status:"pending"};ee.name=V??ee.name,ee.status="running",A.parameters!==void 0?ee.args=A.parameters:A.args!==void 0&&(ee.args=A.args),ee.startedAt=ee.startedAt??Ve(A.startedAt??A.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,U.toolCall=ee,U.streaming=!0,A.executionId&&(U.agentMetadata={executionId:A.executionId,iteration:A.iteration}),g(U)}else if(ae==="tool_output_delta"){let T=Ce(A,!1)??Ce(A,!0)??`tool-${u()}`;if(pe.has(T))continue;let V=Ee(T),U=V.toolCall??{id:T,status:"running"};U.startedAt=U.startedAt??Ve(A.startedAt??A.timestamp);let ee=A.text??A.delta??A.message??"";ee&&(U.chunks=U.chunks??[],U.chunks.push(String(ee))),U.status="running",V.toolCall=U,V.streaming=!0;let me=A.agentContext;(me||A.executionId)&&(V.agentMetadata=V.agentMetadata??{executionId:me?.executionId??A.executionId,iteration:me?.iteration??A.iteration}),g(V)}else if(ae==="tool_complete"){let T=Ce(A,!1)??Ce(A,!0)??`tool-${u()}`;if(pe.has(T)){pe.delete(T);continue}let V=Ee(T),U=V.toolCall??{id:T,status:"running"};U.status="complete",A.result!==void 0&&(U.result=A.result),typeof A.duration=="number"&&(U.duration=A.duration),U.completedAt=Ve(A.completedAt??A.timestamp);let ee=A.duration??A.executionTime;if(typeof ee=="number")U.durationMs=ee;else{let re=U.startedAt??Date.now();U.durationMs=Math.max(0,(U.completedAt??Date.now())-re)}V.toolCall=U,V.streaming=!1;let me=A.agentContext;(me||A.executionId)&&(V.agentMetadata=V.agentMetadata??{executionId:me?.executionId??A.executionId,iteration:me?.iteration??A.iteration}),g(V);let J=R(A);J&&H.byCall.delete(J)}else if(ae==="await"&&A.toolName){let T=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,V=T??A.toolId??`local-${u()}`,U=Ee(V),ee=A.toolName,me=A.origin==="webmcp"&&!ea(ee)?`webmcp:${ee}`:ee,J=ea(me),re=U.toolCall??{id:V,status:"pending"};re.name=me,re.args=A.parameters,re.status=J?"running":"complete",re.chunks=re.chunks??[],re.startedAt=re.startedAt??Ve(A.startedAt??A.timestamp??A.awaitedAt),J?(re.completedAt=void 0,re.duration=void 0,re.durationMs=void 0):re.completedAt=re.completedAt??re.startedAt,U.toolCall=re,U.streaming=!1,U.agentMetadata={...U.agentMetadata,executionId:A.executionId??U.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(U)}else if(ae==="text_start"){let T=typeof A.id=="string"?A.id:null,V=typeof A.parentToolCallId=="string"&&A.parentToolCallId?A.parentToolCallId:null;if(T&&V){M.set(T,V);continue}let U=b;U&&(Nt==="flow"?(Ut(U),Ue=U):(U.streaming=!1,g(U)),b=null),E=typeof A.id=="string"?A.id:E,O=""}else if(ae==="text_delta"){let T=typeof A.id=="string"?A.id:null,V=T?M.get(T):void 0;if(T&&V){let me=typeof A.delta=="string"?A.delta:"",J=(L.get(T)??"")+me;if(L.set(T,J),J.trim()==="")continue;let re=Ht(T,V);re.agentMetadata={...re.agentMetadata,executionId:A.executionId,parentToolId:V},at(re,J,me,void 0);continue}if(E=typeof A.id=="string"?A.id:E,Nt==="flow"){let me=typeof A.delta=="string"?A.delta:"";if(O+=me,O.trim()==="")continue;let J=j();J.agentMetadata={executionId:A.executionId,iteration:A.iteration},at(J,O,me,void 0),C=J;continue}let U=typeof A.delta=="string"?A.delta:"";O+=U;let ee=j();ee.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:Kn??void 0,agentName:nt?.agentName},at(ee,O,U,void 0),C=ee}else if(ae==="text_complete"){let T=typeof A.id=="string"?A.id:null;if(T&&M.has(T)){let U=D.get(T);U&&Ut(U),M.delete(T),L.delete(T),D.delete(T);continue}let V=b;V&&(Nt==="flow"?(Ut(V),Ue=V):((V.content??"")===""&&typeof A.text=="string"&&(V.content=A.text),V.streaming=!1,g(V)),b=null),E=null,O=""}else if(ae==="step_complete"){let T=A.stepType,V=A.executionType;if(T==="tool"||V==="context")continue;if(A.success===!1){let U=A.error,ee=typeof U=="string"&&U!==""?U:U!=null&&typeof U=="object"&&Reflect.has(U,"message")?String(U.message??"Step failed"):"Step failed";n({type:"error",error:new Error(ee)});let me=b;me&&me.streaming&&(me.streaming=!1,g(me)),n({type:"status",status:"idle"});continue}{let U=Ue;Ue=null;let ee=A.stopReason,me=A.result?.response;if(U)ee&&(U.stopReason=ee),me!=null?Et(U,me):U.streaming!==!1&&(Ie.delete(U.id),Te.delete(U.id),U.streaming=!1,g(U));else{let J=me!=null&&me!=="";if(J||ee){let re=j();ee&&(re.stopReason=ee),J?Ut(re,me):(re.streaming=!1,g(re))}}continue}}else if(ae==="execution_start")Nt=A.kind==="flow"?"flow":"agent",Pt=!0,Nt==="agent"&&(nt={executionId:A.executionId,agentId:A.agentId??"virtual",agentName:A.agentName??"",status:"running",currentIteration:0,maxTurns:A.maxTurns??1,startedAt:Ve(A.startedAt)});else if(ae==="turn_start"){let T=typeof A.iteration=="number"?A.iteration:bn;if(T!==bn){if(nt&&(nt.currentIteration=T),dn==="separate"&&T>1){let V=b;V&&(V.streaming=!1,g(V),tn.set(T-1,V),b=null)}bn=T}Kn=typeof A.id=="string"?A.id:null,C=null}else if(ae==="tool_input_delta"){let T=A.toolCallId??H.lastId;if(T){let V=W.get(T);V?.toolCall&&(V.toolCall.chunks=V.toolCall.chunks??[],V.toolCall.chunks.push(A.delta??""),g(V))}}else{if(ae==="tool_input_complete")continue;if(ae==="turn_complete"){let T=A.stopReason,V=b??C;if(T&&V!==null){let U=A.id;(!U||V.agentMetadata?.turnId===U)&&(V.stopReason=T,g(V))}Kn===A.id&&(Kn=null)}else if(ae==="media_start"){let T=String(A.id);Ge.set(T,{mediaType:typeof A.mediaType=="string"?A.mediaType:void 0,role:typeof A.role=="string"?A.role:void 0,toolCallId:A.toolCallId,parts:[]})}else if(ae==="media_delta"){let T=Ge.get(String(A.id));T&&typeof A.delta=="string"&&T.parts.push(A.delta)}else if(ae==="media_complete"){let T=String(A.id),V=Ge.get(T);Ge.delete(T);let U=(typeof A.mediaType=="string"?A.mediaType:void 0)??V?.mediaType??"application/octet-stream",ee=typeof A.data=="string"?A.data:void 0,me=typeof A.url=="string"?A.url:V&&V.parts.length>0?V.parts.join(""):void 0,J=null;if(ee)J={type:"media",data:ee,mediaType:U};else if(me){let ut=U.toLowerCase();J={type:ut==="image"||ut.startsWith("image/")?"image-url":"file-url",url:me,mediaType:U}}let re=A.toolCallId??V?.toolCallId,Le=J?[J]:[],Me=[];for(let ut of Le){if(!ut||typeof ut!="object")continue;let lt=ut,jt=typeof lt.type=="string"?lt.type:void 0,mt=typeof lt.mediaType=="string"?lt.mediaType.toLowerCase():"",Ze=null,et="";if(jt==="media"){let wt=typeof lt.data=="string"?lt.data:void 0;if(!wt)continue;et=mt.length>0?mt:"application/octet-stream",Ze=`data:${et};base64,${wt}`}else if(jt==="image-url"){let wt=typeof lt.url=="string"?lt.url:void 0;if(!wt)continue;et=mt,Ze=wt}else if(jt==="file-url"){let wt=typeof lt.url=="string"?lt.url:void 0;if(!wt)continue;et=mt,Ze=wt}else continue;if(Ze)if(jt==="image-url"||et.startsWith("image/"))Me.push({type:"image",image:Ze,...et.includes("/")?{mimeType:et}:{}});else if(et.startsWith("audio/"))Me.push({type:"audio",audio:Ze,mimeType:et});else if(et.startsWith("video/"))Me.push({type:"video",video:Ze,mimeType:et});else{let wt=et||"application/octet-stream";Me.push({type:"file",data:Ze,mimeType:wt,filename:_L(wt)})}}if(Me.length>0){let ut=u(),lt=re,mt={id:`agent-media-${typeof lt=="string"&<.length>0?`${lt}-${ut}`:String(ut)}`,role:"assistant",content:"",contentParts:Me,createdAt:new Date().toISOString(),streaming:!1,sequence:ut,agentMetadata:{executionId:A.executionId,iteration:typeof A.iteration=="number"?A.iteration:bn}};g(mt);let Ze=b;Ze&&(Ze.streaming=!1,g(Ze)),b=null,S.current=null}}else if(ae==="execution_complete"){let T=A.kind??Nt;T==="agent"&&nt&&(nt.status=A.success?"complete":"error",nt.completedAt=Ve(A.completedAt),nt.stopReason=A.stopReason);let V=b;V&&(T==="flow"&&V.streaming!==!1?Ut(V):(V.streaming=!1,g(V)),b=null),E=null,O="",Ue=null,n({type:"status",status:"idle",terminal:!0})}else if(ae==="execution_error"){let T=typeof A.error=="string"?A.error:A.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(ae!=="ping"){if(ae==="approval_start"){let T=A.approvalId??`approval-${u()}`,V={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:T,status:"pending",agentId:nt?.agentId??"virtual",executionId:A.executionId??nt?.executionId??"",toolName:A.toolName??"",toolType:A.toolType,description:A.description??`Execute ${A.toolName??"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(V)}else if(ae==="step_await"&&A.awaitReason==="approval_required"){let T=A.approvalId??`approval-${u()}`,V={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:T,status:"pending",agentId:nt?.agentId??"virtual",executionId:A.executionId??nt?.executionId??"",toolName:A.toolName??"",toolType:A.toolType,description:A.description??`Execute ${A.toolName??"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(V)}else if(ae==="approval_complete"){let T=A.approvalId;if(T){let U={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:T,status:A.decision??"approved",agentId:nt?.agentId??"virtual",executionId:A.executionId??nt?.executionId??"",toolName:A.toolName??"",description:A.description??"",resolvedAt:Date.now()}};g(U)}}else if(ae==="artifact_start"||ae==="artifact_delta"||ae==="artifact_update"||ae==="artifact_complete"){if(ae==="artifact_start"){let T=A.artifactType,V=String(A.id),U=typeof A.title=="string"?A.title:void 0,ee=A.file,me;ee&&typeof ee=="object"&&!Array.isArray(ee)&&typeof ee.path=="string"&&typeof ee.mimeType=="string"&&(me={path:ee.path,mimeType:ee.mimeType,...typeof ee.language=="string"?{language:ee.language}:{}}),n({type:"artifact_start",id:V,artifactType:T,title:U,component:typeof A.component=="string"?A.component:void 0,...me?{file:me}:{}});let J=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?{...A.props}:void 0;if(be.set(V,{markdown:"",title:U,file:me,...J?{props:J}:{}}),!xe.has(V)){xe.add(V);let re=os(this.config.features?.artifacts,{artifactType:T,...me?{file:me}:{}}),Le=typeof A.component=="string"?A.component:void 0,Me={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Al(re,{artifactId:V,title:U,artifactType:T,status:"streaming",...me?{file:me}:{},...Le?{component:Le}:{}})};ue.set(V,Me),g(Me)}}else if(ae==="artifact_delta"){let T=String(A.id),V=typeof A.delta=="string"?A.delta:String(A.delta??"");n({type:"artifact_delta",id:T,artDelta:V});let U=be.get(T);U&&(U.markdown+=V)}else if(ae==="artifact_update"){let T=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:T,component:typeof A.component=="string"?A.component:void 0});let V=be.get(String(A.id));V&&(V.props={...V.props??{},...T})}else if(ae==="artifact_complete"){let T=String(A.id);n({type:"artifact_complete",id:T});let V=ue.get(T);if(V){V.streaming=!1;try{let U=JSON.parse(V.rawContent??"{}");if(U.props){U.props.status="complete";let ee=be.get(T);ee?.markdown&&(U.props.markdown=ee.markdown),ee?.file&&(U.props.file=ee.file),U.component==="PersonaArtifactInline"&&ee?.props&&Object.keys(ee.props).length>0&&(U.props.componentProps=ee.props)}V.rawContent=JSON.stringify(U)}catch{}be.delete(T),g(V),ue.delete(T)}}}else if(ae==="transcript_insert"){let T=A.message;if(!T||typeof T!="object")continue;let V=String(T.id??`msg-${u()}`),U=T.role,me={id:V,role:U==="user"?"user":U==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:u()};if(g(me),me.rawContent)try{let re=JSON.parse(me.rawContent)?.props?.artifactId;typeof re=="string"&&xe.add(re)}catch{}b=null,S.current=null,Ie.delete(V),Te.delete(V)}else if(ae==="error"){if(A.recoverable===!1&&A.error!=null&&A.error!==""){let T=typeof A.error=="string"?A.error:A.error?.message!=null?String(A.error.message):"Execution error";n({type:"error",error:new Error(T)});let V=b;V&&V.streaming&&(V.streaming=!1,g(V)),n({type:"status",status:"idle"})}}else if(ae==="step_error"||ae==="dispatch_error"||ae==="flow_error"){let T=null;if(A.error instanceof Error)T=A.error;else if(ae==="dispatch_error"){let V=A.message??A.error;V!=null&&V!==""&&(T=new Error(String(V)))}else{let V=A.error;typeof V=="string"&&V!==""?T=new Error(V):V!=null&&typeof V=="object"&&Reflect.has(V,"message")&&(T=new Error(String(V.message??V)))}if(T){n({type:"error",error:T});let V=b;V&&V.streaming&&(V.streaming=!1,g(V)),n({type:"status",status:"idle"})}}}}}Qt.length=0};;){let{done:G,value:ae}=await s.read();if(G)break;l+=a.decode(ae,{stream:!0});let A=l.split(`
|
|
1143
1143
|
|
|
1144
1144
|
`);l=A.pop()??"";for(let T of A){let V=T.split(`
|
|
1145
|
-
`),U="message",ee="",me=null;for(let Me of V)Me.startsWith("event:")?U=Me.replace("event:","").trim():Me.startsWith("data:")?ee+=Me.replace("data:","").trim():Me.startsWith("id:")&&(me=Me.slice(3).trim());let J=()=>{me!==null&&me!==""&&n({type:"cursor",id:me})};if(!ee){J();continue}let re;try{re=JSON.parse(ee)}catch(Me){n({type:"error",error:Me instanceof Error?Me:new Error("Failed to parse chat stream payload")});continue}let Le=U!=="message"?U:re.type??"message";if(this.onSSEEvent?.(Le,re),this.parseSSEEvent){S.current=b;let Me=await this.handleCustomSSEEvent(re,n,S,g,u,I);if(S.current&&S.current!==b&&(b=S.current),Me){J();continue}}
|
|
1145
|
+
`),U="message",ee="",me=null;for(let Me of V)Me.startsWith("event:")?U=Me.replace("event:","").trim():Me.startsWith("data:")?ee+=Me.replace("data:","").trim():Me.startsWith("id:")&&(me=Me.slice(3).trim());let J=()=>{me!==null&&me!==""&&n({type:"cursor",id:me})};if(!ee){J();continue}let re;try{re=JSON.parse(ee)}catch(Me){n({type:"error",error:Me instanceof Error?Me:new Error("Failed to parse chat stream payload")});continue}let Le=U!=="message"?U:re.type??"message";if(this.onSSEEvent?.(Le,re),this.parseSSEEvent){S.current=b;let Me=await this.handleCustomSSEEvent(re,n,S,g,u,I);if(S.current&&S.current!==b&&(b=S.current),Me){J();continue}}Qt.push({payloadType:Le,payload:re}),_t(),J()}}_t()}};ta();Xf();var zL=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function qL(t){let e=t?.text?.trim()??"";return e?Wl(zL(t),e):""}function Lw(t){let e=qL(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[nr(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
|
|
1146
1146
|
|
|
1147
|
-
`)}:{}}function
|
|
1147
|
+
`)}:{}}function pp(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function Pw(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 Jf(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 Iw(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 Jf(t,n.id)?n.id:null}return null}function Zf(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}Bl();function eg(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 Ol=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):eg(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 mp=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 UL=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Hw(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:UL()}catch{return!1}}eo();var{setLoader:SO,load:JL}=zt({fallbackImport:()=>Promise.resolve().then(()=>(Dw(),Ow))});var sg=JL;function ig(t){if(!t)return"";let e=ZL(t);return _w(e!==null?e:t)}function ZL(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 _w(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /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
|
|
1149
|
+
`),e.trim()}var zw=null;var ag=()=>zw?zw():Promise.resolve().then(()=>(Vw(),$w));eo();var{setLoader:RO,load:rP}=zt({fallbackImport:()=>Promise.resolve().then(()=>(Uw(),qw))});var jw=rP;var sP=["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 iP(t,e){return sP.some(n=>t[n]!==e[n])}var rr=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function lg(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 ag=t=>({isError:!0,content:[{type:"text",text:t}]}),eP=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,qw=t=>Zi(t)||t===as,fp=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.ttsSpokenMessageIds=new Set;this.readAloud=new pp(()=>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&&(Zi(n.name)||n.name===as&&ls(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 Hl(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&&og().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||sg().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 Lw(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Bl.isSupported()?new Bl({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 sg().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");let o=++this.voiceSetupGeneration;this.voiceSetupPromise=og().then(r=>{o===this.voiceSetupGeneration&&this.wireVoiceProvider(r.createVoiceProvider(n))}).catch(r=>{console.error("Failed to setup voice:",r)}).finally(()=>{o===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let o=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,s,a)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!a});else{let l=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!a});this.pendingVoiceUserMessageId=l.id}if(a){this.pendingVoiceUserMessageId=null;let l=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=l.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!a,voiceProcessing:!a});else{let l=this.injectMessage({role:"assistant",content:s,streaming:!a,voiceProcessing:!a});this.pendingVoiceAssistantMessageId=l.id}a&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(r=>{this.voiceLevel=Number.isFinite(r)?Math.max(0,Math.min(1,r)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:o,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(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(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let 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.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 rr("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 or("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 rr("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 rr("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new rr("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=Il(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 rr("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 rr("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 rr("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 rr("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=Il(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=Pl(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=Pl(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=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!ZL(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new Hl(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role: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"?Jd():n==="assistant"?na():`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"?Jd():r==="assistant"?na():`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 cg=t=>({isError:!0,content:[{type:"text",text:t}]}),aP=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Kw=t=>ea(t)||t===as,hp=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.ttsSpokenMessageIds=new Set;this.readAloud=new mp(()=>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&&(ea(n.name)||n.name===as&&ls(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 Rl(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&&sg().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||ag().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 Hw(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Ol.isSupported()?new Ol({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 ag().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");let o=++this.voiceSetupGeneration;this.voiceSetupPromise=sg().then(r=>{o===this.voiceSetupGeneration&&this.wireVoiceProvider(r.createVoiceProvider(n))}).catch(r=>{console.error("Failed to setup voice:",r)}).finally(()=>{o===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let o=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,s,a)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!a});else{let l=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!a});this.pendingVoiceUserMessageId=l.id}if(a){this.pendingVoiceUserMessageId=null;let l=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=l.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!a,voiceProcessing:!a});else{let l=this.injectMessage({role:"assistant",content:s,streaming:!a,voiceProcessing:!a});this.pendingVoiceAssistantMessageId=l.id}a&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(r=>{this.voiceLevel=Number.isFinite(r)?Math.max(0,Math.min(1,r)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:o,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(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(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let 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.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 rr("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 or("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 rr("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 rr("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new rr("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=Hl(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 rr("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 rr("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 rr("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 rr("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=Hl(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=Il(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=Il(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 st&&(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 st?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 st&&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=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!iP(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new Rl(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role: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"?ep():n==="assistant"?oa():`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"?ep():r==="assistant"?oa():`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(nr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(d){let p=[];a&&p.push(nr(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=Jd(),a=na();this.activeAssistantMessageId=null;let l=n?.contentParts&&ip(n.contentParts)?la:"",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=Tw({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=ig(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=Ew(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=na();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=ig(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!==as?!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===as)return{dedupeKey:m,resumeKey:g,output:XC(),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 I=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));return I||this.callbacks.onError?.(S instanceof Error?S:new Error(String(S))),this.markWebMcpToolComplete(d,ag(I?"Aborted by cancel()":eP(S)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,ag("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===as?{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,ag("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 step_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 step_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=os(this.config.features?.artifacts,e),r=Sl(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=os(this.config.features?.artifacts,n),s=Sl(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=zw().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=>ig(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=na(),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=rg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Jf(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=rg(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&&qw(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&&qw(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)})}};Ue();var To=require("lucide");eo();Jt();var dP={add:t=>pw(t)},pP=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,vp={allowedTypes:Lr,maxFileSize:10*1024*1024,maxFiles:4};function uP(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function mP(t){return t==="application/pdf"?To.FileText:t.startsWith("text/")?To.FileText:t.includes("word")?To.FileText:t.includes("excel")||t.includes("spreadsheet")?To.FileSpreadsheet:t==="application/json"?To.FileCode:To.File}var Dl=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??vp.allowedTypes,maxFileSize:e.maxFileSize??vp.maxFileSize,maxFiles:e.maxFiles??vp.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:dP}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:vp.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=uw(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:uP(),file:o,previewUrl:ap(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=pP(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=ap(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=mP(e.file.type),h=Ke(m,20,"var(--persona-muted, #6b7280)",1.5);h&&u.appendChild(h);let g=v("span");g.textContent=mw(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=q("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=q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=He("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=Ke(To.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 Gw=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),fP=(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 Yw(){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=>{fP(t.attachments,u)||(t.attachments=[...u],p())},setMentionRefs:u=>{Gw(t.mentionRefs,u)||(t.mentionRefs=[...u],p())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,p())},setActiveModeIds:u=>{Gw(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()}}}Ue();var to=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},Qw=(t,e)=>{let n=v("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Xw(t,e={}){let n=to(t,"[data-persona-composer-form]"),o=to(t,"[data-persona-composer-input]");if(!n||!o){let I=`[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(I);return typeof console<"u"&&console.warn(I),null}let r={header:to(t,"[data-persona-composer-header]"),body:to(t,"[data-persona-composer-body]"),actionsStart:to(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:to(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:to(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:to(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:to(t,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=Qw("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,I,E,O,M)=>{if(I)return I;s.add(S);let D=Qw(E,O);return M.appendChild(D),D},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,I)=>S.target===I.target&&S.type===I.type&&S.handler===I.handler,C=to(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:to(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:to(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:to(t,"[data-persona-composer-submit]")??void 0,micButton:to(t,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(S,I,E,O)=>{S.addEventListener(I,E,O),g.push({target:S,type:I,handler:E,options:O})},removeListener:(S,I,E,O)=>{S.removeEventListener(I,E,O),g=g.filter(M=>!b(M,{target:S,type:I,handler:E}))},destroy:()=>{for(let S of g)S.target.removeEventListener(S.type,S.handler,S.options);g=[]}}}Ue();Jt();us();var gP=8,hP=8,pg=10,Jw=200,Zw=300,ex=0,wp=t=>Math.max(0,t);function tx(t){t.delayMs!==void 0&&(Jw=wp(t.delayMs)),t.skipDelayMs!==void 0&&(Zw=wp(t.skipDelayMs))}var yP=()=>Date.now()<ex,bP=t=>{ex=t>0?Date.now()+t:0},Cp=new WeakMap,mg="data-persona-tooltip-suppressed",vP=t=>typeof t.closest=="function"&&t.closest(`[${mg}]`)!==null;function nx(t){Cp.get(t)?.hide()}var ox=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,CP=t=>{let e=t.getRootNode?.();return ox(e)?e:t.ownerDocument.body},ug=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),wP=[...["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 Tn(t){Cp.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=gP,viewportPadding:l=hP}=t,d=()=>e.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,h=null,g=null,b,C=!1,S=!1,I=!1,E=()=>(typeof o=="function"?o():o).trim(),O=()=>(typeof r=="function"?r():r??"").trim(),M=()=>wp(t.delayMs??Jw),D=()=>wp(t.skipDelayMs??Zw),L=()=>{b!==void 0&&(p().clearTimeout(b),b=void 0)},B=()=>{L();let ie=u!==null;g?.(),g=null,u?.remove(),u=null,m=null,h=null,ie&&bP(D())},W=()=>{if(!u)return;let ie=d(),se=p(),pe=e.getBoundingClientRect(),ue=u.getBoundingClientRect(),xe=ie.documentElement.clientWidth||se.innerWidth,be=ie.documentElement.clientHeight||se.innerHeight,F=xe-l-ue.width,Ce=pe.left+pe.width/2-ue.width/2,Ee=ug(Ce,l,F),qe=pe.top-l,ke=be-l-pe.bottom,Ie=ue.height+a,Te=qe>=Ie||qe>=ke?"top":"bottom",vt=Te==="top"?pe.top-a-ue.height:pe.bottom+a,Ye=be-l-ue.height,Et=ug(vt,l,Ye),je=pe.left+pe.width/2,lt=Math.max(pg,ue.width-pg),Vt=ug(je-Ee,pg,lt);u.dataset.placement=Te,u.style.left=`${Ee}px`,u.style.top=`${Et}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${Vt}px`)},z=()=>{if(I||!s||u||!e.isConnected||vP(e))return;let ie=E(),se=CP(e);if(!ie||!se)return;let pe=d(),ue=p();u=pe.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(ua);let xe=ue.getComputedStyle?.(e);if(xe){for(let Ie of wP){let Te=xe.getPropertyValue(Ie).trim();Te&&u.style.setProperty(Ie,Te)}xe.fontFamily&&(u.style.fontFamily=xe.fontFamily)}m=pe.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ie,u.appendChild(m);let be=O();be&&(h=pe.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=be,u.appendChild(h));let F=pe.createElement("span");F.className="persona-control-tooltip__arrow",u.appendChild(F),se.appendChild(u),W(),u.dataset.state="open";let Ce=()=>{if(!e.isConnected){B();return}m&&(m.textContent=E()),h&&(h.textContent=O()),W()};ue.addEventListener("scroll",Ce,!0),ue.addEventListener("resize",Ce);let Ee=e.getRootNode(),qe=ox(Ee)?Ee:pe.documentElement,ke=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||B()});ke?.observe(qe,{childList:!0,subtree:!0}),g=()=>{ue.removeEventListener("scroll",Ce,!0),ue.removeEventListener("resize",Ce),ke?.disconnect()}},H=ie=>{if(!(I||u)){if(L(),ie||M()<=0||yP()){z();return}b=p().setTimeout(()=>{b=void 0,z()},M())}},w=()=>{C||S?H(S):B()},k=()=>{let ie=p();(!ie.matchMedia||!ie.matchMedia("(hover: none)").matches)&&(C=!0,w())},R=()=>{C=!1,w()},_=()=>{try{S=e.matches(":focus-visible")}catch{S=!0}w()},X=()=>{S=!1,w()},j=()=>{C=!1,S=!1,B()},Q=ie=>{ie.key==="Escape"&&j()};n.addEventListener("mouseenter",k),n.addEventListener("mouseleave",R),e.addEventListener("focus",_),e.addEventListener("blur",X),e.addEventListener("keydown",Q),e.addEventListener("click",j);let Z={get isOpen(){return u!==null},show:z,hide:B,reposition:W,destroy:()=>{I||(I=!0,B(),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",R),e.removeEventListener("focus",_),e.removeEventListener("blur",X),e.removeEventListener("keydown",Q),e.removeEventListener("click",j),Cp.delete(e))}};return Cp.set(e,Z),Z}Ue();Jt();var rx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ma(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];rx(s)&&rx(r)?n[o]=ma(s,r):n[o]=r}return n}var Pr="min(440px, calc(100vw - 24px))",ix="440px",fg="How can I help...",xP={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:Pr,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)"},Tt={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:xP,copy:{inputPlaceholder:fg,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 sx(t,e){if(!(!t&&!e))return t?e?ma(t,e):t:e}function xp(t){return t?{...Tt,...t,theme:sx(Tt.theme,t.theme),darkTheme:sx(Tt.darkTheme,t.darkTheme),launcher:{...Tt.launcher,...t.launcher,dock:{...Tt.launcher?.dock,...t.launcher?.dock},clearChat:{...Tt.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...Tt.tooltip,...t.tooltip},copy:{...Tt.copy,...t.copy},sendButton:{...Tt.sendButton,...t.sendButton},statusIndicator:{...Tt.statusIndicator,...t.statusIndicator},voiceRecognition:{...Tt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=Tt.features?.artifacts,n=t.features?.artifacts,o=Tt.features?.scrollToBottom,r=t.features?.scrollToBottom,s=Tt.features?.scrollBehavior,a=t.features?.scrollBehavior,l=Tt.features?.streamAnimation,d=t.features?.streamAnimation,p=Tt.features?.askUserQuestion,u=t.features?.askUserQuestion,m=Tt.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},I=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},E=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...Tt.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...C!==void 0?{scrollBehavior:C}:{},...g!==void 0?{artifacts:g}:{},...S!==void 0?{streamAnimation:S}:{},...I!==void 0?{askUserQuestion:I}:{},...E!==void 0?{history:E}:{}}})(),suggestionChips:t.suggestionChips??Tt.suggestionChips,suggestionChipsConfig:{...Tt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...Tt.layout,...t.layout,header:{...Tt.layout?.header,...t.layout?.header},messages:{...Tt.layout?.messages,...t.layout?.messages,avatar:{...Tt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...Tt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...Tt.layout?.slots,...t.layout?.slots}},markdown:{...Tt.markdown,...t.markdown,options:{...Tt.markdown?.options,...t.markdown?.options}},messageActions:{...Tt.messageActions,...t.messageActions}}:Tt}function gg(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 Sp(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function ax(t,e){t.style.maxHeight=`${e*gg(t)}px`,t.style.overflowY="auto"}function Fl(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 lx(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function cx(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||!lx(e)}function SP(t){return(t.submitKey??"enter")!=="enter"||lx(t)?"enter":"send"}function Ap(t,e){t.setAttribute("enterkeyhint",SP(e))}function Mp(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 hg(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 po="persona-composer-control",_o="persona-composer-control--glyph",bg=40,$n=24,Tp=(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)}},Ep=(t,e)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??fg,n.dir="auto",Ap(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:Fl(n)}),Mp(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=Sp(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*gg(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}},MP="[data-persona-glyph-stack]",vg=(t,e,n="send")=>{let o=q("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},kp=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??"")||bg,g=e.backgroundColor,b=e.textColor,C=v("div","persona-send-button-wrapper"),S=q("button",{className:Bt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${po}`:"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}}),I=null,E=null,O=null;if(n){let L=parseFloat(e.iconSize??"")||Math.round(h*.5),B=e.iconStrokeWidth??2,W=b?.trim()||"currentColor";r&&(I=He(r,L,W,B)),E=He(s,L,W,B),I&&E?(O=vg(I,E),S.appendChild(O)):I?S.appendChild(I):(S.textContent=o,E=null)}else S.textContent=d;S.setAttribute("aria-label",a),C.appendChild(S),Tn({anchor:S,trigger:C,text:()=>S.getAttribute("aria-label")??"",enabled:u});let M="send";return{button:S,wrapper:C,setMode:L=>{if(L===M)return;M=L;let B=L==="stop"?l:a;S.setAttribute("aria-label",B),S.setAttribute("data-persona-send-mode",L),n?(S.querySelector(MP)??O)?.setAttribute("data-mode",L):S.textContent=L==="stop"?p:d},glyphStack:O}},fa=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=q("button",{className:Bt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",po,!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=He(l,p,m||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",h.appendChild(g);let S=e.tooltipText??"Start voice recognition",I=e.showTooltip??!1;return Tn({anchor:g,trigger:h,text:()=>g.getAttribute("aria-label")??S,enabled:I}),{button:g,wrapper:h}},Lp=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??Lr).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=q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${po} ${_o}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=He(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 Tn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},Pp=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},Ip=()=>q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});ga();Ue();Jt();var EP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',kP=["--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"],Cg="data-persona-menu-focus",LP=new Set(["ArrowDown","ArrowUp","Home","End"]);function mx(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(EP)??t}var PP=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function fx(t){let e=t.label,n=!1,o=v("div","persona-send-button-wrapper"),r=q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${po} ${_o}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let _=t.getButtonSize?.()??"";r.style.width=_,r.style.height=_,r.style.minWidth=_,r.style.minHeight=_,r.style.lineHeight="1",r.replaceChildren();let X=He("plus",$n,"currentColor",1.5);X?r.appendChild(X):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 X=s.getRootNode().activeElement;return X instanceof HTMLElement?X:null},h=()=>{let _=m();for(let X of d){let j=!!_&&mx(X)===_;X.toggleAttribute(Cg,j&&u)}},g=()=>d.filter(_=>_.isConnected||s.contains(_)).map(mx).filter(_=>!PP(_)),b=(_,X)=>{_.forEach((j,Q)=>{j.setAttribute("tabindex",Q===X?"0":"-1")})},C=_=>{let X=g();if(X.length===0)return;let j=(_%X.length+X.length)%X.length;p=j,b(X,j),X[j].focus(),h()},S=()=>o.ownerDocument??document,I=null,E=null,O=null,M=()=>{I&&(S().removeEventListener("focusin",I,!0),I=null)},D=()=>{E&&(s.removeEventListener("focusin",E),E=null),O&&(s.removeEventListener("pointerdown",O,!0),O=null)},L=null,B=()=>(L||(L=ms({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),M()}})),L),W=()=>L?.isOpen===!0,z=(_=!1)=>{if(W()){L?.close(),r.setAttribute("aria-expanded","false"),M(),D(),p=-1,u=!1;for(let X of d)X.removeAttribute(Cg);_&&r.focus()}},H=(_=0,X=!1)=>{if(n||W())return;u=X,Tp(r,s,kP),B().open(),r.setAttribute("aria-expanded","true");let j=g();b(j,-1),C(_<0?j.length-1:_),I=Q=>{let Z=typeof Q.composedPath=="function"?Q.composedPath():[];Z.includes(s)||Z.includes(o)||z()},S().addEventListener("focusin",I,!0),E=()=>h(),s.addEventListener("focusin",E),O=()=>{u=!1},s.addEventListener("pointerdown",O,!0)},w=_=>{_.preventDefault(),_.stopPropagation(),W()?z(!0):H(0)},k=_=>{if(_.key==="ArrowDown"||_.key==="Enter"||_.key===" "){_.preventDefault(),u=!0,W()?C(0):H(0,!0);return}_.key==="ArrowUp"&&(_.preventDefault(),u=!0,W()?C(-1):H(-1,!0))},R=_=>{switch(LP.has(_.key)&&(u=!0),_.key){case"ArrowDown":_.preventDefault(),C(p+1);return;case"ArrowUp":_.preventDefault(),C(p-1);return;case"Home":_.preventDefault(),C(0);return;case"End":_.preventDefault(),C(g().length-1);return;case"Escape":_.preventDefault(),_.stopPropagation(),z(!0);return;case"Tab":z(!0);return;default:}};return r.addEventListener("click",w),r.addEventListener("keydown",k),s.addEventListener("keydown",R),{trigger:o,triggerButton:r,panel:s,setItems:_=>{for(let j of d)_.includes(j)||j.removeAttribute(Cg);if(d=[..._],!W())return;let X=g();b(X,Math.min(p,X.length-1)),h()},isOpen:W,open:()=>H(0),close:z,setLabel:_=>{_!==e&&(e=_,l())},applyButtonSize:a,destroy:()=>{n=!0,M(),D(),r.removeEventListener("click",w),r.removeEventListener("keydown",k),s.removeEventListener("keydown",R),L?.destroy(),L=null,o.remove(),s.remove(),d=[]}}}var sr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},gx="data-persona-composer-action",wg="data-persona-composer-disable-when-streaming",IP="core:overflow",HP=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function RP(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 xg(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 hx=(t,e)=>{!t||typeof console>"u"||console.warn(e)},WP=(t,e)=>e.includes(":")?e:`${t}:${e}`;function BP(t){let{debug:e}=t,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){hx(e,`[Persona] composer action "${l.id}" is already contributed by ${yx(d)}; the ${yx(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?WP(p,l.id):l.id,m=l.order??sr.custom;l.placement==="end"&&m>=sr.send&&(hx(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${sr.send-1}.`),m=sr.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 yx=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",bx=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,OP=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function DP(t,e){if(!t||t==="always")return!0;let n=OP(e);return t==="when-text"?n:!n}var fs=t=>t.kind==="custom",Sg=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,_P=t=>{let e=Sg(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},NP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function FP(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(NP)||o.childNodes.forEach(n)};return n(t),e.trim()}var $P=t=>FP(t).length===0;function vx(t){let e=new Map,n=[],o=!1,r=()=>t.getButtonSize?.(),s=(w,k)=>{let R=w.button;if(!R)return;R.setAttribute("role","menuitem"),R.setAttribute("tabindex","-1"),R.className="persona-composer-overflow-menu__item";for(let j of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])R.style[j]="";R.style.lineHeight="1",k.tooltipText?R.setAttribute("title",k.tooltipText):R.removeAttribute("title"),R.replaceChildren();let _=v("span","persona-composer-overflow-menu__icon");if(k.iconName){let j=He(k.iconName,16,"currentColor",1.5);j&&_.appendChild(j)}let X=v("span","persona-composer-overflow-menu__label");X.textContent=k.shortLabel??k.label,R.append(_,X)},a=(w,k)=>{let R=w.button;if(!R)return;if(R.setAttribute("aria-label",k.label),k.pressed===void 0?R.removeAttribute("aria-pressed"):R.setAttribute("aria-pressed",k.pressed?"true":"false"),R.toggleAttribute(wg,k.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,s(w,k);return}R.removeAttribute("role"),R.removeAttribute("tabindex"),R.removeAttribute("title");let _=r(),X=!!k.shortLabel;if(R.className=Bt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",po,_o,X&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),R.style.width=_&&!X?_:"",R.style.height=_??"",R.style.minWidth=_&&!X?_:"",R.style.minHeight=_??"",R.style.fontSize=X?"":"18px",R.style.lineHeight="1",R.style.color=k.iconColor??"",R.style.backgroundColor=k.backgroundColor??"",R.replaceChildren(),k.iconName){let j=He(k.iconName,$n,"currentColor",1.5);j&&R.appendChild(j)}if(X){let j=v("span","persona-composer-action-button__label");j.textContent=k.shortLabel,R.appendChild(j)}else R.firstChild||(R.textContent=k.label);w.tooltip?.destroy(),w.tooltip=Tn({anchor:R,trigger:w.element,text:()=>k.tooltipText??k.label,enabled:!!k.tooltipText})},l=(w,k)=>{let R=w.action,_=q("button",{attrs:{type:"button"}}),X=_;if(k==="bar"){let Z=v("div","persona-send-button-wrapper");Z.appendChild(_),X=Z}X.setAttribute(gx,w.id);let j={resolved:w,element:X,button:_,owned:!0,managed:!0,busy:!1,visible:!0,mode:k},Q=Z=>{if(Z.preventDefault(),Z.stopPropagation(),j.busy||_.disabled)return;let ie=j.resolved.action;j.mode==="menu"&&g?.close(!0);let se;try{se=ie.onSelect(t.actionContext,Z)}catch(pe){t.reportError(pe,{actionId:j.resolved.id});return}!se||typeof se.then!="function"||(j.busy=!0,_.setAttribute("aria-busy","true"),se.catch(pe=>{t.reportError(pe,{actionId:j.resolved.id})}).finally(()=>{j.busy=!1,_.removeAttribute("aria-busy")}))};return _.addEventListener("click",Q),j.detach=()=>_.removeEventListener("click",Q),a(j,R),j},d=w=>{let k=w.action,R;try{R=k.render({...t.actionContext,id:w.id,action:k})}catch(_){return t.reportError(_,{actionId:w.id}),null}return R?.element?(R.element.setAttribute(gx,w.id),R.element.toggleAttribute(wg,k.disableWhenStreaming===!0),{resolved:w,element:R.element,owned:!0,managed:!0,destroy:R.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,k)=>{if(w.builtIn){let _=w.builtIn.element;return _?{resolved:w,element:_,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let R=w.action;return R?fs(R)?d(w):l(w,k):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(k){t.reportError(k,{actionId:w.resolved.id})}w.element.remove()}},m=(w,k)=>{for(let R=0;R<k.length;R++){let _=k[R];if(!_.managed)continue;let X=null;for(let j=R+1;j<k.length;j++){let Q=k[j];if(!Q.managed&&Q.element.parentElement===w){X=Q.element;break}}X?(_.element.parentElement!==w||_.element.nextSibling!==X)&&w.insertBefore(_.element,X):w.lastChild!==_.element&&w.appendChild(_.element)}},h=(w,k)=>{if(w.button){w.button.disabled=k;return}if(!w.owned)return;let R=w.element;R.toggleAttribute("data-disabled",k),R.setAttribute("aria-disabled",k?"true":"false");let _=R instanceof HTMLButtonElement||R instanceof HTMLSelectElement||R instanceof HTMLInputElement||R instanceof HTMLTextAreaElement?R:R.querySelector("button, select, input, textarea");_&&(_.disabled=k)},g=null,b=null,C=null,S=0,I=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},E=()=>(g?g.setLabel(t.getOverflowLabel?.()??"More actions"):g=fx({label:t.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),O=w=>{b!==w&&(C?.disconnect(),b=w,S=xg(w),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(k=>{let _=k[k.length-1]?.contentRect?.width??xg(w);_!==S&&(S=_,z())}),C.observe(w)))},M=(w,k)=>{let R=RP(w.collapseAutoActionsBelow,k);if(R===null)return!1;let _=S||xg(k);return _>0&&_<R},D=(w,k,R)=>{if(!k)return"bar";if(w.resolved.builtIn){let X=HP(w.resolved.id);return X&&k.includeBuiltIns?.includes(X)?"menu":"bar"}let _=w.resolved.presentation;return _==="overflow"||_==="auto"&&R?"menu":"bar"},L=w=>{let k=w.menuSlot;if(!k)return;if(!$P(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let R=_P(w.element);if(!R){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=v("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==R&&(w.menuLabel.textContent=R),w.menuLabel.parentElement!==k&&k.appendChild(w.menuLabel)},B=(w,k)=>{if(w.mode===k)return w;let R=w.resolved.action;if(R&&!fs(R)){u(w),e.delete(w.resolved.id);let _=l(w.resolved,k);return e.set(w.resolved.id,_),_}if(k==="menu"){let _=q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[mg]:""}});_.appendChild(w.element),nx(Sg(w.element)),w.menuSlot=_;let X=j=>{let Q=Sg(w.element);if(Q.disabled)return;let Z=j.target===Q||Q.contains(j.target);g?.close(!0),Z||Q.click()};_.addEventListener("click",X,!0),w.detachMenuSlot=()=>_.removeEventListener("click",X,!0),w.managed=!0,L(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=k,w},W=(w,k)=>{let R=k.map(_=>_.menuSlot??_.element);for(R.forEach((_,X)=>{let j=w.children[X];j!==_&&(j?w.insertBefore(_,j):w.appendChild(_))});w.children.length>R.length;)w.lastElementChild?.remove()},z=()=>{if(o)return;let w=t.getBindings();if(!w)return;let k=t.getState(),R=k.phase==="streaming",_=I();_&&O(w.footer);let X=_?M(_,w.footer):!1,j={start:[],end:[]},Q=[];for(let Z of n){let ie=e.get(Z.id);if(!ie)continue;let se=Z.action,pe=se?bx(se.visible,k,!0)&&DP(se.visibility,k):!0;if(ie.visible!==pe&&(ie.visible=pe,!pe&&ie.managed&&(ie.menuSlot??ie.element).remove()),!!pe){if(ie=B(ie,D(ie,_,X)),se){let ue=bx(se.disabled,k,!1)||se.disableWhenStreaming===!0&&R;h(ie,ue),!fs(se)&&se.pressed!==void 0&&ie.button?.setAttribute("aria-pressed",se.pressed?"true":"false")}ie.mode==="menu"?(L(ie),Q.push(ie)):j[Z.placement].push(ie)}}if(Q.length>0){let Z=E();W(Z.panel,Q),Z.setItems(Q.map(ue=>ue.menuSlot??ue.element)),Z.applyButtonSize();let ie=Number.isFinite(_?.order)?_?.order:sr.overflow,se=j.start.findIndex(ue=>ue.resolved.order>ie),pe={resolved:{id:IP,placement:"start",presentation:"bar",order:ie,sequence:-1,source:"core"},element:Z.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};j.start.splice(se<0?j.start.length:se,0,pe)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));m(w.actionsStart,j.start),m(w.actionsEnd,j.end)};return{resolve:()=>{if(o)return;let w=BP(t.collect()),k=new Set(w.map(R=>R.id));for(let[R,_]of e)k.has(R)||(u(_),e.delete(R));for(let R of w){let _=e.get(R.id);if(!_){let Z=p(R,"bar");Z&&e.set(R.id,Z);continue}let X=_.resolved.action,j=R.action;if(!!X!=!!j||X&&j&&fs(X)!==fs(j)||X&&j&&fs(X)&&fs(j)&&X.render!==j.render){u(_),e.delete(R.id);let Z=p(R,_.mode);Z&&e.set(R.id,Z);continue}_.resolved=R,R.builtIn?(_.managed=R.builtIn.managed===!0||_.mode==="menu",R.builtIn.element&&_.mode==="bar"&&(_.element=R.builtIn.element)):j&&!fs(j)?a(_,j):j&&_.element.toggleAttribute(wg,j.disableWhenStreaming===!0)}n=w,z()},sync:z,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=[]}}}}ga();Ue();Jt();var VP="core:model",zP=700,Cx=16,qP=["--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"],wx=()=>{let t=q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function xx(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=q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=t.getModels(),S=C.map(I=>`${I.id}:${I.label}`).join("|");S!==p&&(p=S,d.replaceChildren(...C.map(I=>{let E=q("option",{attrs:{value:I.id}});return E.textContent=I.label,E}))),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}=wx();return g.append(d,b),{element:g,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",h)}}},a=()=>{let d=q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=v("span","persona-composer-model-picker-label"),u=v("span","persona-composer-model-picker-suffix");d.append(p,u);let m=q("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=(k=!1)=>{C()&&(b?.close(),d.setAttribute("aria-expanded","false"),k&&d.focus())},I=k=>{let R=[...h.values()];if(R.length===0)return;let _=(k%R.length+R.length)%R.length;R[_].focus()},E=k=>{if(C())return;b||(b=ms({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Tp(d,m,qP),b.open(),d.setAttribute("aria-expanded","true");let _=[...h.keys()].indexOf(r(t.getModels())?.id??"");I(k??(_>=0?_:0))},O=k=>{S(!0),t.onSelect(k)},M=k=>{k.preventDefault(),k.stopPropagation();let R=k.currentTarget.getAttribute("data-persona-model-option");R&&O(R)},D=k=>{let R=q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":k.id}});if(k.icon){let Z=He(k.icon,Cx,"currentColor",1.5);if(Z){let ie=v("span","persona-composer-model-option-icon");ie.appendChild(Z),R.appendChild(ie)}}let _=v("span","persona-composer-model-option-body"),X=v("span","persona-composer-model-option-label");if(X.textContent=k.label,_.appendChild(X),k.description){let Z=v("span","persona-composer-model-option-description");Z.textContent=k.description,_.appendChild(Z)}R.appendChild(_);let j=v("span","persona-composer-model-option-check");j.setAttribute("aria-hidden","true");let Q=He("check",Cx,"currentColor",2);return Q&&j.appendChild(Q),R.appendChild(j),R.addEventListener("click",M),R},L=()=>{let k=t.getModels(),R=k.map(j=>`${j.id}:${j.label}:${j.icon??""}:${j.description??""}`).join("|");if(R!==g){g=R;for(let j of h.values())j.removeEventListener("click",M);h.clear(),m.replaceChildren(...k.map(j=>{let Q=D(j);return h.set(j.id,Q),Q}))}let _=r(k);for(let[j,Q]of h)Q.setAttribute("aria-selected",String(j===_?.id));p.textContent=_?.label??"";let X=t.getSuffix?.()??"";u.textContent=X,d.setAttribute("aria-label",[e,[_?.label,X].filter(Boolean).join(" ")].filter(Boolean).join(": "))};L(),o=L;let B=k=>{k.preventDefault(),k.stopPropagation(),C()?S(!0):E()},W=k=>{if(k.key==="ArrowDown"){k.preventDefault(),C()?I(0):E(0);return}k.key==="ArrowUp"&&(k.preventDefault(),C()?I(-1):E(-1))},z=k=>{let R=[...h.values()],_=R.indexOf(k.target?.closest?.(".persona-composer-model-option"));switch(k.key){case"ArrowDown":k.preventDefault(),I(_+1);return;case"ArrowUp":k.preventDefault(),I(_-1);return;case"Home":k.preventDefault(),I(0);return;case"End":k.preventDefault(),I(R.length-1);return;case"Escape":k.preventDefault(),k.stopPropagation(),S(!0);return;case"Tab":S(!0);return;default:}};d.addEventListener("click",B),d.addEventListener("keydown",W),m.addEventListener("keydown",z);let{wrapper:H,chevron:w}=wx();return H.append(d,w),{element:H,destroy:()=>{o===L&&(o=null),d.removeEventListener("click",B),d.removeEventListener("keydown",W),m.removeEventListener("keydown",z);for(let k of h.values())k.removeEventListener("click",M);h.clear(),b?.destroy(),b=null,m.remove()}}};return{action:{id:VP,kind:"custom",placement:"end",order:zP,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}Ue();Jt();Bp();var UP=":scope > [data-persona-composer-mode]";function Sx(t){let e=t.row,n="",o=!1,r=new Set(t.initialIds??[]),s=p=>{let u=q("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=He(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=q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),g=He("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(UP)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),ha(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(E=>E.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}ha(e)},destroy:()=>{o=!0,d(),ha(e)}}}Ue();Jt();var Ax=t=>`core:mode:${t}`;var Tg=t=>Math.min(300+t,499),Mx=t=>`core:mode-group:${t}`;function Op(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function jP(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Tx(t,e){return t?.length?t.filter(n=>!Op(n.groupId,e)&&!jP(n.groupId,e)):[]}var KP=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Ex(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(KP(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 Dp(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function kx(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Lx(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var GP=16;function Px(t){let e=null;return{action:{id:Mx(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=q("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=q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=He(p.iconName,GP,"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?.()}}Bp();Ue();Jt();function Ix(t){let e=q("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=q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=cp(s.text),l.appendChild(d);let p=q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=He("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()}}}Ue();Jt();function Hx(t){let e=q("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=q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=He(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=cp(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=q("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()}}}Ue();function Rx(t){let e=q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=q("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=q("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 Wx(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 Bx(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 Ox(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 Dx(t){return t.wrapped||t.text.includes(`
|
|
1156
|
-
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function
|
|
1155
|
+
`),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(nr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(d){let p=[];a&&p.push(nr(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=ep(),a=oa();this.activeAssistantMessageId=null;let l=n?.contentParts&&lp(n.contentParts)?ca:"",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=Lw({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=lg(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=Pw(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=oa();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=lg(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!==as?!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===as)return{dedupeKey:m,resumeKey:g,output:ZC(),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 I=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));return I||this.callbacks.onError?.(S instanceof Error?S:new Error(String(S))),this.markWebMcpToolComplete(d,cg(I?"Aborted by cancel()":aP(S)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,cg("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===as?{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,cg("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 step_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 step_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=os(this.config.features?.artifacts,e),r=Al(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=os(this.config.features?.artifacts,n),s=Al(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=jw().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=>lg(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=oa(),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=ig(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return eg(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=ig(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&&Kw(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&&Kw(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)})}};qe();var Eo=require("lucide");to();en();var yP={add:t=>fw(t)},bP=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,wp={allowedTypes:Pr,maxFileSize:10*1024*1024,maxFiles:4};function vP(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function CP(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??wp.allowedTypes,maxFileSize:e.maxFileSize??wp.maxFileSize,maxFiles:e.maxFiles??wp.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:yP}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:wp.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=gw(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:vP(),file:o,previewUrl:cp(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=bP(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=cp(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=CP(e.file.type),h=Ke(m,20,"var(--persona-muted, #6b7280)",1.5);h&&u.appendChild(h);let g=v("span");g.textContent=hw(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=q("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=q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=He("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=Ke(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 Xw=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),wP=(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 Jw(){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=>{wP(t.attachments,u)||(t.attachments=[...u],p())},setMentionRefs:u=>{Xw(t.mentionRefs,u)||(t.mentionRefs=[...u],p())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,p())},setActiveModeIds:u=>{Xw(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()}}}qe();var no=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},Zw=(t,e)=>{let n=v("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function ex(t,e={}){let n=no(t,"[data-persona-composer-form]"),o=no(t,"[data-persona-composer-input]");if(!n||!o){let I=`[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(I);return typeof console<"u"&&console.warn(I),null}let r={header:no(t,"[data-persona-composer-header]"),body:no(t,"[data-persona-composer-body]"),actionsStart:no(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:no(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:no(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:no(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:no(t,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=Zw("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,I,E,O,M)=>{if(I)return I;s.add(S);let D=Zw(E,O);return M.appendChild(D),D},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,I)=>S.target===I.target&&S.type===I.type&&S.handler===I.handler,C=no(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:no(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:no(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:no(t,"[data-persona-composer-submit]")??void 0,micButton:no(t,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(S,I,E,O)=>{S.addEventListener(I,E,O),g.push({target:S,type:I,handler:E,options:O})},removeListener:(S,I,E,O)=>{S.removeEventListener(I,E,O),g=g.filter(M=>!b(M,{target:S,type:I,handler:E}))},destroy:()=>{for(let S of g)S.target.removeEventListener(S.type,S.handler,S.options);g=[]}}}qe();en();us();var xP=8,SP=8,mg=10,tx=200,nx=300,ox=0,Sp=t=>Math.max(0,t);function rx(t){t.delayMs!==void 0&&(tx=Sp(t.delayMs)),t.skipDelayMs!==void 0&&(nx=Sp(t.skipDelayMs))}var AP=()=>Date.now()<ox,MP=t=>{ox=t>0?Date.now()+t:0},xp=new WeakMap,gg="data-persona-tooltip-suppressed",TP=t=>typeof t.closest=="function"&&t.closest(`[${gg}]`)!==null;function sx(t){xp.get(t)?.hide()}var ix=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,EP=t=>{let e=t.getRootNode?.();return ix(e)?e:t.ownerDocument.body},fg=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),kP=[...["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 En(t){xp.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=xP,viewportPadding:l=SP}=t,d=()=>e.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,h=null,g=null,b,C=!1,S=!1,I=!1,E=()=>(typeof o=="function"?o():o).trim(),O=()=>(typeof r=="function"?r():r??"").trim(),M=()=>Sp(t.delayMs??tx),D=()=>Sp(t.skipDelayMs??nx),L=()=>{b!==void 0&&(p().clearTimeout(b),b=void 0)},B=()=>{L();let ie=u!==null;g?.(),g=null,u?.remove(),u=null,m=null,h=null,ie&&MP(D())},W=()=>{if(!u)return;let ie=d(),se=p(),pe=e.getBoundingClientRect(),ue=u.getBoundingClientRect(),xe=ie.documentElement.clientWidth||se.innerWidth,be=ie.documentElement.clientHeight||se.innerHeight,F=xe-l-ue.width,Ce=pe.left+pe.width/2-ue.width/2,Ee=fg(Ce,l,F),Ve=pe.top-l,ke=be-l-pe.bottom,Ie=ue.height+a,Te=Ve>=Ie||Ve>=ke?"top":"bottom",bt=Te==="top"?pe.top-a-ue.height:pe.bottom+a,Ye=be-l-ue.height,Et=fg(bt,l,Ye),Ue=pe.left+pe.width/2,at=Math.max(mg,ue.width-mg),Ut=fg(Ue-Ee,mg,at);u.dataset.placement=Te,u.style.left=`${Ee}px`,u.style.top=`${Et}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${Ut}px`)},z=()=>{if(I||!s||u||!e.isConnected||TP(e))return;let ie=E(),se=EP(e);if(!ie||!se)return;let pe=d(),ue=p();u=pe.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(ma);let xe=ue.getComputedStyle?.(e);if(xe){for(let Ie of kP){let Te=xe.getPropertyValue(Ie).trim();Te&&u.style.setProperty(Ie,Te)}xe.fontFamily&&(u.style.fontFamily=xe.fontFamily)}m=pe.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ie,u.appendChild(m);let be=O();be&&(h=pe.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=be,u.appendChild(h));let F=pe.createElement("span");F.className="persona-control-tooltip__arrow",u.appendChild(F),se.appendChild(u),W(),u.dataset.state="open";let Ce=()=>{if(!e.isConnected){B();return}m&&(m.textContent=E()),h&&(h.textContent=O()),W()};ue.addEventListener("scroll",Ce,!0),ue.addEventListener("resize",Ce);let Ee=e.getRootNode(),Ve=ix(Ee)?Ee:pe.documentElement,ke=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||B()});ke?.observe(Ve,{childList:!0,subtree:!0}),g=()=>{ue.removeEventListener("scroll",Ce,!0),ue.removeEventListener("resize",Ce),ke?.disconnect()}},H=ie=>{if(!(I||u)){if(L(),ie||M()<=0||AP()){z();return}b=p().setTimeout(()=>{b=void 0,z()},M())}},w=()=>{C||S?H(S):B()},k=()=>{let ie=p();(!ie.matchMedia||!ie.matchMedia("(hover: none)").matches)&&(C=!0,w())},R=()=>{C=!1,w()},_=()=>{try{S=e.matches(":focus-visible")}catch{S=!0}w()},X=()=>{S=!1,w()},j=()=>{C=!1,S=!1,B()},Q=ie=>{ie.key==="Escape"&&j()};n.addEventListener("mouseenter",k),n.addEventListener("mouseleave",R),e.addEventListener("focus",_),e.addEventListener("blur",X),e.addEventListener("keydown",Q),e.addEventListener("click",j);let Z={get isOpen(){return u!==null},show:z,hide:B,reposition:W,destroy:()=>{I||(I=!0,B(),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",R),e.removeEventListener("focus",_),e.removeEventListener("blur",X),e.removeEventListener("keydown",Q),e.removeEventListener("click",j),xp.delete(e))}};return xp.set(e,Z),Z}qe();en();var ax=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function fa(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];ax(s)&&ax(r)?n[o]=fa(s,r):n[o]=r}return n}var Ir="min(440px, calc(100vw - 24px))",cx="440px",hg="How can I help...",LP={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:Ir,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)"},Tt={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:LP,copy:{inputPlaceholder:hg,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 lx(t,e){if(!(!t&&!e))return t?e?fa(t,e):t:e}function Ap(t){return t?{...Tt,...t,theme:lx(Tt.theme,t.theme),darkTheme:lx(Tt.darkTheme,t.darkTheme),launcher:{...Tt.launcher,...t.launcher,dock:{...Tt.launcher?.dock,...t.launcher?.dock},clearChat:{...Tt.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...Tt.tooltip,...t.tooltip},copy:{...Tt.copy,...t.copy},sendButton:{...Tt.sendButton,...t.sendButton},statusIndicator:{...Tt.statusIndicator,...t.statusIndicator},voiceRecognition:{...Tt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=Tt.features?.artifacts,n=t.features?.artifacts,o=Tt.features?.scrollToBottom,r=t.features?.scrollToBottom,s=Tt.features?.scrollBehavior,a=t.features?.scrollBehavior,l=Tt.features?.streamAnimation,d=t.features?.streamAnimation,p=Tt.features?.askUserQuestion,u=t.features?.askUserQuestion,m=Tt.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},I=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},E=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...Tt.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...C!==void 0?{scrollBehavior:C}:{},...g!==void 0?{artifacts:g}:{},...S!==void 0?{streamAnimation:S}:{},...I!==void 0?{askUserQuestion:I}:{},...E!==void 0?{history:E}:{}}})(),suggestionChips:t.suggestionChips??Tt.suggestionChips,suggestionChipsConfig:{...Tt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...Tt.layout,...t.layout,header:{...Tt.layout?.header,...t.layout?.header},messages:{...Tt.layout?.messages,...t.layout?.messages,avatar:{...Tt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...Tt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...Tt.layout?.slots,...t.layout?.slots}},markdown:{...Tt.markdown,...t.markdown,options:{...Tt.markdown?.options,...t.markdown?.options}},messageActions:{...Tt.messageActions,...t.messageActions}}:Tt}function yg(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 Mp(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function dx(t,e){t.style.maxHeight=`${e*yg(t)}px`,t.style.overflowY="auto"}function $l(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 px(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function ux(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||!px(e)}function PP(t){return(t.submitKey??"enter")!=="enter"||px(t)?"enter":"send"}function Tp(t,e){t.setAttribute("enterkeyhint",PP(e))}function Ep(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 bg(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 uo="persona-composer-control",No="persona-composer-control--glyph",Cg=40,Vn=24,kp=(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)}},Lp=(t,e)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??hg,n.dir="auto",Tp(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:$l(n)}),Ep(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=Mp(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*yg(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}},HP="[data-persona-glyph-stack]",wg=(t,e,n="send")=>{let o=q("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},Pp=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??"")||Cg,g=e.backgroundColor,b=e.textColor,C=v("div","persona-send-button-wrapper"),S=q("button",{className:Dt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${uo}`:"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}}),I=null,E=null,O=null;if(n){let L=parseFloat(e.iconSize??"")||Math.round(h*.5),B=e.iconStrokeWidth??2,W=b?.trim()||"currentColor";r&&(I=He(r,L,W,B)),E=He(s,L,W,B),I&&E?(O=wg(I,E),S.appendChild(O)):I?S.appendChild(I):(S.textContent=o,E=null)}else S.textContent=d;S.setAttribute("aria-label",a),C.appendChild(S),En({anchor:S,trigger:C,text:()=>S.getAttribute("aria-label")??"",enabled:u});let M="send";return{button:S,wrapper:C,setMode:L=>{if(L===M)return;M=L;let B=L==="stop"?l:a;S.setAttribute("aria-label",B),S.setAttribute("data-persona-send-mode",L),n?(S.querySelector(HP)??O)?.setAttribute("data-mode",L):S.textContent=L==="stop"?p:d},glyphStack:O}},ga=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??"")||Vn,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,h=v("div","persona-send-button-wrapper"),g=q("button",{className:Dt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",uo,!d&&No),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=He(l,p,m||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",h.appendChild(g);let S=e.tooltipText??"Start voice recognition",I=e.showTooltip??!1;return En({anchor:g,trigger:h,text:()=>g.getAttribute("aria-label")??S,enabled:I}),{button:g,wrapper:h}},Ip=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??Pr).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=q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${uo} ${No}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=He(r,Vn,"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 En({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},Hp=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},Rp=()=>q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});ha();qe();en();var WP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',BP=["--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"],xg="data-persona-menu-focus",OP=new Set(["ArrowDown","ArrowUp","Home","End"]);function hx(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(WP)??t}var DP=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function yx(t){let e=t.label,n=!1,o=v("div","persona-send-button-wrapper"),r=q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${uo} ${No}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let _=t.getButtonSize?.()??"";r.style.width=_,r.style.height=_,r.style.minWidth=_,r.style.minHeight=_,r.style.lineHeight="1",r.replaceChildren();let X=He("plus",Vn,"currentColor",1.5);X?r.appendChild(X):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 X=s.getRootNode().activeElement;return X instanceof HTMLElement?X:null},h=()=>{let _=m();for(let X of d){let j=!!_&&hx(X)===_;X.toggleAttribute(xg,j&&u)}},g=()=>d.filter(_=>_.isConnected||s.contains(_)).map(hx).filter(_=>!DP(_)),b=(_,X)=>{_.forEach((j,Q)=>{j.setAttribute("tabindex",Q===X?"0":"-1")})},C=_=>{let X=g();if(X.length===0)return;let j=(_%X.length+X.length)%X.length;p=j,b(X,j),X[j].focus(),h()},S=()=>o.ownerDocument??document,I=null,E=null,O=null,M=()=>{I&&(S().removeEventListener("focusin",I,!0),I=null)},D=()=>{E&&(s.removeEventListener("focusin",E),E=null),O&&(s.removeEventListener("pointerdown",O,!0),O=null)},L=null,B=()=>(L||(L=ms({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),M()}})),L),W=()=>L?.isOpen===!0,z=(_=!1)=>{if(W()){L?.close(),r.setAttribute("aria-expanded","false"),M(),D(),p=-1,u=!1;for(let X of d)X.removeAttribute(xg);_&&r.focus()}},H=(_=0,X=!1)=>{if(n||W())return;u=X,kp(r,s,BP),B().open(),r.setAttribute("aria-expanded","true");let j=g();b(j,-1),C(_<0?j.length-1:_),I=Q=>{let Z=typeof Q.composedPath=="function"?Q.composedPath():[];Z.includes(s)||Z.includes(o)||z()},S().addEventListener("focusin",I,!0),E=()=>h(),s.addEventListener("focusin",E),O=()=>{u=!1},s.addEventListener("pointerdown",O,!0)},w=_=>{_.preventDefault(),_.stopPropagation(),W()?z(!0):H(0)},k=_=>{if(_.key==="ArrowDown"||_.key==="Enter"||_.key===" "){_.preventDefault(),u=!0,W()?C(0):H(0,!0);return}_.key==="ArrowUp"&&(_.preventDefault(),u=!0,W()?C(-1):H(-1,!0))},R=_=>{switch(OP.has(_.key)&&(u=!0),_.key){case"ArrowDown":_.preventDefault(),C(p+1);return;case"ArrowUp":_.preventDefault(),C(p-1);return;case"Home":_.preventDefault(),C(0);return;case"End":_.preventDefault(),C(g().length-1);return;case"Escape":_.preventDefault(),_.stopPropagation(),z(!0);return;case"Tab":z(!0);return;default:}};return r.addEventListener("click",w),r.addEventListener("keydown",k),s.addEventListener("keydown",R),{trigger:o,triggerButton:r,panel:s,setItems:_=>{for(let j of d)_.includes(j)||j.removeAttribute(xg);if(d=[..._],!W())return;let X=g();b(X,Math.min(p,X.length-1)),h()},isOpen:W,open:()=>H(0),close:z,setLabel:_=>{_!==e&&(e=_,l())},applyButtonSize:a,destroy:()=>{n=!0,M(),D(),r.removeEventListener("click",w),r.removeEventListener("keydown",k),s.removeEventListener("keydown",R),L?.destroy(),L=null,o.remove(),s.remove(),d=[]}}}var sr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},bx="data-persona-composer-action",Sg="data-persona-composer-disable-when-streaming",_P="core:overflow",NP=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function FP(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 Ag(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 vx=(t,e)=>{!t||typeof console>"u"||console.warn(e)},$P=(t,e)=>e.includes(":")?e:`${t}:${e}`;function VP(t){let{debug:e}=t,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){vx(e,`[Persona] composer action "${l.id}" is already contributed by ${Cx(d)}; the ${Cx(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?$P(p,l.id):l.id,m=l.order??sr.custom;l.placement==="end"&&m>=sr.send&&(vx(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${sr.send-1}.`),m=sr.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 Cx=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",wx=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,zP=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function qP(t,e){if(!t||t==="always")return!0;let n=zP(e);return t==="when-text"?n:!n}var fs=t=>t.kind==="custom",Mg=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,UP=t=>{let e=Mg(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},jP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function KP(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(jP)||o.childNodes.forEach(n)};return n(t),e.trim()}var GP=t=>KP(t).length===0;function xx(t){let e=new Map,n=[],o=!1,r=()=>t.getButtonSize?.(),s=(w,k)=>{let R=w.button;if(!R)return;R.setAttribute("role","menuitem"),R.setAttribute("tabindex","-1"),R.className="persona-composer-overflow-menu__item";for(let j of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])R.style[j]="";R.style.lineHeight="1",k.tooltipText?R.setAttribute("title",k.tooltipText):R.removeAttribute("title"),R.replaceChildren();let _=v("span","persona-composer-overflow-menu__icon");if(k.iconName){let j=He(k.iconName,16,"currentColor",1.5);j&&_.appendChild(j)}let X=v("span","persona-composer-overflow-menu__label");X.textContent=k.shortLabel??k.label,R.append(_,X)},a=(w,k)=>{let R=w.button;if(!R)return;if(R.setAttribute("aria-label",k.label),k.pressed===void 0?R.removeAttribute("aria-pressed"):R.setAttribute("aria-pressed",k.pressed?"true":"false"),R.toggleAttribute(Sg,k.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,s(w,k);return}R.removeAttribute("role"),R.removeAttribute("tabindex"),R.removeAttribute("title");let _=r(),X=!!k.shortLabel;if(R.className=Dt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",uo,No,X&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),R.style.width=_&&!X?_:"",R.style.height=_??"",R.style.minWidth=_&&!X?_:"",R.style.minHeight=_??"",R.style.fontSize=X?"":"18px",R.style.lineHeight="1",R.style.color=k.iconColor??"",R.style.backgroundColor=k.backgroundColor??"",R.replaceChildren(),k.iconName){let j=He(k.iconName,Vn,"currentColor",1.5);j&&R.appendChild(j)}if(X){let j=v("span","persona-composer-action-button__label");j.textContent=k.shortLabel,R.appendChild(j)}else R.firstChild||(R.textContent=k.label);w.tooltip?.destroy(),w.tooltip=En({anchor:R,trigger:w.element,text:()=>k.tooltipText??k.label,enabled:!!k.tooltipText})},l=(w,k)=>{let R=w.action,_=q("button",{attrs:{type:"button"}}),X=_;if(k==="bar"){let Z=v("div","persona-send-button-wrapper");Z.appendChild(_),X=Z}X.setAttribute(bx,w.id);let j={resolved:w,element:X,button:_,owned:!0,managed:!0,busy:!1,visible:!0,mode:k},Q=Z=>{if(Z.preventDefault(),Z.stopPropagation(),j.busy||_.disabled)return;let ie=j.resolved.action;j.mode==="menu"&&g?.close(!0);let se;try{se=ie.onSelect(t.actionContext,Z)}catch(pe){t.reportError(pe,{actionId:j.resolved.id});return}!se||typeof se.then!="function"||(j.busy=!0,_.setAttribute("aria-busy","true"),se.catch(pe=>{t.reportError(pe,{actionId:j.resolved.id})}).finally(()=>{j.busy=!1,_.removeAttribute("aria-busy")}))};return _.addEventListener("click",Q),j.detach=()=>_.removeEventListener("click",Q),a(j,R),j},d=w=>{let k=w.action,R;try{R=k.render({...t.actionContext,id:w.id,action:k})}catch(_){return t.reportError(_,{actionId:w.id}),null}return R?.element?(R.element.setAttribute(bx,w.id),R.element.toggleAttribute(Sg,k.disableWhenStreaming===!0),{resolved:w,element:R.element,owned:!0,managed:!0,destroy:R.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,k)=>{if(w.builtIn){let _=w.builtIn.element;return _?{resolved:w,element:_,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let R=w.action;return R?fs(R)?d(w):l(w,k):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(k){t.reportError(k,{actionId:w.resolved.id})}w.element.remove()}},m=(w,k)=>{for(let R=0;R<k.length;R++){let _=k[R];if(!_.managed)continue;let X=null;for(let j=R+1;j<k.length;j++){let Q=k[j];if(!Q.managed&&Q.element.parentElement===w){X=Q.element;break}}X?(_.element.parentElement!==w||_.element.nextSibling!==X)&&w.insertBefore(_.element,X):w.lastChild!==_.element&&w.appendChild(_.element)}},h=(w,k)=>{if(w.button){w.button.disabled=k;return}if(!w.owned)return;let R=w.element;R.toggleAttribute("data-disabled",k),R.setAttribute("aria-disabled",k?"true":"false");let _=R instanceof HTMLButtonElement||R instanceof HTMLSelectElement||R instanceof HTMLInputElement||R instanceof HTMLTextAreaElement?R:R.querySelector("button, select, input, textarea");_&&(_.disabled=k)},g=null,b=null,C=null,S=0,I=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},E=()=>(g?g.setLabel(t.getOverflowLabel?.()??"More actions"):g=yx({label:t.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),O=w=>{b!==w&&(C?.disconnect(),b=w,S=Ag(w),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(k=>{let _=k[k.length-1]?.contentRect?.width??Ag(w);_!==S&&(S=_,z())}),C.observe(w)))},M=(w,k)=>{let R=FP(w.collapseAutoActionsBelow,k);if(R===null)return!1;let _=S||Ag(k);return _>0&&_<R},D=(w,k,R)=>{if(!k)return"bar";if(w.resolved.builtIn){let X=NP(w.resolved.id);return X&&k.includeBuiltIns?.includes(X)?"menu":"bar"}let _=w.resolved.presentation;return _==="overflow"||_==="auto"&&R?"menu":"bar"},L=w=>{let k=w.menuSlot;if(!k)return;if(!GP(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let R=UP(w.element);if(!R){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=v("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==R&&(w.menuLabel.textContent=R),w.menuLabel.parentElement!==k&&k.appendChild(w.menuLabel)},B=(w,k)=>{if(w.mode===k)return w;let R=w.resolved.action;if(R&&!fs(R)){u(w),e.delete(w.resolved.id);let _=l(w.resolved,k);return e.set(w.resolved.id,_),_}if(k==="menu"){let _=q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[gg]:""}});_.appendChild(w.element),sx(Mg(w.element)),w.menuSlot=_;let X=j=>{let Q=Mg(w.element);if(Q.disabled)return;let Z=j.target===Q||Q.contains(j.target);g?.close(!0),Z||Q.click()};_.addEventListener("click",X,!0),w.detachMenuSlot=()=>_.removeEventListener("click",X,!0),w.managed=!0,L(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=k,w},W=(w,k)=>{let R=k.map(_=>_.menuSlot??_.element);for(R.forEach((_,X)=>{let j=w.children[X];j!==_&&(j?w.insertBefore(_,j):w.appendChild(_))});w.children.length>R.length;)w.lastElementChild?.remove()},z=()=>{if(o)return;let w=t.getBindings();if(!w)return;let k=t.getState(),R=k.phase==="streaming",_=I();_&&O(w.footer);let X=_?M(_,w.footer):!1,j={start:[],end:[]},Q=[];for(let Z of n){let ie=e.get(Z.id);if(!ie)continue;let se=Z.action,pe=se?wx(se.visible,k,!0)&&qP(se.visibility,k):!0;if(ie.visible!==pe&&(ie.visible=pe,!pe&&ie.managed&&(ie.menuSlot??ie.element).remove()),!!pe){if(ie=B(ie,D(ie,_,X)),se){let ue=wx(se.disabled,k,!1)||se.disableWhenStreaming===!0&&R;h(ie,ue),!fs(se)&&se.pressed!==void 0&&ie.button?.setAttribute("aria-pressed",se.pressed?"true":"false")}ie.mode==="menu"?(L(ie),Q.push(ie)):j[Z.placement].push(ie)}}if(Q.length>0){let Z=E();W(Z.panel,Q),Z.setItems(Q.map(ue=>ue.menuSlot??ue.element)),Z.applyButtonSize();let ie=Number.isFinite(_?.order)?_?.order:sr.overflow,se=j.start.findIndex(ue=>ue.resolved.order>ie),pe={resolved:{id:_P,placement:"start",presentation:"bar",order:ie,sequence:-1,source:"core"},element:Z.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};j.start.splice(se<0?j.start.length:se,0,pe)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));m(w.actionsStart,j.start),m(w.actionsEnd,j.end)};return{resolve:()=>{if(o)return;let w=VP(t.collect()),k=new Set(w.map(R=>R.id));for(let[R,_]of e)k.has(R)||(u(_),e.delete(R));for(let R of w){let _=e.get(R.id);if(!_){let Z=p(R,"bar");Z&&e.set(R.id,Z);continue}let X=_.resolved.action,j=R.action;if(!!X!=!!j||X&&j&&fs(X)!==fs(j)||X&&j&&fs(X)&&fs(j)&&X.render!==j.render){u(_),e.delete(R.id);let Z=p(R,_.mode);Z&&e.set(R.id,Z);continue}_.resolved=R,R.builtIn?(_.managed=R.builtIn.managed===!0||_.mode==="menu",R.builtIn.element&&_.mode==="bar"&&(_.element=R.builtIn.element)):j&&!fs(j)?a(_,j):j&&_.element.toggleAttribute(Sg,j.disableWhenStreaming===!0)}n=w,z()},sync:z,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=[]}}}}ha();qe();en();var YP="core:model",QP=700,Sx=16,XP=["--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"],Ax=()=>{let t=q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Mx(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=q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=t.getModels(),S=C.map(I=>`${I.id}:${I.label}`).join("|");S!==p&&(p=S,d.replaceChildren(...C.map(I=>{let E=q("option",{attrs:{value:I.id}});return E.textContent=I.label,E}))),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}=Ax();return g.append(d,b),{element:g,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",h)}}},a=()=>{let d=q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=v("span","persona-composer-model-picker-label"),u=v("span","persona-composer-model-picker-suffix");d.append(p,u);let m=q("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=(k=!1)=>{C()&&(b?.close(),d.setAttribute("aria-expanded","false"),k&&d.focus())},I=k=>{let R=[...h.values()];if(R.length===0)return;let _=(k%R.length+R.length)%R.length;R[_].focus()},E=k=>{if(C())return;b||(b=ms({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),kp(d,m,XP),b.open(),d.setAttribute("aria-expanded","true");let _=[...h.keys()].indexOf(r(t.getModels())?.id??"");I(k??(_>=0?_:0))},O=k=>{S(!0),t.onSelect(k)},M=k=>{k.preventDefault(),k.stopPropagation();let R=k.currentTarget.getAttribute("data-persona-model-option");R&&O(R)},D=k=>{let R=q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":k.id}});if(k.icon){let Z=He(k.icon,Sx,"currentColor",1.5);if(Z){let ie=v("span","persona-composer-model-option-icon");ie.appendChild(Z),R.appendChild(ie)}}let _=v("span","persona-composer-model-option-body"),X=v("span","persona-composer-model-option-label");if(X.textContent=k.label,_.appendChild(X),k.description){let Z=v("span","persona-composer-model-option-description");Z.textContent=k.description,_.appendChild(Z)}R.appendChild(_);let j=v("span","persona-composer-model-option-check");j.setAttribute("aria-hidden","true");let Q=He("check",Sx,"currentColor",2);return Q&&j.appendChild(Q),R.appendChild(j),R.addEventListener("click",M),R},L=()=>{let k=t.getModels(),R=k.map(j=>`${j.id}:${j.label}:${j.icon??""}:${j.description??""}`).join("|");if(R!==g){g=R;for(let j of h.values())j.removeEventListener("click",M);h.clear(),m.replaceChildren(...k.map(j=>{let Q=D(j);return h.set(j.id,Q),Q}))}let _=r(k);for(let[j,Q]of h)Q.setAttribute("aria-selected",String(j===_?.id));p.textContent=_?.label??"";let X=t.getSuffix?.()??"";u.textContent=X,d.setAttribute("aria-label",[e,[_?.label,X].filter(Boolean).join(" ")].filter(Boolean).join(": "))};L(),o=L;let B=k=>{k.preventDefault(),k.stopPropagation(),C()?S(!0):E()},W=k=>{if(k.key==="ArrowDown"){k.preventDefault(),C()?I(0):E(0);return}k.key==="ArrowUp"&&(k.preventDefault(),C()?I(-1):E(-1))},z=k=>{let R=[...h.values()],_=R.indexOf(k.target?.closest?.(".persona-composer-model-option"));switch(k.key){case"ArrowDown":k.preventDefault(),I(_+1);return;case"ArrowUp":k.preventDefault(),I(_-1);return;case"Home":k.preventDefault(),I(0);return;case"End":k.preventDefault(),I(R.length-1);return;case"Escape":k.preventDefault(),k.stopPropagation(),S(!0);return;case"Tab":S(!0);return;default:}};d.addEventListener("click",B),d.addEventListener("keydown",W),m.addEventListener("keydown",z);let{wrapper:H,chevron:w}=Ax();return H.append(d,w),{element:H,destroy:()=>{o===L&&(o=null),d.removeEventListener("click",B),d.removeEventListener("keydown",W),m.removeEventListener("keydown",z);for(let k of h.values())k.removeEventListener("click",M);h.clear(),b?.destroy(),b=null,m.remove()}}};return{action:{id:YP,kind:"custom",placement:"end",order:QP,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}qe();en();Dp();var JP=":scope > [data-persona-composer-mode]";function Tx(t){let e=t.row,n="",o=!1,r=new Set(t.initialIds??[]),s=p=>{let u=q("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=He(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=q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),g=He("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(JP)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),ya(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(E=>E.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}ya(e)},destroy:()=>{o=!0,d(),ya(e)}}}qe();en();var Ex=t=>`core:mode:${t}`;var kg=t=>Math.min(300+t,499),kx=t=>`core:mode-group:${t}`;function _p(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function ZP(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Lx(t,e){return t?.length?t.filter(n=>!_p(n.groupId,e)&&!ZP(n.groupId,e)):[]}var eI=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Px(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(eI(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 Np(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Ix(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Hx(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var tI=16;function Rx(t){let e=null;return{action:{id:kx(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=q("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=q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=He(p.iconName,tI,"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?.()}}Dp();qe();en();function Wx(t){let e=q("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=q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=pp(s.text),l.appendChild(d);let p=q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=He("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()}}}qe();en();function Bx(t){let e=q("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=q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=He(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=pp(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=q("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()}}}qe();function Ox(t){let e=q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=q("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=q("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 Dx(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 _x(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 Nx(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 Fx(t){return t.wrapped||t.text.includes(`
|
|
1156
|
+
`)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function $x(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function Vx(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}Fp();function Lg(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 Ux(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var nI=t=>typeof t?.then=="function";function qx(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 jx(t,e,n){let o;try{o=t(Lg(e),{signal:n})}catch(r){return{status:"error",error:r}}return nI(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:qx(e,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):qx(e,o)}qe();$p();Pg();qe();en();function Qx(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",r=e.buttonTooltipText??"Add context",s=v("div","persona-send-button-wrapper"),a=q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${uo} ${No}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=He(o,Vn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),En({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}eo();var{setLoader:oN,load:cI}=zt({fallbackImport:()=>Promise.resolve().then(()=>(fS(),mS))});var Wg=cI;en();eo();var{setLoader:gN,load:vI}=zt({fallbackImport:()=>Promise.resolve().then(()=>(TS(),MS)),resetOnSetLoader:!0});var ES=vI;qe();en();function Gl(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=q("span",{className:Dt("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=He(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(q("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function kS(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Vp(e).filter(M=>M.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(M=>M.sources.some(D=>typeof D.matchCommand=="function")),r=M=>o.some(D=>D.trigger?D.position==="line-start"?M.split(`
|
|
1157
1157
|
`).some(B=>B.startsWith(D.trigger)):(D.position==="anywhere"?M:M.split(`
|
|
1158
|
-
`)[0]).startsWith(D.trigger):!1),s=(M,D)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${M}`,{detail:D}))}catch{}},a=!t.chipRow,l=t.chipRow??q("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 M=Hg().then(D=>(D.setMentionIconRenderer(He),d=D.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:O,emit:s}),d)).catch(D=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",D),p===M&&(p=null),null));return p=M,M},S=()=>{AS().then(M=>{let D=M.mountInlineComposer({textarea:t.textarea,renderToken:B=>Kl(B,{render:e.renderMentionToken}),onMentionRemoved:B=>d?.untrackMention(B)});m=D.input,h=D.destroy;let L=u;L.replaceWith(D.element),u=D.element,b={next:D.element,prev:L},g?.(D.element,L),d?d.rebindComposer(D.input):p&&p.then(B=>B?.rebindComposer(D.input))}).catch(M=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",M)})};e.display==="inline"&&S();let I=[],E=new Map;for(let M of n){if(!M.showButton)continue;let D=Kx({config:{...e,buttonIconName:M.buttonIconName,buttonTooltipText:M.buttonTooltipText},onOpen:()=>{C().then(L=>L?.openMenu(M.trigger))}});I.push(D),E.set(M.trigger,D.button)}let O=(M,D,L)=>{let B=E.get(D);B&&(B.setAttribute("aria-expanded",M?"true":"false"),M?B.setAttribute("aria-controls",L):B.removeAttribute("aria-controls"))};return{affordanceButtons:I.map(M=>M.wrapper),contextRow:l,handleInput:M=>{if(d){d.handleInput();return}if(!Ux(M))return;let D=u,L=D.selectionStart??0;Vl(D.value,L,n)&&C().then(B=>B?.handleInput())},handleKeydown:M=>{if(d?.isMenuOpen())return d.handleKeydown(M);if(M.key==="Backspace"&&d?.hasMentions()&&!b){let D=u,L=D.selectionStart===0&&D.selectionEnd===0;if((D.value.length===0||L)&&d.removeLastChip())return M.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async M=>r(M)?(d??await C())?.dispatchInlineCommand(M)??null:null,clear:()=>d?.clear(),prefetch:()=>{Hg().catch(()=>{})},onComposerSwap:M=>{g=M,b&&M(b.next,b.prev)},destroy:()=>{d?.destroy(),h?.();for(let M of I)M.wrapper.remove();a&&l.remove()}}}var Jp="16px",Zp="transparent",mI=(()=>{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})(),fI={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:mI,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"}},gI={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"}},hI={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:Pr,maxWidth:ix,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Jp,canvasBackground:Zp},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Vn(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."))?Vn(t,o):o}function ES(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=Vn(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 yI(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 kS(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]=kS(s,r):n[o]=r}return n}function bI(t,e){return e?kS(t,e):t}function ya(t,e={}){let n={palette:fI,semantic:gI,components:hI},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:bI(n.components,t?.components)};if(e.validate!==!1){let r=yI(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 $g=t=>t.trim()==="0"?"0px":t,TS="--persona-",vI=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},CI=.179,En=(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[TS+s],r!==void 0)break;r!==void 0&&(t[TS+n]=r)}};function LS(t){let e=ES(t),n={};for(let[F,Ce]of Object.entries(e)){let Ee=F.replace(/\./g,"-");n[`--persona-${Ee}`]=Ce.value}En(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"],En(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"]]),En(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"]}`,En(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"]??Jp,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Zp,En(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"]]),En(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"],En(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"],En(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[F,Ce]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ee=n[`--persona-components-history-overlay-${F}`];Ee&&(n[`--persona-history-overlay-${Ce}`]=Ee)}for(let[F,Ce]of[["background","bg"],["borderRadius","radius"]]){let Ee=n[`--persona-components-history-menu-${F}`];Ee&&(n[`--persona-history-menu-${Ce}`]=Ee)}let m=t.components?.history?.motion;if(m){let F=qe=>{if(qe===void 0)return;let ke=String(qe).trim();return/^\d+(\.\d+)?$/.test(ke)?`${ke}ms`:ke},Ce=F(m.enterDurationMs);Ce!==void 0&&(n["--persona-history-enter-ms"]=Ce);let Ee=F(m.exitDurationMs);Ee!==void 0&&(n["--persona-history-exit-ms"]=Ee),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 F of["scrim","shadow"]){let Ce=n[`--persona-components-history-confirm-${F}`];Ce&&(n[`--persona-history-confirm-${F}`]=Ce)}for(let[F,Ce]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ee=n[`--persona-components-tooltip-${F}`];Ee&&(n[`--persona-tooltip-${Ce}`]=Ee)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[F,Ce]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ee=n[`--persona-components-messageActions-${F}`];Ee&&(n[`--persona-message-action-${Ce}`]=Ee)}En(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,En(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"],["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"]]),En(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 I=n["--persona-components-markdown-heading-h1-fontSize"];I&&(n["--persona-md-h1-size"]=I);let E=n["--persona-components-markdown-heading-h1-fontWeight"];E&&(n["--persona-md-h1-weight"]=E);let O=n["--persona-components-markdown-heading-h2-fontSize"];O&&(n["--persona-md-h2-size"]=O);let M=n["--persona-components-markdown-heading-h2-fontWeight"];M&&(n["--persona-md-h2-weight"]=M);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),En(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"]]),En(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),En(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),En(n,[["md-hr-color","components-markdown-hr-color","divider"]]),En(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"],En(n,[["message-border","components-message-border","border"]]),En(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 L=t.components,B=L?.iconButton;B&&(B.background&&(n["--persona-icon-btn-bg"]=B.background),B.border&&(n["--persona-icon-btn-border"]=B.border),B.color&&(n["--persona-icon-btn-color"]=B.color),B.padding&&(n["--persona-icon-btn-padding"]=B.padding),B.borderRadius&&(n["--persona-icon-btn-radius"]=B.borderRadius),B.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=B.hoverBackground),B.hoverColor&&(n["--persona-icon-btn-hover-color"]=B.hoverColor),B.activeBackground&&(n["--persona-icon-btn-active-bg"]=B.activeBackground),B.activeBorder&&(n["--persona-icon-btn-active-border"]=B.activeBorder));let W=L?.labelButton;W&&(W.background&&(n["--persona-label-btn-bg"]=W.background),W.border&&(n["--persona-label-btn-border"]=W.border),W.color&&(n["--persona-label-btn-color"]=W.color),W.padding&&(n["--persona-label-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-label-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-label-btn-hover-bg"]=W.hoverBackground),W.fontSize&&(n["--persona-label-btn-font-size"]=W.fontSize),W.gap&&(n["--persona-label-btn-gap"]=W.gap));let z=L?.toggleGroup;z&&(z.gap&&(n["--persona-toggle-group-gap"]=z.gap),z.borderRadius&&(n["--persona-toggle-group-radius"]=z.borderRadius));let H=L?.artifact;if(H?.toolbar){let F=H.toolbar;F.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=F.iconHoverColor),F.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=F.iconHoverBackground),F.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=F.iconPadding),F.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=F.iconBorderRadius),F.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=F.iconBorder),F.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=$g(F.toggleGroupGap)),F.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=F.toggleBorderRadius),F.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=$g(F.toggleGroupPadding)),F.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=F.toggleGroupBorder),F.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=F.toggleGroupBorderRadius),F.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Vn(t,F.toggleGroupBackground)??F.toggleGroupBackground),F.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=F.copyBackground),F.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=F.copyBorder),F.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=F.copyColor),F.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=$g(F.copyBorderRadius)),F.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=F.copyPadding),F.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=F.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??F.copyMenuBackground),F.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=F.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??F.copyMenuBorder),F.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=F.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??F.copyMenuShadow),F.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=F.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??F.copyMenuBorderRadius),F.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=F.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??F.copyMenuItemHoverBackground),F.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=F.iconBackground),F.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=F.toolbarBorder)}if(H?.tab){let F=H.tab;F.background&&(n["--persona-artifact-tab-bg"]=F.background),F.activeBackground&&(n["--persona-artifact-tab-active-bg"]=F.activeBackground),F.activeBorder&&(n["--persona-artifact-tab-active-border"]=F.activeBorder),F.borderRadius&&(n["--persona-artifact-tab-radius"]=F.borderRadius),F.textColor&&(n["--persona-artifact-tab-color"]=F.textColor),F.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=F.hoverBackground),F.listBackground&&(n["--persona-artifact-tab-list-bg"]=F.listBackground),F.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=F.listBorderColor),F.listPadding&&(n["--persona-artifact-tab-list-padding"]=F.listPadding)}if(H?.pane){let F=H.pane;if(F.toolbarBackground){let Ce=Vn(t,F.toolbarBackground)??F.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ce}}if(H?.card){let F=H.card;F.background&&(n["--persona-artifact-card-bg"]=F.background),F.border&&(n["--persona-artifact-card-border"]=F.border),F.borderRadius&&(n["--persona-artifact-card-radius"]=F.borderRadius),F.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=F.hoverBackground),F.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=F.hoverBorderColor)}if(H?.inline){let F=H.inline;F.background&&(n["--persona-artifact-inline-bg"]=Vn(t,F.background)??F.background),F.border&&(n["--persona-artifact-inline-border"]=F.border),F.borderRadius&&(n["--persona-artifact-inline-radius"]=F.borderRadius),F.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Vn(t,F.chromeBackground)??F.chromeBackground),F.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Vn(t,F.chromeBorder)??F.chromeBorder),F.titleColor&&(n["--persona-artifact-inline-title-color"]=Vn(t,F.titleColor)??F.titleColor),F.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Vn(t,F.mutedColor)??F.mutedColor),F.frameHeight&&(n["--persona-artifact-inline-frame-height"]=F.frameHeight)}let w=L?.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"]=Vn(t,w.background)??w.background));let k=n["--persona-surface"],R=n["--persona-container"],_=n["--persona-palette-colors-gray-100"]??"#f3f4f6",X=n["--persona-palette-colors-gray-200"]??"#e5e7eb",j=n["--persona-palette-colors-gray-300"]??"#d1d5db",Q=!R||R===k,Z=vI(k??n["--persona-background"]),ie=Q&&Z!==void 0&&Z<CI,se=ie?"rgba(255, 255, 255, 0.08)":_,pe=ie?"rgba(255, 255, 255, 0.12)":X,ue=ie?"rgba(255, 255, 255, 0.16)":j,xe=Q?se:R,be=Q?pe:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??xe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??be,Q&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ue),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??xe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??xe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??xe,n}var wI={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"}}},xI={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},PS=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Vg=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",SI=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Vg()},IS=t=>SI(t),AI=t=>ya(t),MI=t=>{let e=ma(xI,t??{})??{};return ya({...e,palette:{...e.palette,colors:{...wI.colors,...e.palette?.colors}}},{validate:!1})},ba=t=>{let e=IS(t),n=PS(t?.theme),o=PS(t?.darkTheme);return e==="dark"?MI(ma(n??{},o??{})):AI(n)},TI=t=>LS(t),Gl=(t,e)=>{let n=ba(e),o=TI(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",IS(e))},eu=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Vg())});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(Vg());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 Or=require("lucide");Jt();eo();Ue();var gs=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var tu="24px",zg=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",Yl=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},HS=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var RS=null;var qg=()=>{if(RS!==null)return RS;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},EI="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",nu=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},ou=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 nu("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(nu("unsupported",t),null):(n==="space"&&(o.key=" "),o)},kI=t=>EI.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),WS=(t,e)=>{let n=ou(t);if(!n)return"";let o=qg(),r=kI(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("+")},ru=t=>WS(t,!1),Ql=t=>WS(t,!0),LI=(t,e)=>e.key?.toLowerCase()===t.key&&(qg()?e.metaKey:e.ctrlKey)===t.mod&&!(qg()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,PI=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},BS=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(LI(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&PI(a))){s.preventDefault();try{l.run(s)}catch(d){nu(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=ou(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=e.get(l);return d?(nu(`${d.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",Ql(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};var OS=require("idiomorph"),su=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;OS.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 DS=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Ug={index:-1,draft:""};function _S(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 NS(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 FS(){return new Map}function $S(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function VS(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function zS(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}Kg();us();nc();Zn();var{setLoader:zN,load:tH}=Ft({fallbackImport:()=>Promise.resolve().then(()=>(uA(),pA))});var mA=tH;us();function Zg(t,e=In){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 rc=0,hs=null;function eh(t=document){if(rc++,rc===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;hs={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,rc=Math.max(0,rc-1),rc===0&&hs)){let n=t.body,o=t.defaultView??window;n.style.overflow=hs.originalOverflow,n.style.position=hs.originalPosition,n.style.top=hs.originalTop,n.style.width=hs.originalWidth,o.scrollTo(0,hs.scrollY),hs=null}}}var sc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},an=t=>(t?.launcher?.mountMode??"floating")==="docked",ic=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Eo=t=>{let e=t?.launcher?.dock;return{side:e?.side??sc.side,width:e?.width??sc.width,animate:e?.animate??sc.animate,reveal:e?.reveal??sc.reveal,maxHeight:e?.maxHeight??sc.maxHeight}};Ue();Ue();var gA=require("lucide");Jt();eo();var th=t=>t==="followUp"?"follow-up":t,nh=(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"}},nH=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'}},fA=new WeakSet,oH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,rH=t=>{oH()||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"})})},oh=t=>{var O,M,D;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 L={suggestion:{...e},surface:o,source:r,behavior:C},B=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:L,bubbles:!0,composed:!0,cancelable:!0}));if(b&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!B)return;for(let z of d)if(z.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let W=m();if(C==="fill"){W.value=e.prompt,W.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),W.focus();return}if(g){g(e.prompt);return}W.value="",u.sendMessage(e.prompt)},I=()=>{let L=v("button",`persona-suggestion persona-suggestion--${s}`);if(L.type="button",L.disabled=a,L.dataset.suggestionId=e.id,L.dataset.emphasis=e.emphasis,L.dataset.behavior=C,s==="chip"&&(p?.fontFamily&&(L.style.fontFamily=nH(p.fontFamily)),p?.fontWeight&&(L.style.fontWeight=p.fontWeight),p?.paddingX&&(L.style.paddingLeft=p.paddingX,L.style.paddingRight=p.paddingX),p?.paddingY&&(L.style.paddingTop=p.paddingY,L.style.paddingBottom=p.paddingY)),e.icon){let W=He(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);W&&(W.classList.add("persona-suggestion__icon"),e.iconColor&&(W.style.color=e.iconColor),L.appendChild(W))}let B=v("span","persona-suggestion__copy");if(B.appendChild(q("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&B.appendChild(q("span",{className:"persona-suggestion__description",text:e.description})),L.appendChild(B),s!=="chip"){let W=Ke(gA.ArrowRight,16,"currentColor",1.8);W&&(W.classList.add("persona-suggestion__arrow"),L.appendChild(W))}return L.addEventListener("click",S),L},E=null;for(let L of d)if(L.renderSuggestion&&(E=L.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:I,select:S}),E))break;return E??(E=I()),(O=E.dataset).suggestionId||(O.suggestionId=e.id),(M=E.dataset).behavior||(M.behavior=C),(D=E.dataset).emphasis||(D.emphasis=e.emphasis),E instanceof HTMLButtonElement||E.setAttribute("aria-disabled",a?"true":"false"),E},ac=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,I=m?!b:!C;t.toggleAttribute("data-scroll-left",S),t.toggleAttribute("data-scroll-right",I)},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",I=C?.surface??(S==="config"?"starter":"followUp"),E=I==="followUp",O=C?.variant??"chip",M=C?.behavior??"send",D=C?.overflow??"wrap",L=C?.config??{},B=C?.plugins??[],W=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,z=E?"followUps":"starters";!fA.has(L)&&L.debug===!0&&O!=="chip"&&L.suggestions?.[z]?.overflow!==void 0&&(fA.add(L),console.info(`[persona] suggestions.${z}.overflow applies to the "chip" variant only; the "${O}" variant manages its own stacking.`));let H=j=>j.map(nh).filter(Q=>Q!==null).map(Q=>({...Q,behavior:Q.behavior??M})),w=H(u??[]);B.forEach(j=>{j.transformSuggestions&&(w=H(j.transformSuggestions({suggestions:w.map(Q=>({...Q})),surface:I,source:S,config:L})))});let k=W===void 0?w:w.slice(0,W);if(!k.length){t.hidden=!0,o=null,s();return}if(!E&&(g??m.getMessages()).some(Q=>Q.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=th(I),t.dataset.variant=O,t.dataset.overflow=D;let R=document.createDocumentFragment(),_=m.isStreaming();k.forEach((j,Q)=>{let Z=oh({item:j,index:Q,surface:I,source:S,variant:O,streaming:_,config:L,plugins:B,chipsConfig:b,session:m,getTextarea:()=>h,eventTarget:t,submitPrompt:C?.submitPrompt});R.appendChild(Z),n.push(Z),[...Z instanceof HTMLButtonElement?[Z]:[],...Array.from(Z.querySelectorAll("button"))].forEach(se=>{e.includes(se)||(se.disabled=_,e.push(se))})}),t.appendChild(R),a(),l();let X=JSON.stringify({normalized:k,surface:I,variant:O,source:S});X!==o&&(o=X,rH(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:k.map(j=>({...j})),surface:I,source:S,variant:O},bubbles:!0,composed:!0})),E&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:k.map(j=>j.prompt)},bubbles:!0,composed:!0})))}}};var uo={"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"};us();Ue();Jt();Ue();Jt();var sH="persona-header-control",iH="persona-header-control--glyph",aH="persona-header-control--sparse",lH=20,cH={x:[1.4,1.05]},hA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",dH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",uu=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=cH[e]??[1,1.5],l=!o;t.classList.toggle(iH,l),t.classList.toggle(aH,l&&s!==1);let d=parseFloat(o??"")||lH,p=He(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)},si=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=hA,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:h,borderRadius:g,paddingX:b,paddingY:C,hidden:S,extraClassName:I,attrs:E}=t,O=v("div",a),M=!!(m||h),D=q("button",{className:Bt(sH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!M&&"persona-border-none",!g&&"persona-rounded-full",I),attrs:{type:"button","aria-label":e,...E},style:{width:l,height:l,minWidth:l,minHeight:l,display:S?"none":void 0,color:p||zn.actionIconColor,backgroundColor:u,border:M?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:g,paddingLeft:b,paddingRight:b,paddingTop:C,paddingBottom:C}});return r?uu(D,r,{iconSize:d,iconText:s}):s&&(D.textContent=s),O.appendChild(D),Tn({anchor:D,trigger:O,text:()=>D.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:D,wrapper:O}},Ca=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=hA,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=si({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}},wa=(t,e={})=>{let{wrapperClassName:n=dH,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=si({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 zn={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)"},rh={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)"},pH={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)"},ii=t=>{let{config:e,showClose:n=!0}=t,o=q("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:zn.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=q("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 D=parseFloat(s)||24,L=He(d,D*.6,"currentColor",1);L?p.replaceChildren(L):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let D=v("img");D.src=e.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,p.replaceChildren(D)}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=q("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:zn.titleColor,...rh}}),h=q("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:zn.subtitleColor,...pH}});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,I=null;if(b){let L=wa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=L.button,I=L.wrapper,C==="top-right"&&(I.style.right="48px"),C==="inline"&&o.appendChild(I)}let E=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:O,wrapper:M}=Ca(e,{showClose:n,wrapperClassName:E});return a!=="top-right"&&o.appendChild(M),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:h,closeButton:O,closeButtonWrapper:M,clearChatButton:S,clearChatButtonWrapper:I}},lc=(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))};Ue();sh();li();var uH=t=>{let e=ii({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 mH(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=si({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?ru(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=Ql(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=cc({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 fH=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=zn.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 M=bA({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:D=>{let L=W=>{W===!1&&M.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},B=d.onSelect(D);B instanceof Promise?B.then(L,()=>{}):L(B)},hover:d.hover,className:""});p=M.element,p.style.color=zn.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=zn.titleColor,Object.assign(u.style,rh),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let D=r.onTitleClick;p.addEventListener("click",L=>{L.target.closest("button")||D()}),p.addEventListener("keydown",L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),D())})}let M=r?.titleRowHover;M&&(p.style.borderRadius=M.borderRadius??"10px",p.style.padding=M.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=M.background??"",p.style.borderColor=M.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}=Ca(e,{showClose:n,wrapperClassName:m});o&&h.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");d||mH(b,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},S=null,I=null;if(C.enabled??!0){let M=C.placement??"inline",D=wa(e,{wrapperClassName:M==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});S=D.button,I=D.wrapper,M==="top-right"?I.style.right="48px":b.appendChild(I)}b.appendChild(g),l.appendChild(b);let E=v("div");E.style.display="none";let O=v("span");return O.style.display="none",{header:l,iconHolder:E,headerTitle:u,headerSubtitle:O,closeButton:h,closeButtonWrapper:g,clearChatButton:S,clearChatButtonWrapper:I}},vA={default:uH,minimal:fH},gH=t=>vA[t]??vA.default,fu=(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=gH(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};Ue();var dc=t=>{let{config:e}=t,n=q("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Ip(),r=q("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ep(e);a();let l=kp(e),d=fa(e),p=Lp(e),u=Pp(e),m=q("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=q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),b=q("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}};Ue();var gu=require("lucide");eo();var CA=()=>{let t=q("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=Ke(gu.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=Ke(gu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},hu=t=>{let{config:e}=t,n=q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ip(),r=Pp(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Ep(e,{defaultMaxLines:5});a();let l=kp(e),d=fa(e),p=Lp(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let h=q("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=q("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}};Ue();Jt();Ue();li();Jt();nc();var hH=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}},yH=(t,e)=>{if(!t)return null;let n=hH(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},bH=(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},vH=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ah=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(":"))},lh=320,MA=320,CH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),wH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),xH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),SH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),AH=t=>{if(!t||t.length===0)return null;let e=q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=He(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(q("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},MH=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Kl(o.ref,{readonly:!0,render:e}))}return n},wA="\uE000",xA="\uE001",TH=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=h=>`${wA}${r}:${h}${xA}`,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(MH(e,o));return}t.innerHTML=l;let p=new RegExp(`${wA}${r}:(\\d+)${xA}`),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(Kl(C.ref,{readonly:!0,render:o}),S),g=S}}},EH=(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=`${lh}px`,p.style.maxHeight=`${MA}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}),vH(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}},kH=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(!ah(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=`${lh}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},LH=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(!ah(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=`${lh}px`,r.style.maxHeight=`${MA}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}},PH=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(!ah(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}},pc=()=>{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},IH=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:pc};if(e){let r=e(o);if(r!==null)return r}return pc()},HH=(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},SA=(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},uc=(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},AA={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"}},RH=(t,e,n="bubble",o)=>{if(!o)return;let r=e==="user"?"user":"assistant",s=AA[n??"bubble"]??AA.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)`)},yu="custom:",WH=t=>`${yu}${t}`,TA=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),BH=(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=TA(e,t.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let O=v("div");return O.style.display="none",O.id=`actions-${t.id}`,O.setAttribute("data-actions-for",t.id),O}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],I=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${S} ${h==="hover"?"persona-message-actions-hover":""}`);I.id=`actions-${t.id}`,I.setAttribute("data-actions-for",t.id);let E=(O,M,D)=>{let L=gn({icon:O,label:M,size:14,className:"persona-message-action-btn",chromeless:!0});return L.setAttribute("data-action",D),L};r&&I.appendChild(E("copy","Copy message","copy")),l&&I.appendChild(E("volume-2","Read aloud","read-aloud")),s&&I.appendChild(E("thumbs-up","Upvote","upvote")),a&&I.appendChild(E("thumbs-down","Downvote","downvote")),d&&I.appendChild(E("refresh-cw","Regenerate response","regenerate")),p&&I.appendChild(E("pencil","Edit message","edit")),u&&I.appendChild(E("quote","Quote message","quote"));for(let O of m)I.appendChild(E(O.iconName??"ellipsis",O.label,WH(O.id)));return I},ch=(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=uc(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;RH(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 I=CH(t),E=t.content?.trim()??"",M=I.length>0&&E===la,D=cu(s?.widgetConfig?.features?.streamAnimation),L=s?.widgetConfig?.features?.streamAnimation?.plugins,B=t.role==="assistant"&&D.type!=="none"?Jl(D.type,L):null,W=t.role==="assistant"&&B?.isAnimating?.(t)===!0,z=t.role==="assistant"&&B!==null&&(!!t.streaming||W);z&&B?.bubbleClass&&C.classList.add(B.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),t.streaming&&H.classList.add("persona-content-streaming"),z&&B&&(B.containerClass&&H.classList.add(B.containerClass),H.style.setProperty("--persona-stream-step",`${D.speed}ms`),H.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let w=z?du(t.content??"",D.buffer,B,t,!!t.streaming):t.content??"",k=()=>{let be=e({text:w,message:t,streaming:!!t.streaming,raw:t.rawContent});return z&&B?.wrap==="char"?Zl(be,"char",t.id,{skipTags:B.skipTags}):z&&B?.wrap==="word"?Zl(be,"word",t.id,{skipTags:B.skipTags}):be},R=null;if(M?(R=document.createElement("div"),R.innerHTML=k(),R.style.display="none",H.appendChild(R)):t.contentSegments?.length?TH(H,t.contentSegments,be=>e({text:be,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):H.innerHTML=k(),z&&B?.useCaret&&!M&&E){let be=pu(),F=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=F[F.length-1];if(Ce?.parentNode)Ce.parentNode.insertBefore(be,Ce.nextSibling);else{let Ee=H.lastElementChild;Ee?Ee.appendChild(be):H.appendChild(be)}}if(m&&g==="inline"&&t.createdAt){let be=SA(t,p,"span");be.classList.add("persona-timestamp-inline");let F=H.lastElementChild;F?F.appendChild(be):H.appendChild(be)}if(I.length>0){let be=EH(I,!M&&!!E,()=>{M&&R&&(R.style.display="")});be?C.appendChild(be):M&&R&&(R.style.display="")}let _=wH(t);if(_.length>0){let be=kH(_);be&&C.appendChild(be)}let X=xH(t);if(X.length>0){let be=LH(X);be&&C.appendChild(be)}let j=SH(t);if(j.length>0){let be=PH(j);be&&C.appendChild(be)}let Q=t.contentSegments?.length?null:AH(t.contextMentions);if(Q&&C.appendChild(Q),C.appendChild(H),m&&g==="below"&&t.createdAt){let be=SA(t,p);be.classList.add("persona-mt-1"),C.appendChild(be)}let Z=t.role==="assistant"?yH(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let be=!!(w&&w.trim()),F=D.placeholder==="skeleton",Ce=F&&D.buffer==="line"&&be;if(be)Ce&&C.appendChild(ec());else if(F)C.appendChild(ec());else{let Ee=IH("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Ee&&C.appendChild(Ee)}}Z&&t.stopReason&&!t.streaming&&(E||(H.style.display="none"),C.appendChild(bH(t.stopReason,Z)));let ie=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,se=s?.actionEligibility,pe=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&se?.canEdit===!0||o?.showQuote===!0&&se?.canQuote===!0||TA(o,"user").length>0);if((ie||pe)&&o){let be=BH(t,pe?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,se);C.appendChild(be)}if(!u||t.role==="system")return C;let ue=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),xe=HH(d,t.role);return h==="right"||h==="left"&&t.role==="user"?ue.append(C,xe):ue.append(xe,C),ue};var OH=40,DH=(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=He(e.name,OH);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(q("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(q("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},EA=(t,e,n={})=>{let o=q("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=q("div",{className:"persona-welcome-head-text"},r,s),d=q("div",{className:"persona-welcome-title-row"},o,l);return{host:q("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow: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}},xa=(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)},vu=(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==="",DH(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")},_H="data-persona-welcome-plugin",kA="data-persona-welcome-overlay",bu="persona-welcome-overlay-active",dh=new WeakMap,ph=(t,e,n)=>{n.setAttribute(_H,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(kA,""),t.classList.contains(bu)||(dh.set(t,t.scrollTop),t.classList.add(bu),t.scrollTop=0)},uh=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(kA),t.classList.contains(bu)&&(t.classList.remove(bu),t.scrollTop=dh.get(t)??t.scrollTop,dh.delete(t))},LA=()=>{let t=q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},Cu=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=q("div",{className:uc("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(q("div",{className:"persona-flex"},r)),t.hidden=!1},PA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,IA=(t,e)=>{if(PA()||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,E=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-E),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},HA=(t,e,n)=>{if(e<=1||PA()||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 NH="Hello \u{1F44B}",FH="I can answer questions and help you get things done here.",RA=new WeakSet,qn=(t,e)=>!!t&&t[e]!==void 0,$H=(t,e)=>{!t||t.debug!==!0||!e.length||RA.has(t)||(RA.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Hr=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=Yl(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".'),$H(t,s),{title:qn(e,"title")?e.title:n?.welcomeTitle??NH,kicker:e?.kicker??"",subtitle:qn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??FH,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()||tu}},WA=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Sa=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var BA="16px",fh="10px",gh="14px",OA=t=>{let e=t?.launcher?.enabled??!0,n=an(t);if(ic(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??In);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??In),{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&&uo[r.position]?uo[r.position]:uo["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??In);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=t?.launcher?.width??t?.launcherWidth??Pr;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},hh=t=>{let e=q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":th(t)}});return e.hidden=!0,e},DA=(t,e)=>{let n=hh("starter"),o=EA(t,n,{flatShadow:an(t)}),r=Hr(t);vu(o,r),xa(e,o.host,Sa(r,t?.initialMessages));let s=LA();return Cu(s,r.message,t),{welcome:o,greetingHost:s}},VH=(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}=Ca(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:BA,iconSize:fh});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 B=wa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:BA,iconSize:gh});a=B.button,l=B.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=DA(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"),I=hh("followUp"),E=gs(t,!0);E&&(S.style.maxWidth=E,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),p.append(h,m,S,I);let O=q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),M=hu({config:t}),{root:D,textNode:L}=CA();return n.append(d,r,p,O),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:S,starterSuggestions:C,transcriptSuggestions:I,composerOverlay:O,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.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:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode,peekBanner:D,peekTextNode:L}},_A=(t,e=!0)=>{if(ic(t))return VH(t,e);let n=q("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?fu(t,o,{showClose:e}):ii({config:t,showClose:e}),a=q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=DA(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=hh("followUp"),C=gs(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=dc({config:t}),I=t?.layout?.showFooter!==!1;r?lc(n,s,t):(s.header.style.display="none",lc(n,s,t)),n.append(a);let E=q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return I||(S.footer.style.display="none"),n.append(S.footer),n.append(E),{container:n,body:a,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:b,composerOverlay:E,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}};Ue();Jt();us();var yh=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
|
|
1158
|
+
`)[0]).startsWith(D.trigger):!1),s=(M,D)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${M}`,{detail:D}))}catch{}},a=!t.chipRow,l=t.chipRow??q("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 M=Wg().then(D=>(D.setMentionIconRenderer(He),d=D.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:O,emit:s}),d)).catch(D=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",D),p===M&&(p=null),null));return p=M,M},S=()=>{ES().then(M=>{let D=M.mountInlineComposer({textarea:t.textarea,renderToken:B=>Gl(B,{render:e.renderMentionToken}),onMentionRemoved:B=>d?.untrackMention(B)});m=D.input,h=D.destroy;let L=u;L.replaceWith(D.element),u=D.element,b={next:D.element,prev:L},g?.(D.element,L),d?d.rebindComposer(D.input):p&&p.then(B=>B?.rebindComposer(D.input))}).catch(M=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",M)})};e.display==="inline"&&S();let I=[],E=new Map;for(let M of n){if(!M.showButton)continue;let D=Qx({config:{...e,buttonIconName:M.buttonIconName,buttonTooltipText:M.buttonTooltipText},onOpen:()=>{C().then(L=>L?.openMenu(M.trigger))}});I.push(D),E.set(M.trigger,D.button)}let O=(M,D,L)=>{let B=E.get(D);B&&(B.setAttribute("aria-expanded",M?"true":"false"),M?B.setAttribute("aria-controls",L):B.removeAttribute("aria-controls"))};return{affordanceButtons:I.map(M=>M.wrapper),contextRow:l,handleInput:M=>{if(d){d.handleInput();return}if(!Gx(M))return;let D=u,L=D.selectionStart??0;zl(D.value,L,n)&&C().then(B=>B?.handleInput())},handleKeydown:M=>{if(d?.isMenuOpen())return d.handleKeydown(M);if(M.key==="Backspace"&&d?.hasMentions()&&!b){let D=u,L=D.selectionStart===0&&D.selectionEnd===0;if((D.value.length===0||L)&&d.removeLastChip())return M.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async M=>r(M)?(d??await C())?.dispatchInlineCommand(M)??null:null,clear:()=>d?.clear(),prefetch:()=>{Wg().catch(()=>{})},onComposerSwap:M=>{g=M,b&&M(b.next,b.prev)},destroy:()=>{d?.destroy(),h?.();for(let M of I)M.wrapper.remove();a&&l.remove()}}}var eu="16px",tu="transparent",CI=(()=>{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})(),wI={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:CI,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"}},xI={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"}},SI={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:Ir,maxWidth:cx,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:eu,canvasBackground:tu},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 PS(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 AI(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 IS(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]=IS(s,r):n[o]=r}return n}function MI(t,e){return e?IS(t,e):t}function ba(t,e={}){let n={palette:wI,semantic:xI,components:SI},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:MI(n.components,t?.components)};if(e.validate!==!1){let r=AI(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 zg=t=>t.trim()==="0"?"0px":t,LS="--persona-",TI=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},EI=.179,kn=(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[LS+s],r!==void 0)break;r!==void 0&&(t[LS+n]=r)}};function HS(t){let e=PS(t),n={};for(let[F,Ce]of Object.entries(e)){let Ee=F.replace(/\./g,"-");n[`--persona-${Ee}`]=Ce.value}kn(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"],kn(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"]]),kn(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"]}`,kn(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"]??eu,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??tu,kn(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"]]),kn(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"],kn(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"],kn(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[F,Ce]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ee=n[`--persona-components-history-overlay-${F}`];Ee&&(n[`--persona-history-overlay-${Ce}`]=Ee)}for(let[F,Ce]of[["background","bg"],["borderRadius","radius"]]){let Ee=n[`--persona-components-history-menu-${F}`];Ee&&(n[`--persona-history-menu-${Ce}`]=Ee)}let m=t.components?.history?.motion;if(m){let F=Ve=>{if(Ve===void 0)return;let ke=String(Ve).trim();return/^\d+(\.\d+)?$/.test(ke)?`${ke}ms`:ke},Ce=F(m.enterDurationMs);Ce!==void 0&&(n["--persona-history-enter-ms"]=Ce);let Ee=F(m.exitDurationMs);Ee!==void 0&&(n["--persona-history-exit-ms"]=Ee),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 F of["scrim","shadow"]){let Ce=n[`--persona-components-history-confirm-${F}`];Ce&&(n[`--persona-history-confirm-${F}`]=Ce)}for(let[F,Ce]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ee=n[`--persona-components-tooltip-${F}`];Ee&&(n[`--persona-tooltip-${Ce}`]=Ee)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[F,Ce]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ee=n[`--persona-components-messageActions-${F}`];Ee&&(n[`--persona-message-action-${Ce}`]=Ee)}kn(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,kn(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"]]),kn(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 I=n["--persona-components-markdown-heading-h1-fontSize"];I&&(n["--persona-md-h1-size"]=I);let E=n["--persona-components-markdown-heading-h1-fontWeight"];E&&(n["--persona-md-h1-weight"]=E);let O=n["--persona-components-markdown-heading-h2-fontSize"];O&&(n["--persona-md-h2-size"]=O);let M=n["--persona-components-markdown-heading-h2-fontWeight"];M&&(n["--persona-md-h2-weight"]=M);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),kn(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"]]),kn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),kn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),kn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),kn(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"],kn(n,[["message-border","components-message-border","border"]]),kn(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 L=t.components,B=L?.iconButton;B&&(B.background&&(n["--persona-icon-btn-bg"]=B.background),B.border&&(n["--persona-icon-btn-border"]=B.border),B.color&&(n["--persona-icon-btn-color"]=B.color),B.padding&&(n["--persona-icon-btn-padding"]=B.padding),B.borderRadius&&(n["--persona-icon-btn-radius"]=B.borderRadius),B.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=B.hoverBackground),B.hoverColor&&(n["--persona-icon-btn-hover-color"]=B.hoverColor),B.activeBackground&&(n["--persona-icon-btn-active-bg"]=B.activeBackground),B.activeBorder&&(n["--persona-icon-btn-active-border"]=B.activeBorder));let W=L?.labelButton;W&&(W.background&&(n["--persona-label-btn-bg"]=W.background),W.border&&(n["--persona-label-btn-border"]=W.border),W.color&&(n["--persona-label-btn-color"]=W.color),W.padding&&(n["--persona-label-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-label-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-label-btn-hover-bg"]=W.hoverBackground),W.fontSize&&(n["--persona-label-btn-font-size"]=W.fontSize),W.gap&&(n["--persona-label-btn-gap"]=W.gap));let z=L?.toggleGroup;z&&(z.gap&&(n["--persona-toggle-group-gap"]=z.gap),z.borderRadius&&(n["--persona-toggle-group-radius"]=z.borderRadius));let H=L?.artifact;if(H?.toolbar){let F=H.toolbar;F.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=F.iconHoverColor),F.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=F.iconHoverBackground),F.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=F.iconPadding),F.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=F.iconBorderRadius),F.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=F.iconBorder),F.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=zg(F.toggleGroupGap)),F.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=F.toggleBorderRadius),F.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=zg(F.toggleGroupPadding)),F.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=F.toggleGroupBorder),F.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=F.toggleGroupBorderRadius),F.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=zn(t,F.toggleGroupBackground)??F.toggleGroupBackground),F.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=F.copyBackground),F.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=F.copyBorder),F.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=F.copyColor),F.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=zg(F.copyBorderRadius)),F.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=F.copyPadding),F.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=F.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??F.copyMenuBackground),F.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=F.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??F.copyMenuBorder),F.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=F.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??F.copyMenuShadow),F.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=F.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??F.copyMenuBorderRadius),F.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=F.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??F.copyMenuItemHoverBackground),F.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=F.iconBackground),F.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=F.toolbarBorder)}if(H?.tab){let F=H.tab;F.background&&(n["--persona-artifact-tab-bg"]=F.background),F.activeBackground&&(n["--persona-artifact-tab-active-bg"]=F.activeBackground),F.activeBorder&&(n["--persona-artifact-tab-active-border"]=F.activeBorder),F.borderRadius&&(n["--persona-artifact-tab-radius"]=F.borderRadius),F.textColor&&(n["--persona-artifact-tab-color"]=F.textColor),F.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=F.hoverBackground),F.listBackground&&(n["--persona-artifact-tab-list-bg"]=F.listBackground),F.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=F.listBorderColor),F.listPadding&&(n["--persona-artifact-tab-list-padding"]=F.listPadding)}if(H?.pane){let F=H.pane;if(F.toolbarBackground){let Ce=zn(t,F.toolbarBackground)??F.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ce}}if(H?.card){let F=H.card;F.background&&(n["--persona-artifact-card-bg"]=F.background),F.border&&(n["--persona-artifact-card-border"]=F.border),F.borderRadius&&(n["--persona-artifact-card-radius"]=F.borderRadius),F.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=F.hoverBackground),F.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=F.hoverBorderColor)}if(H?.inline){let F=H.inline;F.background&&(n["--persona-artifact-inline-bg"]=zn(t,F.background)??F.background),F.border&&(n["--persona-artifact-inline-border"]=F.border),F.borderRadius&&(n["--persona-artifact-inline-radius"]=F.borderRadius),F.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=zn(t,F.chromeBackground)??F.chromeBackground),F.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=zn(t,F.chromeBorder)??F.chromeBorder),F.titleColor&&(n["--persona-artifact-inline-title-color"]=zn(t,F.titleColor)??F.titleColor),F.mutedColor&&(n["--persona-artifact-inline-muted-color"]=zn(t,F.mutedColor)??F.mutedColor),F.frameHeight&&(n["--persona-artifact-inline-frame-height"]=F.frameHeight)}let w=L?.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 k=n["--persona-surface"],R=n["--persona-container"],_=n["--persona-palette-colors-gray-100"]??"#f3f4f6",X=n["--persona-palette-colors-gray-200"]??"#e5e7eb",j=n["--persona-palette-colors-gray-300"]??"#d1d5db",Q=!R||R===k,Z=TI(k??n["--persona-background"]),ie=Q&&Z!==void 0&&Z<EI,se=ie?"rgba(255, 255, 255, 0.08)":_,pe=ie?"rgba(255, 255, 255, 0.12)":X,ue=ie?"rgba(255, 255, 255, 0.16)":j,xe=Q?se:R,be=Q?pe:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??xe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??be,Q&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ue),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??xe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??xe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??xe,n}var kI={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"}}},LI={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)"}}}},RS=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},qg=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",PI=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":qg()},WS=t=>PI(t),II=t=>ba(t),HI=t=>{let e=fa(LI,t??{})??{};return ba({...e,palette:{...e.palette,colors:{...kI.colors,...e.palette?.colors}}},{validate:!1})},va=t=>{let e=WS(t),n=RS(t?.theme),o=RS(t?.darkTheme);return e==="dark"?HI(fa(n??{},o??{})):II(n)},RI=t=>HS(t),Yl=(t,e)=>{let n=va(e),o=RI(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",WS(e))},nu=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(qg())});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(qg());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 Dr=require("lucide");en();to();qe();var gs=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var ou="24px",Ug=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",Ql=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},BS=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var OS=null;var jg=()=>{if(OS!==null)return OS;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},WI="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",ru=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},su=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 ru("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(ru("unsupported",t),null):(n==="space"&&(o.key=" "),o)},BI=t=>WI.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),DS=(t,e)=>{let n=su(t);if(!n)return"";let o=jg(),r=BI(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("+")},iu=t=>DS(t,!1),Xl=t=>DS(t,!0),OI=(t,e)=>e.key?.toLowerCase()===t.key&&(jg()?e.metaKey:e.ctrlKey)===t.mod&&!(jg()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,DI=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},_S=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(OI(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&DI(a))){s.preventDefault();try{l.run(s)}catch(d){ru(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=su(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=e.get(l);return d?(ru(`${d.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",Xl(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};var NS=require("idiomorph"),au=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;NS.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 FS=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Kg={index:-1,draft:""};function $S(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 VS(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 zS(){return new Map}function qS(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function US(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function jS(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}Yg();us();oc();eo();var{setLoader:QN,load:lH}=zt({fallbackImport:()=>Promise.resolve().then(()=>(gA(),fA))});var hA=lH;us();function th(t,e=Rn){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 sc=0,hs=null;function nh(t=document){if(sc++,sc===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;hs={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,sc=Math.max(0,sc-1),sc===0&&hs)){let n=t.body,o=t.defaultView??window;n.style.overflow=hs.originalOverflow,n.style.position=hs.originalPosition,n.style.top=hs.originalTop,n.style.width=hs.originalWidth,o.scrollTo(0,hs.scrollY),hs=null}}}var ic={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},cn=t=>(t?.launcher?.mountMode??"floating")==="docked",ac=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",ko=t=>{let e=t?.launcher?.dock;return{side:e?.side??ic.side,width:e?.width??ic.width,animate:e?.animate??ic.animate,reveal:e?.reveal??ic.reveal,maxHeight:e?.maxHeight??ic.maxHeight}};qe();qe();var bA=require("lucide");en();to();var oh=t=>t==="followUp"?"follow-up":t,rh=(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"}},cH=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'}},yA=new WeakSet,dH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,pH=t=>{dH()||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"})})},sh=t=>{var O,M,D;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 L={suggestion:{...e},surface:o,source:r,behavior:C},B=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:L,bubbles:!0,composed:!0,cancelable:!0}));if(b&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!B)return;for(let z of d)if(z.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let W=m();if(C==="fill"){W.value=e.prompt,W.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),W.focus();return}if(g){g(e.prompt);return}W.value="",u.sendMessage(e.prompt)},I=()=>{let L=v("button",`persona-suggestion persona-suggestion--${s}`);if(L.type="button",L.disabled=a,L.dataset.suggestionId=e.id,L.dataset.emphasis=e.emphasis,L.dataset.behavior=C,s==="chip"&&(p?.fontFamily&&(L.style.fontFamily=cH(p.fontFamily)),p?.fontWeight&&(L.style.fontWeight=p.fontWeight),p?.paddingX&&(L.style.paddingLeft=p.paddingX,L.style.paddingRight=p.paddingX),p?.paddingY&&(L.style.paddingTop=p.paddingY,L.style.paddingBottom=p.paddingY)),e.icon){let W=He(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);W&&(W.classList.add("persona-suggestion__icon"),e.iconColor&&(W.style.color=e.iconColor),L.appendChild(W))}let B=v("span","persona-suggestion__copy");if(B.appendChild(q("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&B.appendChild(q("span",{className:"persona-suggestion__description",text:e.description})),L.appendChild(B),s!=="chip"){let W=Ke(bA.ArrowRight,16,"currentColor",1.8);W&&(W.classList.add("persona-suggestion__arrow"),L.appendChild(W))}return L.addEventListener("click",S),L},E=null;for(let L of d)if(L.renderSuggestion&&(E=L.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:I,select:S}),E))break;return E??(E=I()),(O=E.dataset).suggestionId||(O.suggestionId=e.id),(M=E.dataset).behavior||(M.behavior=C),(D=E.dataset).emphasis||(D.emphasis=e.emphasis),E instanceof HTMLButtonElement||E.setAttribute("aria-disabled",a?"true":"false"),E},lc=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,I=m?!b:!C;t.toggleAttribute("data-scroll-left",S),t.toggleAttribute("data-scroll-right",I)},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",I=C?.surface??(S==="config"?"starter":"followUp"),E=I==="followUp",O=C?.variant??"chip",M=C?.behavior??"send",D=C?.overflow??"wrap",L=C?.config??{},B=C?.plugins??[],W=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,z=E?"followUps":"starters";!yA.has(L)&&L.debug===!0&&O!=="chip"&&L.suggestions?.[z]?.overflow!==void 0&&(yA.add(L),console.info(`[persona] suggestions.${z}.overflow applies to the "chip" variant only; the "${O}" variant manages its own stacking.`));let H=j=>j.map(rh).filter(Q=>Q!==null).map(Q=>({...Q,behavior:Q.behavior??M})),w=H(u??[]);B.forEach(j=>{j.transformSuggestions&&(w=H(j.transformSuggestions({suggestions:w.map(Q=>({...Q})),surface:I,source:S,config:L})))});let k=W===void 0?w:w.slice(0,W);if(!k.length){t.hidden=!0,o=null,s();return}if(!E&&(g??m.getMessages()).some(Q=>Q.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=oh(I),t.dataset.variant=O,t.dataset.overflow=D;let R=document.createDocumentFragment(),_=m.isStreaming();k.forEach((j,Q)=>{let Z=sh({item:j,index:Q,surface:I,source:S,variant:O,streaming:_,config:L,plugins:B,chipsConfig:b,session:m,getTextarea:()=>h,eventTarget:t,submitPrompt:C?.submitPrompt});R.appendChild(Z),n.push(Z),[...Z instanceof HTMLButtonElement?[Z]:[],...Array.from(Z.querySelectorAll("button"))].forEach(se=>{e.includes(se)||(se.disabled=_,e.push(se))})}),t.appendChild(R),a(),l();let X=JSON.stringify({normalized:k,surface:I,variant:O,source:S});X!==o&&(o=X,pH(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:k.map(j=>({...j})),surface:I,source:S,variant:O},bubbles:!0,composed:!0})),E&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:k.map(j=>j.prompt)},bubbles:!0,composed:!0})))}}};var mo={"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"};us();qe();en();qe();en();var uH="persona-header-control",mH="persona-header-control--glyph",fH="persona-header-control--sparse",gH=20,hH={x:[1.4,1.05]},vA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",yH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",fu=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=hH[e]??[1,1.5],l=!o;t.classList.toggle(mH,l),t.classList.toggle(fH,l&&s!==1);let d=parseFloat(o??"")||gH,p=He(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)},si=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=vA,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:h,borderRadius:g,paddingX:b,paddingY:C,hidden:S,extraClassName:I,attrs:E}=t,O=v("div",a),M=!!(m||h),D=q("button",{className:Dt(uH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!M&&"persona-border-none",!g&&"persona-rounded-full",I),attrs:{type:"button","aria-label":e,...E},style:{width:l,height:l,minWidth:l,minHeight:l,display:S?"none":void 0,color:p||qn.actionIconColor,backgroundColor:u,border:M?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:g,paddingLeft:b,paddingRight:b,paddingTop:C,paddingBottom:C}});return r?fu(D,r,{iconSize:d,iconText:s}):s&&(D.textContent=s),O.appendChild(D),En({anchor:D,trigger:O,text:()=>D.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:D,wrapper:O}},wa=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=vA,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=si({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}},xa=(t,e={})=>{let{wrapperClassName:n=yH,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=si({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 qn={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)"},ih={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)"},bH={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)"},ii=t=>{let{config:e,showClose:n=!0}=t,o=q("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:qn.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=q("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 D=parseFloat(s)||24,L=He(d,D*.6,"currentColor",1);L?p.replaceChildren(L):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let D=v("img");D.src=e.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,p.replaceChildren(D)}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=q("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:qn.titleColor,...ih}}),h=q("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:qn.subtitleColor,...bH}});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,I=null;if(b){let L=xa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=L.button,I=L.wrapper,C==="top-right"&&(I.style.right="48px"),C==="inline"&&o.appendChild(I)}let E=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:O,wrapper:M}=wa(e,{showClose:n,wrapperClassName:E});return a!=="top-right"&&o.appendChild(M),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:h,closeButton:O,closeButtonWrapper:M,clearChatButton:S,clearChatButtonWrapper:I}},cc=(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))};qe();ah();li();var vH=t=>{let e=ii({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 CH(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=si({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?iu(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=Xl(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=dc({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 wH=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=qn.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 M=wA({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:D=>{let L=W=>{W===!1&&M.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},B=d.onSelect(D);B instanceof Promise?B.then(L,()=>{}):L(B)},hover:d.hover,className:""});p=M.element,p.style.color=qn.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=qn.titleColor,Object.assign(u.style,ih),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let D=r.onTitleClick;p.addEventListener("click",L=>{L.target.closest("button")||D()}),p.addEventListener("keydown",L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),D())})}let M=r?.titleRowHover;M&&(p.style.borderRadius=M.borderRadius??"10px",p.style.padding=M.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=M.background??"",p.style.borderColor=M.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}=wa(e,{showClose:n,wrapperClassName:m});o&&h.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");d||CH(b,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},S=null,I=null;if(C.enabled??!0){let M=C.placement??"inline",D=xa(e,{wrapperClassName:M==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});S=D.button,I=D.wrapper,M==="top-right"?I.style.right="48px":b.appendChild(I)}b.appendChild(g),l.appendChild(b);let E=v("div");E.style.display="none";let O=v("span");return O.style.display="none",{header:l,iconHolder:E,headerTitle:u,headerSubtitle:O,closeButton:h,closeButtonWrapper:g,clearChatButton:S,clearChatButtonWrapper:I}},xA={default:vH,minimal:wH},xH=t=>xA[t]??xA.default,hu=(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=xH(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};qe();var pc=t=>{let{config:e}=t,n=q("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Rp(),r=q("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Lp(e);a();let l=Pp(e),d=ga(e),p=Ip(e),u=Hp(e),m=q("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=q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),b=q("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}};qe();var yu=require("lucide");to();var SA=()=>{let t=q("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=Ke(yu.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=Ke(yu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},bu=t=>{let{config:e}=t,n=q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Rp(),r=Hp(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Lp(e,{defaultMaxLines:5});a();let l=Pp(e),d=ga(e),p=Ip(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let h=q("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=q("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}};qe();en();qe();li();en();oc();var SH=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}},AH=(t,e)=>{if(!t)return null;let n=SH(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},MH=(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},TH=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ch=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(":"))},dh=320,kA=320,EH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),kH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),LH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),PH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),IH=t=>{if(!t||t.length===0)return null;let e=q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=He(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(q("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},HH=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Gl(o.ref,{readonly:!0,render:e}))}return n},AA="\uE000",MA="\uE001",RH=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=h=>`${AA}${r}:${h}${MA}`,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(HH(e,o));return}t.innerHTML=l;let p=new RegExp(`${AA}${r}:(\\d+)${MA}`),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(Gl(C.ref,{readonly:!0,render:o}),S),g=S}}},WH=(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=`${dh}px`,p.style.maxHeight=`${kA}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}),TH(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}},BH=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(!ch(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=`${dh}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},OH=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(!ch(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=`${dh}px`,r.style.maxHeight=`${kA}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}},DH=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(!ch(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}},uc=()=>{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},_H=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:uc};if(e){let r=e(o);if(r!==null)return r}return uc()},NH=(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},TA=(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},mc=(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},EA={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"}},FH=(t,e,n="bubble",o)=>{if(!o)return;let r=e==="user"?"user":"assistant",s=EA[n??"bubble"]??EA.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)`)},vu="custom:",$H=t=>`${vu}${t}`,LA=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),VH=(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=LA(e,t.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let O=v("div");return O.style.display="none",O.id=`actions-${t.id}`,O.setAttribute("data-actions-for",t.id),O}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],I=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${S} ${h==="hover"?"persona-message-actions-hover":""}`);I.id=`actions-${t.id}`,I.setAttribute("data-actions-for",t.id);let E=(O,M,D)=>{let L=yn({icon:O,label:M,size:14,className:"persona-message-action-btn",chromeless:!0});return L.setAttribute("data-action",D),L};r&&I.appendChild(E("copy","Copy message","copy")),l&&I.appendChild(E("volume-2","Read aloud","read-aloud")),s&&I.appendChild(E("thumbs-up","Upvote","upvote")),a&&I.appendChild(E("thumbs-down","Downvote","downvote")),d&&I.appendChild(E("refresh-cw","Regenerate response","regenerate")),p&&I.appendChild(E("pencil","Edit message","edit")),u&&I.appendChild(E("quote","Quote message","quote"));for(let O of m)I.appendChild(E(O.iconName??"ellipsis",O.label,$H(O.id)));return I},ph=(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=mc(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;FH(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 I=EH(t),E=t.content?.trim()??"",M=I.length>0&&E===ca,D=pu(s?.widgetConfig?.features?.streamAnimation),L=s?.widgetConfig?.features?.streamAnimation?.plugins,B=t.role==="assistant"&&D.type!=="none"?Zl(D.type,L):null,W=t.role==="assistant"&&B?.isAnimating?.(t)===!0,z=t.role==="assistant"&&B!==null&&(!!t.streaming||W);z&&B?.bubbleClass&&C.classList.add(B.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),t.streaming&&H.classList.add("persona-content-streaming"),z&&B&&(B.containerClass&&H.classList.add(B.containerClass),H.style.setProperty("--persona-stream-step",`${D.speed}ms`),H.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let w=z?uu(t.content??"",D.buffer,B,t,!!t.streaming):t.content??"",k=()=>{let be=e({text:w,message:t,streaming:!!t.streaming,raw:t.rawContent});return z&&B?.wrap==="char"?ec(be,"char",t.id,{skipTags:B.skipTags}):z&&B?.wrap==="word"?ec(be,"word",t.id,{skipTags:B.skipTags}):be},R=null;if(M?(R=document.createElement("div"),R.innerHTML=k(),R.style.display="none",H.appendChild(R)):t.contentSegments?.length?RH(H,t.contentSegments,be=>e({text:be,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):H.innerHTML=k(),z&&B?.useCaret&&!M&&E){let be=mu(),F=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=F[F.length-1];if(Ce?.parentNode)Ce.parentNode.insertBefore(be,Ce.nextSibling);else{let Ee=H.lastElementChild;Ee?Ee.appendChild(be):H.appendChild(be)}}if(m&&g==="inline"&&t.createdAt){let be=TA(t,p,"span");be.classList.add("persona-timestamp-inline");let F=H.lastElementChild;F?F.appendChild(be):H.appendChild(be)}if(I.length>0){let be=WH(I,!M&&!!E,()=>{M&&R&&(R.style.display="")});be?C.appendChild(be):M&&R&&(R.style.display="")}let _=kH(t);if(_.length>0){let be=BH(_);be&&C.appendChild(be)}let X=LH(t);if(X.length>0){let be=OH(X);be&&C.appendChild(be)}let j=PH(t);if(j.length>0){let be=DH(j);be&&C.appendChild(be)}let Q=t.contentSegments?.length?null:IH(t.contextMentions);if(Q&&C.appendChild(Q),C.appendChild(H),m&&g==="below"&&t.createdAt){let be=TA(t,p);be.classList.add("persona-mt-1"),C.appendChild(be)}let Z=t.role==="assistant"?AH(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let be=!!(w&&w.trim()),F=D.placeholder==="skeleton",Ce=F&&D.buffer==="line"&&be;if(be)Ce&&C.appendChild(tc());else if(F)C.appendChild(tc());else{let Ee=_H("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Ee&&C.appendChild(Ee)}}Z&&t.stopReason&&!t.streaming&&(E||(H.style.display="none"),C.appendChild(MH(t.stopReason,Z)));let ie=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,se=s?.actionEligibility,pe=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&se?.canEdit===!0||o?.showQuote===!0&&se?.canQuote===!0||LA(o,"user").length>0);if((ie||pe)&&o){let be=VH(t,pe?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,se);C.appendChild(be)}if(!u||t.role==="system")return C;let ue=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),xe=NH(d,t.role);return h==="right"||h==="left"&&t.role==="user"?ue.append(C,xe):ue.append(xe,C),ue};var zH=40,qH=(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=He(e.name,zH);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(q("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(q("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},PA=(t,e,n={})=>{let o=q("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=q("div",{className:"persona-welcome-head-text"},r,s),d=q("div",{className:"persona-welcome-title-row"},o,l);return{host:q("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow: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}},Sa=(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)},wu=(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==="",qH(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")},UH="data-persona-welcome-plugin",IA="data-persona-welcome-overlay",Cu="persona-welcome-overlay-active",uh=new WeakMap,mh=(t,e,n)=>{n.setAttribute(UH,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(IA,""),t.classList.contains(Cu)||(uh.set(t,t.scrollTop),t.classList.add(Cu),t.scrollTop=0)},fh=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(IA),t.classList.contains(Cu)&&(t.classList.remove(Cu),t.scrollTop=uh.get(t)??t.scrollTop,uh.delete(t))},HA=()=>{let t=q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},xu=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=q("div",{className:mc("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(q("div",{className:"persona-flex"},r)),t.hidden=!1},RA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,WA=(t,e)=>{if(RA()||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,E=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-E),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},BA=(t,e,n)=>{if(e<=1||RA()||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 jH="Hello \u{1F44B}",KH="I can answer questions and help you get things done here.",OA=new WeakSet,Un=(t,e)=>!!t&&t[e]!==void 0,GH=(t,e)=>{!t||t.debug!==!0||!e.length||OA.has(t)||(OA.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Rr=t=>{let e=t?.welcome,n=t?.copy,o=Un(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Un(e,"dismiss")?e.dismiss:"never",s=[];Un(e,"title")&&Un(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Un(e,"subtitle")&&Un(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Un(e,"variant")&&Un(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Un(e,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Un(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=Ql(e?.anchorComposerTop)!==null;return Un(e,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(Un(e,"anchorComposerTop")||Un(e,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),GH(t,s),{title:Un(e,"title")?e.title:n?.welcomeTitle??jH,kicker:e?.kicker??"",subtitle:Un(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??KH,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()||ou}},DA=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Aa=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var _A="16px",hh="10px",yh="14px",NA=t=>{let e=t?.launcher?.enabled??!0,n=cn(t);if(ac(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??Rn);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??Rn),{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&&mo[r.position]?mo[r.position]:mo["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??Rn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=t?.launcher?.width??t?.launcherWidth??Ir;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},bh=t=>{let e=q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":oh(t)}});return e.hidden=!0,e},FA=(t,e)=>{let n=bh("starter"),o=PA(t,n,{flatShadow:cn(t)}),r=Rr(t);wu(o,r),Sa(e,o.host,Aa(r,t?.initialMessages));let s=HA();return xu(s,r.message,t),{welcome:o,greetingHost:s}},YH=(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}=wa(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:_A,iconSize:hh});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 B=xa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:_A,iconSize:yh});a=B.button,l=B.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=FA(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"),I=bh("followUp"),E=gs(t,!0);E&&(S.style.maxWidth=E,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),p.append(h,m,S,I);let O=q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),M=bu({config:t}),{root:D,textNode:L}=SA();return n.append(d,r,p,O),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:S,starterSuggestions:C,transcriptSuggestions:I,composerOverlay:O,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.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:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode,peekBanner:D,peekTextNode:L}},$A=(t,e=!0)=>{if(ac(t))return YH(t,e);let n=q("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?hu(t,o,{showClose:e}):ii({config:t,showClose:e}),a=q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=FA(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=bh("followUp"),C=gs(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=pc({config:t}),I=t?.layout?.showFooter!==!1;r?cc(n,s,t):(s.header.style.display="none",cc(n,s,t)),n.append(a);let E=q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return I||(S.footer.style.display="none"),n.append(S.footer),n.append(E),{container:n,body:a,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:b,composerOverlay:E,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}};qe();en();us();var vh=(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">
|
|
@@ -1163,14 +1163,14 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1163
1163
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
1164
1164
|
</span>
|
|
1165
1165
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
1166
|
-
`,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=an(s),d=n.querySelector("[data-role='launcher-title']");if(d){let O=a.title??"Chat Assistant";d.textContent=O,d.setAttribute("title",O)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let O=a.subtitle??"Here to help you get answers fast";p.textContent=O,p.setAttribute("title",O)}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 O=a.agentIconSize??"40px";if(m.style.height=O,m.style.width=O,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 M=parseFloat(O)||24,D=He(a.agentIconName,M*.6,"var(--persona-text-inverse, #ffffff)",1.5);D?(m.appendChild(D),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 O=a.agentIconSize??"40px";h.style.height=O,h.style.width=O,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 O=a.callToActionIconSize??"32px";g.style.height=O,g.style.width=O,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 M=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,M=(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 D=parseFloat(O)||24,L=Math.max(D-M,8),B=He(a.callToActionIconName,L,"currentColor",1.5);B?g.appendChild(B):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&uo[a.position]?uo[a.position]:uo["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??In));let I="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",E="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??I,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,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",FA=new Set,NA=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${zH}`},qH=(t,e)=>{if(FA.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},UH=(t,e)=>{if(FA.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},jH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,KH=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||an(t??{})?null:e},$A=(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=X=>{b(),m=!0,C(),UH(NA(o),X&&g())},I=X=>{!r||m||S(X==="user"&&p)},E=()=>{d=null,!(!s||m||h)&&(u=!0,p=!0,s.hidden=!1,!(jH()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},O=()=>{!r||!s||m||u||h||qH(NA(o),g())||(b(),d=setTimeout(E,Math.max(0,r.delayMs??0)))},M=()=>{S(g()),e()},D=X=>{X.stopPropagation(),S(g())},B=yh(t,()=>{I("user"),e()}),W=()=>{b(),l?.removeEventListener("click",M),a?.removeEventListener("click",D),s?.remove(),s=null,l=null,a=null,p=!1},z=()=>{l=q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",M),a=q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",D),s=q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,B.element)},H=()=>{let X=o.launcher?.position??"bottom-right",j=uo[X]??uo["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",B.element.style.position="";return}n.className=Bt("persona-launcher-surface",j),n.setAttribute("data-teaser",X),n.style.zIndex=String(o.launcher?.zIndex??In),B.element.style.position="static"},w=X=>{let j=KH(X);if(r=j,!j){W();return}s||z(),l.textContent=j.text,a.hidden=j.dismissible===!1,a.setAttribute("aria-label",j.dismissLabel??"Dismiss message"),O()},k=X=>{o=X,B.update(X),w(X),H()},R=(X,j="user")=>{h=X,X&&I(j)},_=()=>{W(),B.destroy(),n.remove()};return n.appendChild(B.element),t&&(w(t),H()),{element:n,launcher:B,get teaser(){return s?{element:s,show:E,dismiss:S}:null},setPanelOpen:R,update:k,destroy:_}};var VA=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=OA(t),s=_A(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}}},bh=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>yh(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=$A(t,n);return{instance:r,element:r.element}};var GH=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},YH=(t,e,n)=>`${GH(t)}plugin:${e}:${n}`,zA=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=>YH(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}}}}};Ue();Jt();oi();wu();Ue();var xu=require("lucide");eo();var QH=["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"],XH="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",JH="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",ZH=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Su=(t,e)=>{let n=v("div",["persona-message-bubble",t,...QH].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},Au=t=>{let e=v("button",t.expandable?XH:JH);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},vh=(t,e,n)=>{t.innerHTML="";let o=Ke(e?xu.ChevronUp:xu.ChevronDown,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},Mu=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=v("div","persona-flex persona-items-center");vh(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},Tu=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?.();ZH(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},Eu=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&vh(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"},ku=(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&&vh(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var Aa=new Set,eR=(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
|
-
`):""},
|
|
1166
|
+
`,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=cn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let O=a.title??"Chat Assistant";d.textContent=O,d.setAttribute("title",O)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let O=a.subtitle??"Here to help you get answers fast";p.textContent=O,p.setAttribute("title",O)}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 O=a.agentIconSize??"40px";if(m.style.height=O,m.style.width=O,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 M=parseFloat(O)||24,D=He(a.agentIconName,M*.6,"var(--persona-text-inverse, #ffffff)",1.5);D?(m.appendChild(D),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 O=a.agentIconSize??"40px";h.style.height=O,h.style.width=O,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 O=a.callToActionIconSize??"32px";g.style.height=O,g.style.width=O,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 M=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,M=(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 D=parseFloat(O)||24,L=Math.max(D-M,8),B=He(a.callToActionIconName,L,"currentColor",1.5);B?g.appendChild(B):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&mo[a.position]?mo[a.position]:mo["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??Rn));let I="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",E="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??I,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,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}},QH="teaser-dismissed",zA=new Set,VA=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${QH}`},XH=(t,e)=>{if(zA.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},JH=(t,e)=>{if(zA.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},ZH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,eR=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||cn(t??{})?null:e},qA=(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=X=>{b(),m=!0,C(),JH(VA(o),X&&g())},I=X=>{!r||m||S(X==="user"&&p)},E=()=>{d=null,!(!s||m||h)&&(u=!0,p=!0,s.hidden=!1,!(ZH()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},O=()=>{!r||!s||m||u||h||XH(VA(o),g())||(b(),d=setTimeout(E,Math.max(0,r.delayMs??0)))},M=()=>{S(g()),e()},D=X=>{X.stopPropagation(),S(g())},B=vh(t,()=>{I("user"),e()}),W=()=>{b(),l?.removeEventListener("click",M),a?.removeEventListener("click",D),s?.remove(),s=null,l=null,a=null,p=!1},z=()=>{l=q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",M),a=q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",D),s=q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,B.element)},H=()=>{let X=o.launcher?.position??"bottom-right",j=mo[X]??mo["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",B.element.style.position="";return}n.className=Dt("persona-launcher-surface",j),n.setAttribute("data-teaser",X),n.style.zIndex=String(o.launcher?.zIndex??Rn),B.element.style.position="static"},w=X=>{let j=eR(X);if(r=j,!j){W();return}s||z(),l.textContent=j.text,a.hidden=j.dismissible===!1,a.setAttribute("aria-label",j.dismissLabel??"Dismiss message"),O()},k=X=>{o=X,B.update(X),w(X),H()},R=(X,j="user")=>{h=X,X&&I(j)},_=()=>{W(),B.destroy(),n.remove()};return n.appendChild(B.element),t&&(w(t),H()),{element:n,launcher:B,get teaser(){return s?{element:s,show:E,dismiss:S}:null},setPanelOpen:R,update:k,destroy:_}};var UA=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=NA(t),s=$A(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}}},Ch=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>vh(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=qA(t,n);return{instance:r,element:r.element}};var tR=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},nR=(t,e,n)=>`${tR(t)}plugin:${e}:${n}`,jA=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=>nR(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}}}}};qe();en();oi();Su();qe();var Au=require("lucide");to();var oR=["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"],rR="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",sR="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",iR=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Mu=(t,e)=>{let n=v("div",["persona-message-bubble",t,...oR].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},Tu=t=>{let e=v("button",t.expandable?rR:sR);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},wh=(t,e,n)=>{t.innerHTML="";let o=Ke(e?Au.ChevronUp:Au.ChevronDown,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},Eu=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=v("div","persona-flex persona-items-center");wh(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},ku=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?.();iR(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},Lu=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&wh(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"},Pu=(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&&wh(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var Ma=new Set,aR=(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
|
+
`):""},KA=(t,e)=>{Pu(t,e,{stateSet:Ma,previewKind:"reasoning",iconColor:"currentColor"})},xh=(t,e)=>{let n=t.reasoning,o=Mu("persona-reasoning-bubble",t.id);if(!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&Ma.has(t.id),l=n.status!=="complete",d=aR(t,r.previewMaxLines??3),p=Tu({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 _=v("span","");return _.setAttribute("data-tool-elapsed",b),_.textContent=ip(n),_},S=g.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:h,previewText:d,isActive:l,config:e??{},elapsed:ip(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 I=v("span","persona-text-xs persona-text-persona-primary");I.textContent=nw(n),u.appendChild(I);let E=r.loadingAnimation??"none",O=g.activeTextTemplate,M=g.completeTextTemplate,D=l?O:M,L=S instanceof HTMLElement,B=(_,X)=>{m.textContent="";let j=ap(_,""),Q=0;for(let Z of j){let ie=Z.styles.length>0?(()=>{let se=v("span",Z.styles.map(pe=>`persona-tool-text-${pe}`).join(" "));return m.appendChild(se),se})():m;if(Z.isDuration&&l)ie.appendChild(C());else{let se=Z.isDuration?ip(n):Z.text;X?Q=ys(ie,se,Q):ie.appendChild(document.createTextNode(se))}}};if(!L&&D)if(I.style.display="none",m.style.display="",l&&E!=="none"){let _=g.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),E==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),B(D,!1)):(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),E==="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)),B(D,!0))}else B(D,!1);else if(!L&&l&&E!=="none"){m.style.display="";let _=g.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`);else{m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${_}ms`),E==="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 X=m.textContent||h;m.textContent="",ys(m,X,0)}n.status==="complete"&&(m.style.display="none")}else L||(n.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!L){let _=v("span","persona-reasoning-header-icon"),X=He(r.iconName,16,"currentColor",2);X&&(_.appendChild(X),p.appendChild(_))}let W="currentColor",z=Eu(p,u,{expandable:s,expanded:a,iconColor:W,metaGap:!1}),H=ku({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 k=n.chunks.join(""),R=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return R.textContent=k||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),w.appendChild(R),Lu({expanded:a,header:p,toggleIcon:z,content:w,collapsedPreview:H,iconColor:W}),o.append(p,H,w),o};qe();oi();Su();var Ta=new Set,GA=t=>t.toggleTextColor||t.headerTextColor||"var(--persona-primary, #171717)",lR=(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=cs(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
1169
|
-
`):""},wh=(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)"},nR=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=tR(t,o?.previewMaxLines??3),a=n?tw(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=Uf(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=Uf(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:l}},jA=(t,e,n)=>{ku(t,e,{stateSet:Ma,previewKind:"tool",iconColor:UA(n?.toolCall??{})})},xh=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=Su("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&&Ma.has(t.id),{summary:d,previewText:p,isActive:u}=nR(t,e),m=Au({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=kl(n),w},S=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:e??{},elapsed:kl(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 I=s.loadingAnimation??"none",E=o.activeTextTemplate,O=o.completeTextTemplate,M=u?E:O,D=S instanceof HTMLElement,L=(w,k)=>{g.textContent="";let R=n.name?.trim()||"tool",_=sp(w,R),X=0;for(let j of _){let Q=j.styles.length>0?(()=>{let Z=v("span",j.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return g.appendChild(Z),Z})():g;if(j.isDuration&&u)Q.appendChild(C());else{let Z=j.isDuration?kl(n):j.text;k?X=ys(Q,Z,X):Q.appendChild(document.createTextNode(Z))}}};if(!D)if(u&&I!=="none"){let w=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),I==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),M&&L(M,!1);else if(g.classList.add(`persona-tool-loading-${I}`),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),I==="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)),M)L(M,!0);else{let k=g.textContent||d;g.textContent="",ys(g,k,0)}}else M&&L(M,!1);let B=UA(o),W=Mu(m,h,{expandable:a,expanded:l,iconColor:B,metaGap:!0}),z=Tu({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,z),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"),k=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(k.style.color=o.labelTextColor),k.textContent="Arguments";let R=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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",wh(R,o),R.textContent=cs(n.args),w.append(k,R),H.appendChild(w)}if(n.chunks&&n.chunks.length){let w=v("div","persona-space-y-1"),k=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(k.style.color=o.labelTextColor),k.textContent="Activity";let R=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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",wh(R,o),R.textContent=n.chunks.join(""),w.append(k,R),H.appendChild(w)}if(n.status==="complete"&&n.result!==void 0){let w=v("div","persona-space-y-1"),k=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(k.style.color=o.labelTextColor),k.textContent="Result";let R=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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",wh(R,o),R.textContent=cs(n.result),w.append(k,R),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 Eu({expanded:l,header:m,toggleIcon:W,content:H,collapsedPreview:z,iconColor:B}),r.append(m,z,H),r};oi();Zn();var{setLoader:i$,load:cR,provide:a$,getSync:dR}=Ft({fallbackImport:()=>Promise.resolve().then(()=>(tM(),eM))});var nM=cR;var oM=dR;ea();Zn();var{setLoader:S$,load:WR}=Ft({fallbackImport:()=>Promise.resolve().then(()=>(mM(),uM))});var Hh=WR;Zn();hc();ei();hp();var Uh=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:BV,load:hW,provide:OV,getSync:yW}=Ft({fallbackImport:()=>Promise.resolve().then(()=>($M(),FM))}),Pa=null,Fu=new Set,VM=t=>{if(Pa)return Pa;Pa=t,t.initArtifactsUi({componentRegistry:No});for(let o of Uh)No.has(o)||No.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=So();e?t.__provideMarkdownParsers(e):Ji(()=>{let o=So();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>gp());let n=[...Fu];Fu.clear();for(let o of n)try{o()}catch{}return t};var $u=()=>hW().then(VM);var Rr=()=>{if(Pa)return Pa;let t=yW();return t?VM(t):null},jh=t=>Pa?()=>{}:(Fu.add(t),()=>{Fu.delete(t)});function Un(t){return t?.features?.artifacts?.enabled===!0}function zM(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"),!Un(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 bW(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 qM=["panel","seamless","detached"];function Kh(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&qM.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Gh(t){return!t||!Un(t)?!1:Kh(t)==="detached"}function Sc(t,e){if(!Un(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"),bW(t),zM(t,e);return}let n=e.features?.artifacts?.layout,o=Kh(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)}zM(t,e)}function Ac(t,e){for(let l of qM)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"),!Un(e))return;let n=e.features?.artifacts?.layout,o=Kh(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 UM(t,e){return!e||!Un(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var vW=new Set(["__proto__","prototype","constructor"]),CW=new Set(["collapsed","card","panel","inline"]),jM=new Set(["markdown","component"]),wW=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,yi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),zu=t=>!vW.has(t),Yh=t=>typeof t=="string"&&CW.has(t),bi=t=>Object.keys(t).length>0;function lr(t,e,n,o){t.push({path:e,code:n,message:o})}var xW="Ignored because this key is not part of the persisted preference schema.",Vu="Ignored an unsupported value.",SW="Expected collapsed, panel, or inline.",AW='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',KM={kind:"mode",message:Vu},Ia={kind:"string",message:"Expected a CSS length string."},Wr={kind:"boolean"},MW={paneWidth:Ia,paneMaxWidth:Ia,paneMinWidth:Ia,expandedPanelWidth:Ia,resizableMinWidth:Ia,resizableMaxWidth:Ia,expandLauncherPanelWhenOpen:Wr,resizable:Wr},TW={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Wr,showReasoning:Wr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Vu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Vu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Vu},expandable:Wr,grouped:Wr}},reasoningDisplay:{kind:"object",children:{expandable:Wr,activePreview:Wr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:KM,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:KM,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:jM,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:jM}}},filePreview:{kind:"object",children:{enabled:Wr}},layout:{kind:"object",children:MW}}}}};function GM(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:lr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:lr(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:lr(o,n,"invalid_value",e.message);case"mode":return Yh(t)?Ao(t):lr(o,n,"invalid_value",e.message);case"modeMap":{if(!yi(t))return lr(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:ta(a);zu(a)&&(r?r.has(a):wW.test(d))?Yh(l)?s[d]=Ao(l):lr(o,`${n}.${a}`,"invalid_value",SW):lr(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":AW)}return bi(s)?s:void 0}case"object":{if(e.bareMode&&Yh(t))return Ao(t);if(!yi(t))return lr(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))(!zu(l)||!r.includes(l))&&lr(o,s(l),"unknown_key",xW);let a={};for(let l of r){let d=e.children[l],p=GM(t[l],d,s(l),o);if(d.deprecated&&t[l]!==void 0&&lr(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=yi(m)&&yi(p)?{...m,...p}:p}return bi(a)?a:void 0}}}function EW(t){let e=[];return{preferences:(t===null?void 0:GM(t,TW,"",e))??{},issues:e}}function Ha(t){if(Array.isArray(t))return t.map(Ha);if(!yi(t))return t;let e={};for(let[n,o]of Object.entries(t))zu(n)&&o!==void 0&&(e[n]=Ha(o));return e}function YM(t,e){let n=Ha(t);for(let[o,r]of Object.entries(e)){if(!zu(o)||r===void 0)continue;let s=n[o];n[o]=yi(s)&&yi(r)?YM(s,r):Ha(r)}return n}function kW(t){let e={},n;for(let r of t){let s=EW(r).preferences;n=QM(n,s.artifacts?.display),e=YM(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function LW(t,e){if(e===void 0)return t===void 0?void 0:Ha(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}:{},...bi(r)?{byMediaType:r}:{}};return bi(s)?s:void 0}function QM(t,e){if(e===void 0)return t===void 0?void 0:Ha(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=LW(n.files,e.files),a={...o?{default:o}:{},...bi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return bi(a)?a:void 0}function PW(t={},e){let n=kW(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=QM(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 Qh(t){let e=t.preferences;return!e||!bi(e)?t:{...t,features:PW(t.features??{},[e])}}function IW(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 HW(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 RW(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function WW(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Xh(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 XM(t,e,n,o,r,s,a=200){let l=IW(r,200),d=WW(e,n,o,a);d=Math.max(l,d);let p=HW(s);return p!==null&&(d=Math.min(d,p)),RW(t,l,d)}Zn();var{setLoader:jV,load:BW,provide:KV,getSync:OW}=Ft({fallbackImport:()=>Promise.resolve().then(()=>(tT(),eT))});var nT=BW;var oT=OW;var Jh=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()}},Zh=new Jh;var rT=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),DW=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),sT=(t,e,n)=>{if(!rT(t)||!rT(e)||DW.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]=sT(t[r],e[r],s)}return o};function iT(t,e){let n=sT(t,e,"");return xp(n)}var aT=()=>{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 _W=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},NW=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},ty=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=_W(t),n=NW(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}},ey=t=>typeof t=="string"?t:t==null?"":String(t),Mc={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:ey(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=ey(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:ey(n.text)}}},lT=t=>Array.isArray(t)?t.map(e=>String(e)):[],ny=t=>{let e=new Set(lT(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(lT(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 FW=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}},$W=t=>t.map(e=>({...e,streaming:!1})),VW=t=>t.map(e=>({...e,status:"complete"})),cT=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?FW(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?$W(n.messages):void 0,artifacts:n.artifacts?VW(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 zW=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")},dT=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 zW(t)},qW=async(t,e)=>{let n=await dT(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await dT(`${t}\0${e}`)}`}};var pT=(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 L=h();if(!L)return p;try{return L.getItem(o)}catch{return a=!0,p}},b=(L,B)=>{if(l||L===p)return;let W=p;p=L,d+=1;let z={previousToken:W,token:L,source:B,revision:d};for(let H of m)H(z)},C=L=>{l||L.key!==null&&L.key!==o||b(L.key===null?null:L.newValue??null,"external")},S=(async()=>{let L=await qW(t,e);o=L.storageKey,r=L.leaseKey,s=L.lockName,p=g(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),I=L=>new Promise(B=>setTimeout(B,L)),E=()=>{let L=h();if(!L)return null;try{let B=L.getItem(r);if(!B)return null;let W=JSON.parse(B);return typeof W?.expiresAt=="number"&&typeof W?.ownerNonce=="string"?W:null}catch{return null}},O=L=>{let B=h();if(B)try{E()?.ownerNonce===L&&B.removeItem(r)}catch{}},M=L=>new Promise(B=>{let W=setTimeout(z,L);function z(){clearTimeout(W),window.removeEventListener("storage",H),B()}function H(w){(w.key===null||w.key===r)&&z()}window.addEventListener("storage",H)}),D=async L=>{let B=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,W=Date.now()+15e3;for(;Date.now()<W;){let z=h();if(!z)break;let H=Date.now(),w=E();if(w&&w.expiresAt>H&&w.ownerNonce!==B){await M(Math.min(w.expiresAt-H,500));continue}try{z.setItem(r,JSON.stringify({ownerNonce:B,expiresAt:H+1e4}))}catch{a=!0;break}if(await I(20+Math.random()*40),E()?.ownerNonce!==B){await M(500);continue}u=B;try{return await L()}finally{u=null,O(B)}}return L()};return{ready:S,async get(){return await S,b(g(),"external"),p},async set(L){await S;let B=h();if(B)try{B.setItem(o,L)}catch{a=!0}b(L,"local")},async clear(){await S;let L=h();if(L)try{L.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return d},subscribe(L){return m.add(L),()=>{m.delete(L)}},async withFirstInitLock(L){await S;let B=globalThis.navigator?.locks;return B?.request?B.request(s,()=>L()):h()?D(L):L()},matches(L,B,W){return L===t&&B===e&&W===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&O(u)}}};Zn();var{setLoader:Bz,load:hB}=Ft({fallbackImport:()=>Promise.resolve().then(()=>(kT(),ET))});var my=hB;var fy=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Br=t=>Object.freeze({...t}),LT=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),PT=t=>t?Br(t):null;function IT(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let M of d.splice(0))try{M()}catch(D){fy("renderHistoryView cleanup",D)}},u=(M,D)=>{for(let L of e){let B=L[M];if(B)try{let W=B(D);if(W)return W}catch(W){fy(M,W)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),h={header:M=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:Br(M.identityStatus),pendingAction:PT(M.pendingAction),copy:Br(M.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:M.defaultRenderer})):null,conversation:M=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:LT(M.conversation),active:M.active,pending:M.pending,open:M.open,requestDelete:M.requestDelete,defaultRenderer:M.defaultRenderer})):null,state:M=>a?u("renderHistoryState",Object.freeze({...m(),state:Br(M.state),identityStatus:Br(M.identityStatus),copy:Br(M.copy),...M.retry?{retry:M.retry}:{},...M.startNewConversation?{startNewConversation:M.startNewConversation}:{},defaultRenderer:M.defaultRenderer})):null},g=e.flatMap(M=>(M.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:L=>D.render(Object.freeze({collapsed:L,presentation:t.getPresentation(),actions:C}))}))),b=t.createView({slots:h,renderDom:!1,onModelChange:()=>O(),railSections:g}),C=Object.freeze({...b.operations,close:t.close}),S=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),I=M=>Object.freeze({conversations:Object.freeze(M.conversations.map(LT)),activeConversationId:M.activeConversationId,state:Br(M.state),pendingAction:PT(M.pendingAction),identityStatus:Br(M.identityStatus),nextCursor:M.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Br(b.copy),actions:C,defaultRenderer:S,requestRender:()=>O(),onCleanup:D=>{d.push(D)}}),E=()=>{a=!1;let M=null;for(let L of e)if(L.renderHistoryView){try{M=L.renderHistoryView(I(b.getModel()))}catch(B){fy("renderHistoryView",B),M=null}if(M)break}let D=!M||M.contains(b.element);return a=D,b.setDomRenderEnabled(D),M??b.element};function O(){if(!(!s||o||r)){r=!0;try{p();let M=E();if(M===l)return;let D=l;l=M,t.onElementChanged(M,D)}finally{r=!1}}}return s=!0,O(),{view:b,get element(){return l??b.element},requestRender:O,dispose:()=>{o=!0,p()}}}var yB=null;function HT(){return yB}Wl();var bB=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"]]),vB=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."]]),gy=t=>vB.get(t)??"Conversation history is unavailable right now.";function CB(t){if(t instanceof or)return t;if(t instanceof at){let e=bB.get(t.code)??"unavailable";return new or(e,gy(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new or("unavailable",gy("unavailable"))}function RT(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 or("unsupported_scope",gy("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw CB(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=gw(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Il([],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}}}}}ry();Ue();var wB="button:not([disabled])";function Yu(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=q("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=q("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=q("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"}},q("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),q("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),q("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},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=q("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},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(wB));if(b.length===0)return;let C=b[0],S=b[b.length-1],I=document.activeElement;g.shiftKey&&(I===C||!l.contains(I))?(g.preventDefault(),S.focus()):!g.shiftKey&&I===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()})}hc();hc();var hy=require("partial-json");Ue();function WT(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=No.get(t.component);if(!s){if(Uh.includes(t.component)){$u().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 BT(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 yy(t){let e=BT(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 OT(t){let e=BT(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 xB=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function DT(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=xB}=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 I=[];for(let L=1;L<=5;L++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${p[L-1]}`),B.title=p[L-1],B.dataset.rating=String(L),B.innerHTML=`
|
|
1169
|
+
`):""},Sh=(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)"},cR=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=lR(t,o?.previewMaxLines??3),a=n?rw(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=Kf(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=Kf(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:l}},YA=(t,e,n)=>{Pu(t,e,{stateSet:Ta,previewKind:"tool",iconColor:GA(n?.toolCall??{})})},Ah=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=Mu("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&&Ta.has(t.id),{summary:d,previewText:p,isActive:u}=cR(t,e),m=Tu({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=Ll(n),w},S=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:e??{},elapsed:Ll(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 I=s.loadingAnimation??"none",E=o.activeTextTemplate,O=o.completeTextTemplate,M=u?E:O,D=S instanceof HTMLElement,L=(w,k)=>{g.textContent="";let R=n.name?.trim()||"tool",_=ap(w,R),X=0;for(let j of _){let Q=j.styles.length>0?(()=>{let Z=v("span",j.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return g.appendChild(Z),Z})():g;if(j.isDuration&&u)Q.appendChild(C());else{let Z=j.isDuration?Ll(n):j.text;k?X=ys(Q,Z,X):Q.appendChild(document.createTextNode(Z))}}};if(!D)if(u&&I!=="none"){let w=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),I==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),M&&L(M,!1);else if(g.classList.add(`persona-tool-loading-${I}`),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),I==="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)),M)L(M,!0);else{let k=g.textContent||d;g.textContent="",ys(g,k,0)}}else M&&L(M,!1);let B=GA(o),W=Eu(m,h,{expandable:a,expanded:l,iconColor:B,metaGap:!0}),z=ku({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,z),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"),k=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(k.style.color=o.labelTextColor),k.textContent="Arguments";let R=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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",Sh(R,o),R.textContent=cs(n.args),w.append(k,R),H.appendChild(w)}if(n.chunks&&n.chunks.length){let w=v("div","persona-space-y-1"),k=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(k.style.color=o.labelTextColor),k.textContent="Activity";let R=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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",Sh(R,o),R.textContent=n.chunks.join(""),w.append(k,R),H.appendChild(w)}if(n.status==="complete"&&n.result!==void 0){let w=v("div","persona-space-y-1"),k=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(k.style.color=o.labelTextColor),k.textContent="Result";let R=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");R.style.fontSize="0.75rem",R.style.lineHeight="1rem",Sh(R,o),R.textContent=cs(n.result),w.append(k,R),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 Lu({expanded:l,header:m,toggleIcon:W,content:H,collapsedPreview:z,iconColor:B}),r.append(m,z,H),r};oi();eo();var{setLoader:m$,load:hR,provide:f$,getSync:yR}=zt({fallbackImport:()=>Promise.resolve().then(()=>(rM(),oM))});var sM=hR;var iM=yR;ta();eo();var{setLoader:P$,load:$R}=zt({fallbackImport:()=>Promise.resolve().then(()=>(yM(),hM))});var Bh=$R;eo();yc();ei();bp();var Gh=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:VV,load:SW,provide:zV,getSync:AW}=zt({fallbackImport:()=>Promise.resolve().then(()=>(UM(),qM))}),Ia=null,Vu=new Set,jM=t=>{if(Ia)return Ia;Ia=t,t.initArtifactsUi({componentRegistry:Fo});for(let o of Gh)Fo.has(o)||Fo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ao();e?t.__provideMarkdownParsers(e):Zi(()=>{let o=Ao();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>yp());let n=[...Vu];Vu.clear();for(let o of n)try{o()}catch{}return t};var zu=()=>SW().then(jM);var Wr=()=>{if(Ia)return Ia;let t=AW();return t?jM(t):null},Yh=t=>Ia?()=>{}:(Vu.add(t),()=>{Vu.delete(t)});function jn(t){return t?.features?.artifacts?.enabled===!0}function KM(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 MW(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 GM=["panel","seamless","detached"];function Qh(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&GM.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Xh(t){return!t||!jn(t)?!1:Qh(t)==="detached"}function Ac(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"),MW(t),KM(t,e);return}let n=e.features?.artifacts?.layout,o=Qh(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)}KM(t,e)}function Mc(t,e){for(let l of GM)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=Qh(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 YM(t,e){return!e||!jn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var TW=new Set(["__proto__","prototype","constructor"]),EW=new Set(["collapsed","card","panel","inline"]),QM=new Set(["markdown","component"]),kW=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,yi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Uu=t=>!TW.has(t),Jh=t=>typeof t=="string"&&EW.has(t),bi=t=>Object.keys(t).length>0;function lr(t,e,n,o){t.push({path:e,code:n,message:o})}var LW="Ignored because this key is not part of the persisted preference schema.",qu="Ignored an unsupported value.",PW="Expected collapsed, panel, or inline.",IW='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',XM={kind:"mode",message:qu},Ha={kind:"string",message:"Expected a CSS length string."},Br={kind:"boolean"},HW={paneWidth:Ha,paneMaxWidth:Ha,paneMinWidth:Ha,expandedPanelWidth:Ha,resizableMinWidth:Ha,resizableMaxWidth:Ha,expandLauncherPanelWhenOpen:Br,resizable:Br},RW={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Br,showReasoning:Br,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:qu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:qu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:qu},expandable:Br,grouped:Br}},reasoningDisplay:{kind:"object",children:{expandable:Br,activePreview:Br}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:XM,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:XM,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:QM,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:QM}}},filePreview:{kind:"object",children:{enabled:Br}},layout:{kind:"object",children:HW}}}}};function JM(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:lr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:lr(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:lr(o,n,"invalid_value",e.message);case"mode":return Jh(t)?Mo(t):lr(o,n,"invalid_value",e.message);case"modeMap":{if(!yi(t))return lr(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:na(a);Uu(a)&&(r?r.has(a):kW.test(d))?Jh(l)?s[d]=Mo(l):lr(o,`${n}.${a}`,"invalid_value",PW):lr(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":IW)}return bi(s)?s:void 0}case"object":{if(e.bareMode&&Jh(t))return Mo(t);if(!yi(t))return lr(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))(!Uu(l)||!r.includes(l))&&lr(o,s(l),"unknown_key",LW);let a={};for(let l of r){let d=e.children[l],p=JM(t[l],d,s(l),o);if(d.deprecated&&t[l]!==void 0&&lr(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=yi(m)&&yi(p)?{...m,...p}:p}return bi(a)?a:void 0}}}function WW(t){let e=[];return{preferences:(t===null?void 0:JM(t,RW,"",e))??{},issues:e}}function Ra(t){if(Array.isArray(t))return t.map(Ra);if(!yi(t))return t;let e={};for(let[n,o]of Object.entries(t))Uu(n)&&o!==void 0&&(e[n]=Ra(o));return e}function ZM(t,e){let n=Ra(t);for(let[o,r]of Object.entries(e)){if(!Uu(o)||r===void 0)continue;let s=n[o];n[o]=yi(s)&&yi(r)?ZM(s,r):Ra(r)}return n}function BW(t){let e={},n;for(let r of t){let s=WW(r).preferences;n=eT(n,s.artifacts?.display),e=ZM(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function OW(t,e){if(e===void 0)return t===void 0?void 0:Ra(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}:{},...bi(r)?{byMediaType:r}:{}};return bi(s)?s:void 0}function eT(t,e){if(e===void 0)return t===void 0?void 0:Ra(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=OW(n.files,e.files),a={...o?{default:o}:{},...bi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return bi(a)?a:void 0}function DW(t={},e){let n=BW(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=eT(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 Zh(t){let e=t.preferences;return!e||!bi(e)?t:{...t,features:DW(t.features??{},[e])}}function _W(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 NW(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 FW(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function $W(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function ey(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 tT(t,e,n,o,r,s,a=200){let l=_W(r,200),d=$W(e,n,o,a);d=Math.max(l,d);let p=NW(s);return p!==null&&(d=Math.min(d,p)),FW(t,l,d)}eo();var{setLoader:ZV,load:VW,provide:ez,getSync:zW}=zt({fallbackImport:()=>Promise.resolve().then(()=>(sT(),rT))});var iT=VW;var aT=zW;var ty=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()}},ny=new ty;var lT=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),qW=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),cT=(t,e,n)=>{if(!lT(t)||!lT(e)||qW.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]=cT(t[r],e[r],s)}return o};function dT(t,e){let n=cT(t,e,"");return Ap(n)}var pT=()=>{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 UW=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},jW=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},ry=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=UW(t),n=jW(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}},oy=t=>typeof t=="string"?t:t==null?"":String(t),Tc={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:oy(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=oy(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:oy(n.text)}}},uT=t=>Array.isArray(t)?t.map(e=>String(e)):[],sy=t=>{let e=new Set(uT(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(uT(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 KW=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}},GW=t=>t.map(e=>({...e,streaming:!1})),YW=t=>t.map(e=>({...e,status:"complete"})),mT=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?KW(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?GW(n.messages):void 0,artifacts:n.artifacts?YW(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 QW=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")},fT=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 QW(t)},XW=async(t,e)=>{let n=await fT(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await fT(`${t}\0${e}`)}`}};var gT=(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 L=h();if(!L)return p;try{return L.getItem(o)}catch{return a=!0,p}},b=(L,B)=>{if(l||L===p)return;let W=p;p=L,d+=1;let z={previousToken:W,token:L,source:B,revision:d};for(let H of m)H(z)},C=L=>{l||L.key!==null&&L.key!==o||b(L.key===null?null:L.newValue??null,"external")},S=(async()=>{let L=await XW(t,e);o=L.storageKey,r=L.leaseKey,s=L.lockName,p=g(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),I=L=>new Promise(B=>setTimeout(B,L)),E=()=>{let L=h();if(!L)return null;try{let B=L.getItem(r);if(!B)return null;let W=JSON.parse(B);return typeof W?.expiresAt=="number"&&typeof W?.ownerNonce=="string"?W:null}catch{return null}},O=L=>{let B=h();if(B)try{E()?.ownerNonce===L&&B.removeItem(r)}catch{}},M=L=>new Promise(B=>{let W=setTimeout(z,L);function z(){clearTimeout(W),window.removeEventListener("storage",H),B()}function H(w){(w.key===null||w.key===r)&&z()}window.addEventListener("storage",H)}),D=async L=>{let B=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,W=Date.now()+15e3;for(;Date.now()<W;){let z=h();if(!z)break;let H=Date.now(),w=E();if(w&&w.expiresAt>H&&w.ownerNonce!==B){await M(Math.min(w.expiresAt-H,500));continue}try{z.setItem(r,JSON.stringify({ownerNonce:B,expiresAt:H+1e4}))}catch{a=!0;break}if(await I(20+Math.random()*40),E()?.ownerNonce!==B){await M(500);continue}u=B;try{return await L()}finally{u=null,O(B)}}return L()};return{ready:S,async get(){return await S,b(g(),"external"),p},async set(L){await S;let B=h();if(B)try{B.setItem(o,L)}catch{a=!0}b(L,"local")},async clear(){await S;let L=h();if(L)try{L.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return d},subscribe(L){return m.add(L),()=>{m.delete(L)}},async withFirstInitLock(L){await S;let B=globalThis.navigator?.locks;return B?.request?B.request(s,()=>L()):h()?D(L):L()},matches(L,B,W){return L===t&&B===e&&W===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&O(u)}}};eo();var{setLoader:Vz,load:SB}=zt({fallbackImport:()=>Promise.resolve().then(()=>(HT(),IT))});var hy=SB;var yy=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Or=t=>Object.freeze({...t}),RT=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),WT=t=>t?Or(t):null;function BT(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let M of d.splice(0))try{M()}catch(D){yy("renderHistoryView cleanup",D)}},u=(M,D)=>{for(let L of e){let B=L[M];if(B)try{let W=B(D);if(W)return W}catch(W){yy(M,W)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),h={header:M=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:Or(M.identityStatus),pendingAction:WT(M.pendingAction),copy:Or(M.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:M.defaultRenderer})):null,conversation:M=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:RT(M.conversation),active:M.active,pending:M.pending,open:M.open,requestDelete:M.requestDelete,defaultRenderer:M.defaultRenderer})):null,state:M=>a?u("renderHistoryState",Object.freeze({...m(),state:Or(M.state),identityStatus:Or(M.identityStatus),copy:Or(M.copy),...M.retry?{retry:M.retry}:{},...M.startNewConversation?{startNewConversation:M.startNewConversation}:{},defaultRenderer:M.defaultRenderer})):null},g=e.flatMap(M=>(M.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:L=>D.render(Object.freeze({collapsed:L,presentation:t.getPresentation(),actions:C}))}))),b=t.createView({slots:h,renderDom:!1,onModelChange:()=>O(),railSections:g}),C=Object.freeze({...b.operations,close:t.close}),S=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),I=M=>Object.freeze({conversations:Object.freeze(M.conversations.map(RT)),activeConversationId:M.activeConversationId,state:Or(M.state),pendingAction:WT(M.pendingAction),identityStatus:Or(M.identityStatus),nextCursor:M.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Or(b.copy),actions:C,defaultRenderer:S,requestRender:()=>O(),onCleanup:D=>{d.push(D)}}),E=()=>{a=!1;let M=null;for(let L of e)if(L.renderHistoryView){try{M=L.renderHistoryView(I(b.getModel()))}catch(B){yy("renderHistoryView",B),M=null}if(M)break}let D=!M||M.contains(b.element);return a=D,b.setDomRenderEnabled(D),M??b.element};function O(){if(!(!s||o||r)){r=!0;try{p();let M=E();if(M===l)return;let D=l;l=M,t.onElementChanged(M,D)}finally{r=!1}}}return s=!0,O(),{view:b,get element(){return l??b.element},requestRender:O,dispose:()=>{o=!0,p()}}}var AB=null;function OT(){return AB}Bl();var MB=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"]]),TB=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."]]),by=t=>TB.get(t)??"Conversation history is unavailable right now.";function EB(t){if(t instanceof or)return t;if(t instanceof st){let e=MB.get(t.code)??"unavailable";return new or(e,by(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new or("unavailable",by("unavailable"))}function DT(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 or("unsupported_scope",by("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw EB(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=bw(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Hl([],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}}}}}ay();qe();var kB="button:not([disabled])";function Xu(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=q("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=q("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=q("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"}},q("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),q("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),q("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},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=q("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},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(kB));if(b.length===0)return;let C=b[0],S=b[b.length-1],I=document.activeElement;g.shiftKey&&(I===C||!l.contains(I))?(g.preventDefault(),S.focus()):!g.shiftKey&&I===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()})}yc();yc();var vy=require("partial-json");qe();function _T(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Fo.get(t.component);if(!s){if(Gh.includes(t.component)){zu().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 NT(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 Cy(t){let e=NT(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 FT(t){let e=NT(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 LB=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function $T(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=LB}=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 I=[];for(let L=1;L<=5;L++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${p[L-1]}`),B.title=p[L-1],B.dataset.rating=String(L),B.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
|
-
`,B.addEventListener("click",()=>{m=L,I.forEach((W,z)=>{let H=z<L;W.classList.toggle("selected",H),W.setAttribute("aria-checked",z===L-1?"true":"false")})}),I.push(B),S.appendChild(B)}h.appendChild(S);let E=null;if(d){let L=document.createElement("div");L.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),L.appendChild(E),h.appendChild(L)}let O=document.createElement("div");O.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=l,M.addEventListener("click",()=>{n?.(),u.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let L=E?.value.trim()||void 0;await e(m,L),u.remove()}catch(L){D.disabled=!1,D.textContent=a,console.error("[CSAT Feedback] Failed to submit:",L)}}),O.appendChild(M),O.appendChild(D),h.appendChild(O),u.appendChild(h),u}function _T(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 I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let O=document.createElement("span");O.className="persona-feedback-label-low",O.textContent=p;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=u,E.appendChild(O),E.appendChild(M);let D=document.createElement("div");D.className="persona-feedback-numbers";let L=[];for(let w=0;w<=10;w++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-number-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`Rating ${w} out of 10`),k.textContent=String(w),k.dataset.rating=String(w),w<=6?k.classList.add("persona-feedback-detractor"):w<=8?k.classList.add("persona-feedback-passive"):k.classList.add("persona-feedback-promoter"),k.addEventListener("click",()=>{h=w,L.forEach((R,_)=>{R.classList.toggle("selected",_===w),R.setAttribute("aria-checked",_===w?"true":"false")})}),L.push(k),D.appendChild(k)}I.appendChild(E),I.appendChild(D),g.appendChild(I);let B=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),w.appendChild(B),g.appendChild(w)}let W=document.createElement("div");W.className="persona-feedback-actions";let z=document.createElement("button");z.type="button",z.className="persona-feedback-btn persona-feedback-btn-skip",z.textContent=l,z.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){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let w=B?.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)}}),W.appendChild(z),W.appendChild(H),g.appendChild(W),m.appendChild(g),m}var Ra="persona-chat-history",MB=30*1e3,TB=641,Wa="data-persona-composer-reason",EB={"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 kB(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=EB[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 Qu(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 LB(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 PB(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var by=t=>!t||typeof t!="object"?{}:{...t},NT=t=>t.map(e=>({...e,streaming:!1})),FT=(t,e,n)=>{let o=t?.markdown?jd(t.markdown):null,r=Gd(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=So()!==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?vC(d):d,g=o(h);m=r&&u?r(g):g}else m=Er(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)),Er(l.text??"")}}};function $T(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=He(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 IB=(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},HB=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:IB(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),VT=(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=xp(e),r=()=>{tx({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Qh(o);let a=Zh.getForInstance(o.plugins),l=BS(t),d=[],p=!1,u=zA(()=>o),m=null,h=null,g=null,b=!1,C=null,S=i=>{m=i,i.initApprovalUi({webMcpToolTitle:Yd});let c=i.createBuiltInApprovalPlugin();h=c.plugin,g=c.teardown},I=()=>{if(m)return m;let i=oM();return i?(S(i),i):(nM().then(c=>{b||m||(S(c),C?.())}).catch(()=>{}),null)},E=!1,O=!1,M=null,D=(i,c,f,y)=>{if(!i.querySelector("[data-tv-form]"))return;let x=oT();if(x){x.enhanceWithForms(i,c,f,y);return}nT().then(()=>{E||O||!M||(O=!0,M())}).catch(()=>{})};o.components&&No.registerAll(o.components);let L=aT(),W=o.persistState===!1?null:o.storageAdapter??cT(),z=!!o.clientToken&&typeof o.reconnectStream!="function",H={},w=null,k,R=new Promise(i=>{k=i}),_,X=!1,j=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&&(X=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(W?.load)try{let i=W.load();if(i&&typeof i.then=="function")w=i.then(c=>j(c??{messages:[],metadata:{}}));else{let f=j(i??{messages:[],metadata:{}});f.metadata&&(H=by(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),_=f.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=j({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}w||k();let Q=()=>H,Z=i=>{H=i({...H})??{},Ri()},ie=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ty],se=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Mc.message,Mc.messageAndClick],pe=ny({parsers:ie,handlers:se,getSessionMetadata:Q,updateSessionMetadata:Z,emit:L.emit,documentRef:typeof document<"u"?document:null});pe.syncFromMetadata();let ue=o.launcher?.enabled??!0,xe=o.launcher?.autoExpand??!1,be=o.autoFocusInput??!1,F=xe,Ce=ue,Ee=o.layout?.header?.layout,qe=!1,ke=()=>ic(o),Ie=()=>ue||ke(),Te=ke()?!1:ue?xe:!0,vt=!1,Ye=null,Et=()=>{vt=!0,Ye&&clearTimeout(Ye),Ye=setTimeout(()=>{vt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),vt=!1)},1e4)},je=FT(o,pe,Et),lt=o.features?.showReasoning??!0,Vt=o.features?.showToolCalls??!0,It=o.features?.showEventStreamToggle??!1,Gt=o.features?.scrollToBottom??{},Ot=o.features?.scrollBehavior??{},Ge=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Dt=`${Ge()}event-stream`,Lt=null,jn=o.features?.eventStream?.maxEvents??2e3,rt=null,Zt=null,ln=null,K=!1,ae=null,A=!1,T=null,V=0,U=(i,c)=>{rt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},ee=(i,c)=>{Zt?.processEvent(i,c),rt?U(i,c):ln&&(ln.length>=jn&&ln.shift(),ln.push({type:i,payload:c}))},me=()=>{rt||!It||(ln??(ln=[]),Hh().then(i=>{if(K||rt||!It)return;Lt=new i.EventStreamStore(Dt),rt=new i.EventStreamBuffer(jn,Lt),Zt=Zt??new i.ThroughputTracker,Lt.open().then(()=>rt?.restore()).catch(f=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let c=ln??[];ln=null;for(let f of c)Zt?.processEvent(f.type,f.payload),U(f.type,f.payload)}).catch(()=>{}))};It&&me();let J=!1,re=null,Le=()=>{},Me=()=>{},mt=()=>{},ct=()=>{},zt=()=>{},ft=()=>A||J&&re==="panel",Je={onCopy:i=>{L.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=>{L.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??{},xt=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 Hn(i,c,f,y){if(!i.hasAttribute(Wa))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 rn=VA({config:o,showClose:Ie()}),{wrapper:st,panel:Fe,pillRoot:Yt}=rn.shell,Qe=rn.panelElements,{container:Pe,body:le,messagesWrapper:We,starterSuggestions:Ci,transcriptSuggestions:Dr,suggestions:Lo,textarea:Ae,sendButton:$e,composerForm:Rn,statusText:gt,welcomeHost:cn,welcomeIconHolder:Oa,greetingHost:Ln,introKicker:Da,introTitle:Ju,introSubtitle:Zu,closeButton:N,iconHolder:de,headerTitle:De,headerSubtitle:Xe,header:ve,footer:Be,actionsRow:Fo}=Qe,$o=Qe.leftActions,_r=Qe.rightActions,Vo=Qe.sendButtonWrapper,My=Qe.setSendButtonMode,ye=Qe.micButton,no=Qe.micButtonWrapper,Qt=Qe.attachmentButton,Kn=Qe.attachmentButtonWrapper,$t=Qe.attachmentInput,Gn=Qe.attachmentPreviewsContainer;Pe.classList.add("persona-relative"),le.classList.add("persona-relative");let tE=12,_a=()=>Gt.label??"",nE=()=>Gt.iconName??"arrow-down",oE=()=>Gt.enabled!==!1,oo=()=>Ot.mode??"anchor-top",Nr=()=>oo()==="follow"||oo()==="anchor-top"&&Ga,Na=()=>Ot.anchorTopOffset??16,rE=()=>Ot.restorePosition??"bottom",Ty=()=>Ot.pauseOnInteraction===!0,Ey=()=>Ot.showActivityWhilePinned!==!1,ky=()=>Ot.announce===!0,em=()=>Ot.scrollbar??"on-scroll",dn=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");dn.type="button",dn.style.display="none",dn.setAttribute("data-persona-scroll-to-bottom","true");let Fa=v("span","persona-flex persona-items-center"),tm=v("span",""),xs=v("span","");xs.setAttribute("data-persona-scroll-to-bottom-count",""),xs.style.display="none",dn.append(Fa,tm,xs),Pe.appendChild(dn);let fo=v("div","persona-stream-anchor-spacer");fo.setAttribute("aria-hidden","true"),fo.setAttribute("data-persona-anchor-spacer",""),fo.style.flexShrink="0",fo.style.pointerEvents="none",fo.style.height="0px",fo.style.display="none",le.appendChild(fo);let dr=v("div","persona-sr-only");dr.setAttribute("aria-live","polite"),dr.setAttribute("aria-atomic","true"),dr.setAttribute("role","status"),dr.setAttribute("data-persona-live-region",""),Object.assign(dr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Pe.appendChild(dr);let $a=null,Hc=null,Rc=i=>{!ky()||!i||(Hc=i,$a===null&&($a=setTimeout(()=>{$a=null,Hc&&ky()&&(dr.textContent=Hc),Hc=null},400)))},Wc="empty",Bc=0,nm=()=>Bc||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Ss=()=>{let c=Be.style.display==="none"?0:Be.offsetHeight;dn.style.bottom=`${c+nm()+tE}px`};Ss();let om=()=>{Mi||(Be.style.marginBottom=Bc>0?`${Bc}px`:"")},Oc=()=>{let i=zg(o,ke()),c=Hr(o),y=Be.style.display==="none"?0:Be.offsetHeight,x=c.anchor==="center"&&Wc==="empty"?Yl(c.anchorComposerTop)??Yl("44%"):null,P=x===null||ke()?0:HS({columnHeight:Pe.clientHeight,footerHeight:y,fraction:x});t.style.setProperty("--persona-composer-overlay-height",`${y}px`),t.style.setProperty("--persona-composer-lift",`${i==="overlay"?P:0}px`),Bc=i==="block"?P:0,om(),Ss()},Ly=()=>{let i=!!_a();dn.setAttribute("aria-label",_a()||"Jump to latest"),dn.title=_a(),dn.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Fa.innerHTML="";let c=He(nE(),"14px","currentColor",2);c?(Fa.appendChild(c),Fa.style.display=""):Fa.style.display="none",tm.textContent=_a(),tm.style.display=i?"":"none"};Ly();let Ct=null,sn=null,Ve=Yw(),sE=i=>{try{Pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};Ve.subscribe(sE);let zo=()=>{Ve.setText(Ae?.value??"")},As=()=>{Ve.setMentionRefs(sn?.getMentionRefs()??[])},iE=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}),Py=i=>{let c=Object.freeze(i.map(iE));Ve.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Lm()};Ve.setSelectedModelId(o.composer?.selectedModelId);let Va=()=>o.composer?.modes??[],wi=()=>Tx(Va(),o.composer?.modeGroups);{let i=Dp(o.composer?.defaultActiveModeIds??[],Va());i.length&&Ve.setActiveModeIds(i)}function Iy(i){if(Ve.getState().selectedModelId!==i){Ve.setSelectedModelId(i),Fr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function Dc(i){Ve.setActiveModeIds(i),pr?.render(i,wi()),xi.forEach(c=>c.repaint()),Uo?.resolve(),ld(),Po()}function rm(i){Dc(Ex(Ve.getState().activeModeIds,i,Va(),o.composer?.modeGroups))}let Fr=null,sm=null,pr=null,xi=new Map,$r=null;function qo(i){Ve.setQuote(i),$r?.render(Ve.getState().quote),Po(),Sb()}let Hy=!1;function im(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Hy&&o.debug===!0&&(Hy=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Vr=null;function Si(i){Ve.setPendingSubmission(i),Vr?.render(Ve.getState().pendingSubmission),Po()}let aE=i=>{let c=xi.get(i);if(c)return c;let f=Px({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(y=>y.id===i),getModes:()=>Va().filter(y=>y.groupId===i),getActiveIds:()=>Ve.getState().activeModeIds,onSelect:y=>rm(y)});return xi.set(i,f),f},lE=()=>{let i=[],c=Ve.getState().activeModeIds,f=new Set;if(Va().forEach((y,x)=>{if(Op(y.groupId,o.composer?.modeGroups)){let P=y.groupId;if(f.has(P))return;f.add(P);let Y=aE(P);Y.action.order=Tg(x),Y.action.label=o.composer?.modeGroups?.find(ne=>ne.id===P)?.label??P,i.push(Y.action);return}i.push({id:Ax(y.id),kind:"button",placement:"start",order:Tg(x),presentation:y.presentation??"auto",label:y.label,shortLabel:y.shortLabel,iconName:y.iconName,pressed:c.includes(y.id),onSelect:()=>rm(y.id)})}),o.composer?.models?.length&&!a.some(y=>y.renderComposer)){let y=o.composer?.modelPicker?.presentation??"native";(!Fr||sm!==y)&&(sm=y,Fr=xx({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Ve.getState().selectedModelId,onSelect:x=>Iy(x),presentation:y,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Fr.action)}return i},am=null,Ry=a.find(i=>i.renderHeader);if(Ry?.renderHeader){let i=Ry.renderHeader({config:o,defaultRenderer:()=>{let c=ii({config:o,showClose:Ie()});return lc(Pe,c,o),c.header},onClose:()=>Rt(!1,"user")});if(i){let c=ve;c&&(c.replaceWith(i),ve=i,rn.header.element=i)}}let Wy=()=>{ae&&(le.style.display="none",Be.parentNode?.insertBefore(ae.element,Be),ae.update())},lm=()=>{if(!rt){me();return}if(A=!0,ae?Wy():Hh().then(c=>{ae||!A||!rt||(ae=c.createEventStreamView({buffer:rt,getFullHistory:()=>rt.getAllFromStore(),onClose:()=>Ai(),config:o,plugins:a,getThroughput:()=>Zt?.getMetric()??{status:"idle"},renderIconByName:He}),Wy())}).catch(()=>{Ai()}),St){St.style.boxShadow=`inset 0 0 0 1.5px ${zn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&St.classList.add(f))}let i=()=>{if(!A)return;let c=Date.now();c-V>=200&&(ae?.update(),V=c),T=requestAnimationFrame(i)};V=0,T=requestAnimationFrame(i),bn(),L.emit("eventStream:opened",{timestamp:Date.now()})},Ai=()=>{if(A){if(A=!1,ae&&ae.element.remove(),le.style.display="",St){St.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&St.classList.remove(c))}T!==null&&(cancelAnimationFrame(T),T=null),bn(),L.emit("eventStream:closed",{timestamp:Date.now()})}},St=null;if(It){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:"");St=v("button",c),St.style.width="28px",St.style.height="28px",St.style.color=zn.actionIconColor,St.type="button",St.setAttribute("aria-label","Event Stream"),St.title="Event Stream";let f=Ke(Or.Activity,"18px","currentColor",1.5);f&&St.appendChild(f);let y=Qe.clearChatButtonWrapper,x=Qe.closeButtonWrapper,P=y||x;P&&P.parentNode===ve?ve.insertBefore(St,P):ve.appendChild(St),St.addEventListener("click",()=>{A?Ai():lm()})}let By=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??Lr).join(","),x.multiple=(c.maxFiles??4)>1,x.style.display="none",x.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(x)}},Mi=!1,Oy=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:()=>Yv(),storage:u(c.id),onSubmit:x=>{!$||$.isStreaming()||Bd(x.trim(),{consumeDraft:!1})},streaming:y,disabled:y,openAttachmentPicker:()=>{Yr()||$t?.click()},models:f?.models,selectedModelId:Ve.getState().selectedModelId??f?.selectedModelId,onModelChange:x=>Iy(x),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{am?.()}:void 0})},Dy=Oy(()=>dc({config:o}).footer);Dy&&(rn.replaceComposer(Dy),Be=rn.composer.footer,Mi=!0);let At=null,cE=i=>{Rn=i.form,Ae=i.input,Vo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&($e=i.sendButton),i.micButton&&(ye=i.micButton,no=i.micButton.parentElement),i.found.status&&(gt=i.found.status),i.found.suggestions&&(Lo=i.found.suggestions),i.attachmentButton&&(Qt=i.attachmentButton,Kn=i.attachmentButton.parentElement),$t=i.attachmentInput??null,Gn=i.attachmentPreviews??null,i.found.actionsRow&&(Fo=i.found.actionsRow),$o=i.found.actionsStart,_r=i.found.actionsEnd};function cm(){let i=Ae;if(!i)return;let c=o.composer?.inputAttributes,f=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;Mp(i,c),f&&i.setAttribute("aria-label",f),Ap(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Fl(i)}),ax(i,Sp(o.composer?.maxLines,ke()?5:3))}let _y=i=>{At=Xw(i,{debug:o.debug===!0}),At&&cE(At),cm()};By(Be),_y(Be),zo();let za=gs(o,ke());za&&(We.style.maxWidth=za,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",Ln.style.maxWidth=za,Ln.style.marginLeft="auto",Ln.style.marginRight="auto",Ln.style.width="100%",Ci.style.maxWidth=za,Dr.style.maxWidth=za,Dr.style.marginLeft="auto",Dr.style.marginRight="auto",Dr.style.width="100%");let Ny=()=>{let i=gs(o,ke());if(!(!i||ke()))for(let c of[Rn,Lo,Gn,gt])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Ny();let Fy=()=>{!o.attachments?.enabled||!$t||!Gn||(Ct?Ct.remountPreviews(Gn):(Ct=Dl.fromConfig(o.attachments,Py),Ct.setPreviewsContainer(Gn)),At?.addListener($t,"change",i=>{let c=i.target;Ct?.handleFileSelect(c.files),c.value=""}),Pe.querySelector(".persona-attachment-drop-overlay")||Pe.appendChild($T(o.attachments.dropOverlay)))};Fy();let dE=()=>sn?.prefetch(),$y=()=>{if(!o.contextMentions?.enabled||!Ae)return;let i=At?.header??null,c=i?Mg(i):void 0;if(sn=MS({config:o,textarea:Ae,anchor:Rn??Ae,getMessages:()=>$.getMessages(),liveRegionHost:Pe,chipRow:c}),sn&&!c){let f=Ae;f.parentElement?.insertBefore(sn.contextRow,f)}};$y();let Uo=null,pE={getState:()=>Ve.getState(),getValue:()=>Ae?.value??"",setValue:i=>{Ae&&(Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),zo())},submit:()=>{$l(At?.form??null)},openAttachmentPicker:()=>{Yr()||$t?.click()},toggleVoice:()=>{am?.()},requestRender:()=>Uo?.resolve()},uE=()=>{let i=[];return(sn?.affordanceButtons??[]).forEach((f,y)=>{i.push({id:`core:mention-${y}`,placement:"start",order:sr.mention+y,element:f,managed:!0})}),Kn&&i.push({id:"core:attachment",placement:"start",order:sr.attachment,element:Kn}),no&&i.push({id:"core:mic",placement:"end",order:sr.mic,element:no}),Vo&&i.push({id:"core:send",placement:"end",order:sr.send,element:Vo}),i},Vy=()=>{Uo?.destroy(),Uo=vx({getBindings:()=>At,collect:()=>({builtIns:uE(),configActions:[...lE(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>Ve.getState(),requestRender:()=>Uo?.resolve()},debug:o.debug===!0}),actionContext:pE,getState:()=>Ve.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Uo.resolve()};Vy();let dm=()=>{if(pr?.destroy(),pr=null,!wi().length)return;let i=At?.header;i&&(pr=Sx({row:Mg(i),onRemove:c=>rm(c),initialIds:Ve.getState().activeModeIds}),pr.render(Ve.getState().activeModeIds,wi()))};dm();let zy=()=>{$r?.destroy(),$r=null,Vr?.destroy(),Vr=null;let i=At?.header;i&&($r=Ix({onDismiss:()=>qo(void 0)}),i.appendChild($r.element),$r.render(Ve.getState().quote),im()==="defer-one"&&(Vr=Hx({onEdit:()=>Fk(),onRemove:()=>Si(void 0)}),i.appendChild(Vr.element),Vr.render(Ve.getState().pendingSubmission)))};zy();let pm=_x(),mE=()=>{let i=At?.header?.querySelector(Ag);if(i)return i.childElementCount>0;let c=Ve.getState();return c.mentionRefs.length>0||Dp(c.activeModeIds,wi()).length>0},qy=()=>!1;function Po(){let i=Ve.getState(),c=pm.observe(Nx(Ae),i.text);Be.toggleAttribute("data-persona-composer-compact",Dx({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:mE(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:qy()}))}function Uy(){o.composer?.layout==="single-row"&&!ke()?Be.setAttribute("data-persona-composer-layout","single-row"):Be.removeAttribute("data-persona-composer-layout")}Uy(),Ve.subscribe(()=>{Uo?.sync(),Lm(),id(),Po(),Sb()}),id();let jy=!1,fE=i=>{if(jy||o.debug!==!0)return;let c=["messages","composer"].filter(f=>i[f]);c.length&&(jy=!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??{};fE(i);let c=y=>{switch(y){case"body-top":return le.querySelector("[data-persona-intro-card]");case"messages":return We;case"footer-top":return Lo;case"composer":return Rn;case"footer-bottom":return gt;default:return null}},f=(y,x)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")ve.insertBefore(x,ve.firstChild);else if(y==="header-right")ve.appendChild(x);else{let P=ve.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(x,P.nextSibling):ve.appendChild(x)}break;case"body-top":{let P=le.querySelector("[data-persona-intro-card]");P?P.replaceWith(x):le.insertBefore(x,le.firstChild);break}case"body-bottom":le.appendChild(x);break;case"footer-top":Lo.replaceWith(x);break;case"footer-bottom":gt.replaceWith(x);break;default:break}};for(let[y,x]of Object.entries(i))if(x)try{let P=x({config:o,defaultContent:()=>c(y)});P&&f(y,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,P)}})();let Ky=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 P=f.getAttribute("data-bubble-type");if(P==="reasoning")Aa.has(x)?Aa.delete(x):Aa.add(x),qA(x,y);else if(P==="tool")Ma.has(x)?Ma.delete(x):Ma.add(x),jA(x,y,o);else if(P==="approval"&&m){let ne=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",te=m.approvalDetailsExpansionState.get(x)??ne;m.approvalDetailsExpansionState.set(x,!te),m.updateApprovalDetailsUI(x,y,o)}pn.delete(x)};We.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Ky(i))}),We.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Ky(i))}),We.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let f=We.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let x=y.toString(),P=DS(x);!P||P===x||(c.setData("text/plain",P),i.preventDefault())});let um=new Map,Gy=null,Yy="idle",gE={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},hE=(i,c)=>{let{icon:f,label:y}=gE[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=He(f,14,"currentColor",2);x&&(i.innerHTML="",i.appendChild(x))},Qy=()=>{We.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let y=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;hE(c,y&&y===Gy?Yy:"idle")})};We.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 P=f.getAttribute("data-action");if(P==="copy"){let ne=$.getMessages().find(te=>te.id===x);if(ne&&Je.onCopy){let te=ne.content||"";navigator.clipboard.writeText(te).then(()=>{f.classList.add("persona-message-action-success");let oe=Ke(Or.Check,14,"currentColor",2);oe&&(f.innerHTML="",f.appendChild(oe)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let fe=Ke(Or.Copy,14,"currentColor",2);fe&&(f.innerHTML="",f.appendChild(fe))},2e3)}).catch(oe=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",oe)}),Je.onCopy(ne)}}else if(P==="read-aloud")$.toggleReadAloud(x);else if(P==="upvote"||P==="downvote"){let ne=(um.get(x)??null)===P,te=P==="upvote"?"thumbs-up":"thumbs-down";if(ne){um.delete(x),f.classList.remove("persona-message-action-active");let oe=He(te,14,"currentColor",2);oe&&(f.innerHTML="",f.appendChild(oe))}else{let oe=P==="upvote"?"downvote":"upvote",fe=y.querySelector(`[data-action="${oe}"]`);if(fe){fe.classList.remove("persona-message-action-active");let Wt=He(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Wt&&(fe.innerHTML="",fe.appendChild(Wt))}um.set(x,P),f.classList.add("persona-message-action-active");let Se=He(te,14,"currentColor",2);Se&&(Se.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(Se)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let bt=$.getMessages().find(Ht=>Ht.id===x);bt&&Je.onFeedback&&Je.onFeedback({type:P,messageId:bt.id,message:bt})}}else if(P==="regenerate")_c?.regenerate(x);else if(P==="edit")_c?.edit(x);else if(P==="quote")_c?.quote(x);else if(P?.startsWith(yu)){let Y=P.slice(yu.length),ne=o.messageActions?.custom?.find(oe=>oe.id===Y),te=$.getMessages().find(oe=>oe.id===x);if(!ne||!te)return;try{ne.onSelect(te)}catch(oe){console.error(`[AgentWidget] messageActions.custom "${Y}" onSelect failed:`,oe)}}});let _c=null;We.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 P=f.getAttribute("data-approval-action");if(!P)return;let Y=P==="approve"?"approved":"denied",te=$.getMessages().find(fe=>fe.id===x);if(!te?.approval)return;let oe=y.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(Se=>{Se.disabled=!0,Se.style.opacity="0.5",Se.style.cursor="not-allowed"}),te.approval.toolType==="webmcp"?$.resolveWebMcpApproval(x,Y):$.resolveApproval(te.approval,Y)});let dt=null,Xy=!1,qa=null,Ms=()=>{},Ua="none",Nc=null,go={artifacts:[],selectedId:null},ur=!1,Io=!1,ja=!1,Ti=!1,Jy=()=>Ti||go.artifacts.some(i=>os(o.features?.artifacts,i)==="panel"),Fc=()=>go.artifacts.length>0&&!ur&&Jy(),Pt={current:null},mm=(i,c)=>{let f=$.getArtifactById(c),y=f?.markdown,x=f?.title||"artifact",P=f?.file,Y=f?.artifactType??"markdown";if(!y){let oe=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(oe){let Se=$.getMessages().find(Re=>Re.id===oe);if(Se?.rawContent)try{let Re=JSON.parse(Se.rawContent);y=Re?.props?.markdown,x=Re?.props?.title||x,Re?.props?.file&&typeof Re.props.file=="object"&&(P=Re.props.file),!f&&typeof Re?.props?.artifactType=="string"&&(Y=Re.props.artifactType)}catch{}}}return{markdown:y,title:x,file:P,artifactType:Y}};We.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:P,title:Y,file:ne}=mm(f,y);if(!P)return;let te=Rr();te&&te.triggerArtifactDownload(te.downloadInfoFor({title:Y,markdown:P,file:ne}))}),We.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]"),P=x?null:f.closest("[data-open-artifact]"),Y=x?x.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,te=(x?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Ht=>Ht.id===y);if(!te)return;let{markdown:oe,title:fe,file:Se,artifactType:Re}=mm(f,Y??""),bt={artifactId:Y,title:fe,artifactType:Re,markdown:oe,file:Se};try{Promise.resolve(te.onClick(bt)).catch(()=>{})}catch{}}),We.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),P=Rr();if(!P)return;let Y="";if(x)Y=P.artifactCopyText(x);else{let{markdown:ne,file:te,artifactType:oe}=mm(f,y);oe==="markdown"&&(Y=P.artifactCopyText({id:y,artifactType:"markdown",status:"complete",markdown:ne??"",...te?{file:te}:{}}))}Y&&navigator.clipboard.writeText(Y).then(()=>{let ne=Ke(Or.Check,16,"currentColor",2);ne&&(f.replaceChildren(ne),setTimeout(()=>{let te=Ke(Or.Copy,16,"currentColor",2);te&&f.replaceChildren(te)},1500))}).catch(()=>{})}),We.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||(ur=!1,Ti=!0,Io=!0,ja=!0,$.selectArtifact(y),Ho())}),We.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(),ur=!1,Ti=!0,$.selectArtifact(y),Ho())}),We.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 Ei=Qe.composerOverlay,ki=(i,c,f)=>{let y=c.trim();if(!y||!Pt.current)return;let x=i.getAttribute("data-tool-call-id")??"",P=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:P,source:f.source},bubbles:!0,composed:!0})),ia(Ei,x);let Y=Pt.current.getMessages().find(ne=>ne.toolCall?.id===x);Y?.agentMetadata?.awaitingLocalTool?Pt.current.resolveAskUserQuestion(Y,f.structured??y):Pt.current.sendMessage(y)},Ts=i=>{let c=Pt.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:Zd(i,y),currentIndex:Mo(i)})},Zy=i=>Object.entries(i).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),fm=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=Mo(i),f=sa(i);if(c>=f-1)return;let y=Pt.current?.getMessages().find(x=>x.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&(tp(i,y,o,c+1),Ts(i))};Ei.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 P=y.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),ia(Ei,P);let Y=Pt.current?.getMessages().find(ne=>ne.toolCall?.id===P);Y?.agentMetadata?.awaitingLocalTool&&(Pt.current?.markAskUserQuestionResolved(Y),Pt.current?.resolveAskUserQuestion(Y,"(dismissed)"));return}if(x==="pick"){let P=f.getAttribute("data-option-label");if(!P)return;let Y=y.getAttribute("data-multi-select")==="true",ne=ss(y);if(ne&&Y){let te=ni(y)[Mo(y)],oe=new Set(Array.isArray(te)?te:[]);oe.has(P)?oe.delete(P):oe.add(P),is(y,Array.from(oe)),Ts(y);return}if(ne){is(y,P),Ts(y),fm(y);return}if(Y){let te=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",te?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!te);let oe=y.querySelector('[data-ask-user-action="submit-multi"]');oe&&(oe.disabled=qf(y).length===0);return}ki(y,P,{source:"pick",values:[P]});return}if(x==="submit-multi"){let P=qf(y);if(P.length===0)return;ki(y,P.join(", "),{source:"multi",values:P});return}if(x==="open-free-text"){let P=y.querySelector('[data-ask-free-text-row="true"]');P&&(P.classList.remove("persona-hidden"),P.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 Y=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Y.trim())return;if(ss(y)){is(y,Y.trim()),Ts(y),fm(y);return}ki(y,Y,{source:"free-text"});return}if(x==="next"||x==="back"){if(!Pt.current)return;let P=y.getAttribute("data-tool-call-id")??"",Y=Pt.current.getMessages().find(Se=>Se.toolCall?.id===P);if(!Y)return;let te=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(te){let Se=ni(y)[Mo(y)];(typeof Se!="string"||Se!==te)&&is(y,te)}let oe=x==="next"?1:-1,fe=Mo(y)+oe;tp(y,Y,o,fe),Ts(y);return}if(x==="submit-all"){if(!Pt.current)return;let P=y.getAttribute("data-tool-call-id")??"",Y=Pt.current.getMessages().find(Se=>Se.toolCall?.id===P);if(!Y)return;let te=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";te&&is(y,te);let oe=Zd(y,Y);Pt.current.persistAskUserQuestionProgress(Y,{answers:oe,currentIndex:Mo(y)});let fe=Zy(oe);ki(y,fe||"(submitted)",{source:"submit-all",structured:oe});return}if(x==="skip"){if(!Pt.current)return;let P=y.getAttribute("data-tool-call-id")??"",Y=Pt.current.getMessages().find(Re=>Re.toolCall?.id===P);if(!Y)return;let ne=ss(y),te=Mo(y),oe=sa(y),fe=te>=oe-1;if(!ne){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),ia(Ei,P),Y.agentMetadata?.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(Y),Pt.current.resolveAskUserQuestion(Y,"(dismissed)"));return}is(y,"");let Se=y.querySelector('[data-ask-free-text-input="true"]');if(Se&&(Se.value=""),fe){let Re=Zd(y,Y),bt=Zy(Re);ki(y,bt||"(skipped)",{source:"submit-all",structured:Re});return}tp(y,Y,o,te+1),Ts(y);return}}),Ei.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(ss(y)){is(y,x.trim()),Ts(y),fm(y);return}ki(y,x,{source:"free-text"})}});let eb=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=Ei.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),P=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];P&&(i.preventDefault(),P.click())};document.addEventListener("keydown",eb);let jo=null,qt=null,Ka=null,$c=null,Vc=()=>{},tb=!1,zc="",qc="";function gm(){$c?.(),$c=null}let yE=()=>{let i=$i&&js?.isConnected?js:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},nb=()=>{if(!jo||!qt)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){qt.style.removeProperty("position"),qt.style.removeProperty("left"),qt.style.removeProperty("top"),qt.style.removeProperty("bottom"),qt.style.removeProperty("width"),qt.style.removeProperty("z-index");return}let y=jo.firstElementChild;if(!y||y===qt)return;let x=10;qt.style.position="absolute",qt.style.top="0",qt.style.bottom="0",qt.style.width=`${x}px`,qt.style.zIndex="5";let P=Xh(jo,c),Y=y.offsetWidth+P/2-x/2;qt.style.left=`${Math.max(0,Y)}px`},Uc=()=>{},bE=()=>{let i=t.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>f?!1:ue||an(o)},jc=()=>!Un(o)||!Fc()||t.classList.contains("persona-artifact-narrow-host")||bE()||(t.ownerDocument.defaultView??window).innerWidth<TB?"none":Gh(o)?"detached":"welded",Ho=()=>{if(!dt||!Un(o))return;Sc(t,o),Ac(t,o),Uc();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Fe.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let f=Fc();dt.setVisible(f),dt.update(go),ur?(dt.setMobileOpen(!1),dt.element.classList.add("persona-hidden"),dt.backdrop?.classList.add("persona-hidden"),Io=!1,ja=!1):go.artifacts.length>0&&Jy()?(dt.element.classList.remove("persona-hidden"),dt.setMobileOpen(!0)):(dt.setMobileOpen(!1),dt.element.classList.add("persona-hidden"),dt.backdrop?.classList.add("persona-hidden"),Io=!1,ja=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(dt.setExpandToggleVisible(y),dt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),dt.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),dt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),dt.setTabFade(o.features?.artifacts?.layout?.tabFade),dt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!ja&&(Io=!1),Io!==tb){let P=dt.element;Io?(zc=P.style.width,qc=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(zc&&(P.style.width=zc),qc&&(P.style.maxWidth=qc),zc="",qc=""),tb=Io}t.classList.toggle("persona-artifact-expanded",Io),dt.setExpanded(Io);let x=jc();x!==Ua&&(Ua=x,Ms()),Vc()};if(Un(o)){Fe.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(Pe),jo=c,c.appendChild(i),Fe.appendChild(c);let f=x=>{Xy||dt||(dt=x.createArtifactPane(o,{onSelect:P=>Pt.current?.selectArtifact(P),onDismiss:()=>{ur=!0,Ho()},onToggleExpand:()=>{let P=!Io,Y=go.selectedId??go.artifacts[go.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:Y,expanded:P})!==!0&&(Io=P,P||(ja=!1),Ho())}}),dt.element.classList.add("persona-hidden"),c.appendChild(dt.element),dt.backdrop&&Fe.appendChild(dt.backdrop),Vc(),Ho())},y=Rr();y?f(y):(jh(()=>{let x=Rr();x&&f(x)}),$u().catch(()=>{})),Vc=()=>{if(!jo||!dt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ka?.(),Ka=null,gm(),qt&&(qt.remove(),qt=null),dt.element.style.removeProperty("width"),dt.element.style.removeProperty("maxWidth");return}if(!qt){let P=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");P.setAttribute("role","separator"),P.setAttribute("aria-orientation","vertical"),P.setAttribute("aria-label","Resize artifacts panel"),P.tabIndex=0;let Y=t.ownerDocument,ne=Y.defaultView??window,te=oe=>{if(!dt||oe.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||ne.innerWidth<=640)return;oe.preventDefault(),gm();let fe=oe.clientX,Se=dt.element.getBoundingClientRect().width,Re=o.features?.artifacts?.layout,bt=Wt=>{let Sn=jo.getBoundingClientRect().width,mn=t.classList.contains("persona-artifact-welded-split"),nn=Xh(jo,ne),Wn=mn?0:P.getBoundingClientRect().width||6,wt=Se-(Wt.clientX-fe),Bn=XM(wt,Sn,nn,Wn,Re?.resizableMinWidth,Re?.resizableMaxWidth,yE());dt.element.style.width=`${Bn}px`,dt.element.style.maxWidth="none",nb()},Ht=()=>{Y.removeEventListener("pointermove",bt),Y.removeEventListener("pointerup",Ht),Y.removeEventListener("pointercancel",Ht),$c=null;try{P.releasePointerCapture(oe.pointerId)}catch{}};$c=Ht,Y.addEventListener("pointermove",bt),Y.addEventListener("pointerup",Ht),Y.addEventListener("pointercancel",Ht);try{P.setPointerCapture(oe.pointerId)}catch{}};P.addEventListener("pointerdown",te),qt=P,jo.insertBefore(P,dt.element),Ka=()=>{P.removeEventListener("pointerdown",te)}}if(qt){let P=Fc();qt.classList.toggle("persona-hidden",!P),nb()}},Uc=()=>{if(!ue||!dt||(o.launcher?.sidebarMode??!1)||an(o)&&Eo(o).reveal==="emerge")return;let P=t.ownerDocument.defaultView??window,Y=o.launcher?.mobileFullscreen??!0,ne=o.launcher?.mobileBreakpoint??640;if(Y&&P.innerWidth<=ne||!UM(o,ue))return;let te=o.launcher?.width??o.launcherWidth??Pr,oe=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Fc()?(Fe.style.width=oe,Fe.style.maxWidth=oe):(Fe.style.width=te,Fe.style.maxWidth=te)},typeof ResizeObserver<"u"&&(qa=new ResizeObserver(()=>{Ho()}),qa.observe(Fe))}else Fe.appendChild(Pe);ke()&&Yt&&(Qe.peekBanner&&Yt.appendChild(Qe.peekBanner),Yt.appendChild(Be)),t.appendChild(st),Yt&&t.appendChild(Yt);let hm=()=>{if(ke()){Fe.style.width="100%",Fe.style.maxWidth="100%";let Ne=o.launcher?.composerBar??{},it=st.dataset.state==="expanded",Nt=Ne.expandedSize??"anchored";if(!(it&&Nt!=="fullscreen")){Pe.style.background="",Pe.style.border="",Pe.style.borderRadius="",Pe.style.overflow="",Pe.style.boxShadow="";return}let xn=o.theme?.components?.panel,co=ba(o),Js=(Zs,$d)=>Zs==null||Zs===""?$d:Vn(co,Zs)??Zs,sC="1px solid var(--persona-border)",Xt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",If="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Pe.style.background="var(--persona-surface, #ffffff)",Pe.style.border=Js(xn?.border,sC),Pe.style.borderRadius=Js(xn?.borderRadius,If),Pe.style.boxShadow=Js(xn?.shadow,Xt),Pe.style.overflow="hidden";return}let i=an(o),c=o.launcher?.sidebarMode??!1,f=i||c||(o.launcher?.fullHeight??!1),y=o.launcher?.enabled===!1,x=o.launcher?.detachedPanel===!0,P=o.theme?.components?.panel,Y=ba(o),ne=(Ne,it)=>Ne==null||Ne===""?it:Vn(Y,Ne)??Ne,te=t.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,Se=te.innerWidth<=fe,Re=oe&&Se&&ue,bt=i&&oe&&Se,Ht=o.launcher?.position??"bottom-left",Wt=Ht==="bottom-left"||Ht==="top-left",Sn=o.launcher?.zIndex??In,mn="var(--persona-panel-border, 1px solid var(--persona-border))",nn="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Wn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",wt=x&&!Re&&!bt;wt?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Bn=wt?mn:c||Re?"none":mn,Tr=wt?nn:Re?"none":c?Wt?"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":nn;i&&!Re&&!wt&&(Tr="none",Bn="none");let Jo=wt?Wn:c||Re?"0":Wn,Zo=ne(P?.border,Bn),G=ne(P?.shadow,Tr),tt=ne(P?.borderRadius,Jo),ot=jc(),Oe=ot==="detached",_t=ot==="welded";t.classList.toggle("persona-artifact-detached-split",Oe),t.classList.toggle("persona-artifact-welded-split",_t);let vn="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)))))",on=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Un(o)&&Gh(o)&&y&&!i;t.classList.toggle("persona-artifact-chat-flush",on);let ze=Oe||on?"none":G,Cn=Oe?mn:_t?"none":Zo,wn=Oe?Wn:tt;on&&(Cn="none",wn="0");let xo=P?.borderRadius!=null&&P.borderRadius!=="",Ze=on&&!xo?"0":tt,jt=le.scrollTop;t.style.cssText="",st.style.cssText="",Fe.style.cssText="",Pe.style.cssText="",le.style.cssText="",Mi||(Be.style.cssText=""),A&&(le.style.display="none"),(f||y)&&(t.style.minWidth="0");let er=()=>{if(jt<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===jt)return;let it=le.scrollHeight-le.clientHeight;it<=0||(le.scrollTop=Math.min(jt,it))})};if(Re){st.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"),st.style.cssText=`
|
|
1173
|
+
`,B.addEventListener("click",()=>{m=L,I.forEach((W,z)=>{let H=z<L;W.classList.toggle("selected",H),W.setAttribute("aria-checked",z===L-1?"true":"false")})}),I.push(B),S.appendChild(B)}h.appendChild(S);let E=null;if(d){let L=document.createElement("div");L.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),L.appendChild(E),h.appendChild(L)}let O=document.createElement("div");O.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=l,M.addEventListener("click",()=>{n?.(),u.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let L=E?.value.trim()||void 0;await e(m,L),u.remove()}catch(L){D.disabled=!1,D.textContent=a,console.error("[CSAT Feedback] Failed to submit:",L)}}),O.appendChild(M),O.appendChild(D),h.appendChild(O),u.appendChild(h),u}function VT(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 I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let O=document.createElement("span");O.className="persona-feedback-label-low",O.textContent=p;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=u,E.appendChild(O),E.appendChild(M);let D=document.createElement("div");D.className="persona-feedback-numbers";let L=[];for(let w=0;w<=10;w++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-number-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`Rating ${w} out of 10`),k.textContent=String(w),k.dataset.rating=String(w),w<=6?k.classList.add("persona-feedback-detractor"):w<=8?k.classList.add("persona-feedback-passive"):k.classList.add("persona-feedback-promoter"),k.addEventListener("click",()=>{h=w,L.forEach((R,_)=>{R.classList.toggle("selected",_===w),R.setAttribute("aria-checked",_===w?"true":"false")})}),L.push(k),D.appendChild(k)}I.appendChild(E),I.appendChild(D),g.appendChild(I);let B=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),w.appendChild(B),g.appendChild(w)}let W=document.createElement("div");W.className="persona-feedback-actions";let z=document.createElement("button");z.type="button",z.className="persona-feedback-btn persona-feedback-btn-skip",z.textContent=l,z.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){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let w=B?.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)}}),W.appendChild(z),W.appendChild(H),g.appendChild(W),m.appendChild(g),m}var Wa="persona-chat-history",HB=30*1e3,RB=641,Ba="data-persona-composer-reason",WB={"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 BB(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=WB[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 Ju(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 OB(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 DB(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var wy=t=>!t||typeof t!="object"?{}:{...t},zT=t=>t.map(e=>({...e,streaming:!1})),qT=(t,e,n)=>{let o=t?.markdown?Kd(t.markdown):null,r=Yd(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?wC(d):d,g=o(h);m=r&&u?r(g):g}else m=kr(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)),kr(l.text??"")}}};function UT(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=He(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 _B=(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},NB=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:_B(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),jT=(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=Ap(e),r=()=>{rx({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Zh(o);let a=ny.getForInstance(o.plugins),l=_S(t),d=[],p=!1,u=jA(()=>o),m=null,h=null,g=null,b=!1,C=null,S=i=>{m=i,i.initApprovalUi({webMcpToolTitle:Qd});let c=i.createBuiltInApprovalPlugin();h=c.plugin,g=c.teardown},I=()=>{if(m)return m;let i=iM();return i?(S(i),i):(sM().then(c=>{b||m||(S(c),C?.())}).catch(()=>{}),null)},E=!1,O=!1,M=null,D=(i,c,f,y)=>{if(!i.querySelector("[data-tv-form]"))return;let x=aT();if(x){x.enhanceWithForms(i,c,f,y);return}iT().then(()=>{E||O||!M||(O=!0,M())}).catch(()=>{})};o.components&&Fo.registerAll(o.components);let L=pT(),W=o.persistState===!1?null:o.storageAdapter??mT(),z=!!o.clientToken&&typeof o.reconnectStream!="function",H={},w=null,k,R=new Promise(i=>{k=i}),_,X=!1,j=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&&(X=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(W?.load)try{let i=W.load();if(i&&typeof i.then=="function")w=i.then(c=>j(c??{messages:[],metadata:{}}));else{let f=j(i??{messages:[],metadata:{}});f.metadata&&(H=wy(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),_=f.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=j({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}w||k();let Q=()=>H,Z=i=>{H=i({...H})??{},Ri()},ie=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ry],se=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Tc.message,Tc.messageAndClick],pe=sy({parsers:ie,handlers:se,getSessionMetadata:Q,updateSessionMetadata:Z,emit:L.emit,documentRef:typeof document<"u"?document:null});pe.syncFromMetadata();let ue=o.launcher?.enabled??!0,xe=o.launcher?.autoExpand??!1,be=o.autoFocusInput??!1,F=xe,Ce=ue,Ee=o.layout?.header?.layout,Ve=!1,ke=()=>ac(o),Ie=()=>ue||ke(),Te=ke()?!1:ue?xe:!0,bt=!1,Ye=null,Et=()=>{bt=!0,Ye&&clearTimeout(Ye),Ye=setTimeout(()=>{bt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),bt=!1)},1e4)},Ue=qT(o,pe,Et),at=o.features?.showReasoning??!0,Ut=o.features?.showToolCalls??!0,Ht=o.features?.showEventStreamToggle??!1,Qt=o.features?.scrollToBottom??{},_t=o.features?.scrollBehavior??{},Ge=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Nt=`${Ge()}event-stream`,Pt=null,Kn=o.features?.eventStream?.maxEvents??2e3,nt=null,tn=null,dn=null,G=!1,ae=null,A=!1,T=null,V=0,U=(i,c)=>{nt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},ee=(i,c)=>{tn?.processEvent(i,c),nt?U(i,c):dn&&(dn.length>=Kn&&dn.shift(),dn.push({type:i,payload:c}))},me=()=>{nt||!Ht||(dn??(dn=[]),Bh().then(i=>{if(G||nt||!Ht)return;Pt=new i.EventStreamStore(Nt),nt=new i.EventStreamBuffer(Kn,Pt),tn=tn??new i.ThroughputTracker,Pt.open().then(()=>nt?.restore()).catch(f=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let c=dn??[];dn=null;for(let f of c)tn?.processEvent(f.type,f.payload),U(f.type,f.payload)}).catch(()=>{}))};Ht&&me();let J=!1,re=null,Le=()=>{},Me=()=>{},ut=()=>{},lt=()=>{},jt=()=>{},mt=()=>A||J&&re==="panel",Ze={onCopy:i=>{L.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=>{L.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??{},wt=i=>i==="idle"?et.idleText??hn.idle:i==="connecting"?et.connectingText??hn.connecting:i==="connected"?et.connectedText??hn.connected:i==="error"?et.errorText??hn.error:i==="paused"?et.pausedText??hn.paused:i==="resuming"?et.resumingText??hn.resuming:hn[i];function Wn(i,c,f,y){if(!i.hasAttribute(Ba))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 an=UA({config:o,showClose:Ie()}),{wrapper:rt,panel:_e,pillRoot:Xt}=an.shell,Qe=an.panelElements,{container:Pe,body:le,messagesWrapper:We,starterSuggestions:Ci,transcriptSuggestions:_r,suggestions:Po,textarea:Ae,sendButton:Ne,composerForm:Bn,statusText:ft,welcomeHost:pn,welcomeIconHolder:Da,greetingHost:Pn,introKicker:_a,introTitle:em,introSubtitle:tm,closeButton:N,iconHolder:de,headerTitle:Oe,headerSubtitle:Je,header:ve,footer:Be,actionsRow:$o}=Qe,Vo=Qe.leftActions,Nr=Qe.rightActions,zo=Qe.sendButtonWrapper,ky=Qe.setSendButtonMode,ye=Qe.micButton,oo=Qe.micButtonWrapper,Jt=Qe.attachmentButton,Gn=Qe.attachmentButtonWrapper,qt=Qe.attachmentInput,Yn=Qe.attachmentPreviewsContainer;Pe.classList.add("persona-relative"),le.classList.add("persona-relative");let sE=12,Na=()=>Qt.label??"",iE=()=>Qt.iconName??"arrow-down",aE=()=>Qt.enabled!==!1,ro=()=>_t.mode??"anchor-top",Fr=()=>ro()==="follow"||ro()==="anchor-top"&&Ya,Fa=()=>_t.anchorTopOffset??16,lE=()=>_t.restorePosition??"bottom",Ly=()=>_t.pauseOnInteraction===!0,Py=()=>_t.showActivityWhilePinned!==!1,Iy=()=>_t.announce===!0,nm=()=>_t.scrollbar??"on-scroll",un=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");un.type="button",un.style.display="none",un.setAttribute("data-persona-scroll-to-bottom","true");let $a=v("span","persona-flex persona-items-center"),om=v("span",""),xs=v("span","");xs.setAttribute("data-persona-scroll-to-bottom-count",""),xs.style.display="none",un.append($a,om,xs),Pe.appendChild(un);let go=v("div","persona-stream-anchor-spacer");go.setAttribute("aria-hidden","true"),go.setAttribute("data-persona-anchor-spacer",""),go.style.flexShrink="0",go.style.pointerEvents="none",go.style.height="0px",go.style.display="none",le.appendChild(go);let dr=v("div","persona-sr-only");dr.setAttribute("aria-live","polite"),dr.setAttribute("aria-atomic","true"),dr.setAttribute("role","status"),dr.setAttribute("data-persona-live-region",""),Object.assign(dr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Pe.appendChild(dr);let Va=null,Rc=null,Wc=i=>{!Iy()||!i||(Rc=i,Va===null&&(Va=setTimeout(()=>{Va=null,Rc&&Iy()&&(dr.textContent=Rc),Rc=null},400)))},Bc="empty",Oc=0,rm=()=>Oc||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Ss=()=>{let c=Be.style.display==="none"?0:Be.offsetHeight;un.style.bottom=`${c+rm()+sE}px`};Ss();let sm=()=>{Mi||(Be.style.marginBottom=Oc>0?`${Oc}px`:"")},Dc=()=>{let i=Ug(o,ke()),c=Rr(o),y=Be.style.display==="none"?0:Be.offsetHeight,x=c.anchor==="center"&&Bc==="empty"?Ql(c.anchorComposerTop)??Ql("44%"):null,P=x===null||ke()?0:BS({columnHeight:Pe.clientHeight,footerHeight:y,fraction:x});t.style.setProperty("--persona-composer-overlay-height",`${y}px`),t.style.setProperty("--persona-composer-lift",`${i==="overlay"?P:0}px`),Oc=i==="block"?P:0,sm(),Ss()},Hy=()=>{let i=!!Na();un.setAttribute("aria-label",Na()||"Jump to latest"),un.title=Na(),un.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),$a.innerHTML="";let c=He(iE(),"14px","currentColor",2);c?($a.appendChild(c),$a.style.display=""):$a.style.display="none",om.textContent=Na(),om.style.display=i?"":"none"};Hy();let vt=null,ln=null,Fe=Jw(),cE=i=>{try{Pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};Fe.subscribe(cE);let qo=()=>{Fe.setText(Ae?.value??"")},As=()=>{Fe.setMentionRefs(ln?.getMentionRefs()??[])},dE=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}),Ry=i=>{let c=Object.freeze(i.map(dE));Fe.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Im()};Fe.setSelectedModelId(o.composer?.selectedModelId);let za=()=>o.composer?.modes??[],wi=()=>Lx(za(),o.composer?.modeGroups);{let i=Np(o.composer?.defaultActiveModeIds??[],za());i.length&&Fe.setActiveModeIds(i)}function Wy(i){if(Fe.getState().selectedModelId!==i){Fe.setSelectedModelId(i),$r?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function _c(i){Fe.setActiveModeIds(i),pr?.render(i,wi()),xi.forEach(c=>c.repaint()),jo?.resolve(),cd(),Io()}function im(i){_c(Px(Fe.getState().activeModeIds,i,za(),o.composer?.modeGroups))}let $r=null,am=null,pr=null,xi=new Map,Vr=null;function Uo(i){Fe.setQuote(i),Vr?.render(Fe.getState().quote),Io(),Tb()}let By=!1;function lm(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!By&&o.debug===!0&&(By=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let zr=null;function Si(i){Fe.setPendingSubmission(i),zr?.render(Fe.getState().pendingSubmission),Io()}let pE=i=>{let c=xi.get(i);if(c)return c;let f=Rx({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(y=>y.id===i),getModes:()=>za().filter(y=>y.groupId===i),getActiveIds:()=>Fe.getState().activeModeIds,onSelect:y=>im(y)});return xi.set(i,f),f},uE=()=>{let i=[],c=Fe.getState().activeModeIds,f=new Set;if(za().forEach((y,x)=>{if(_p(y.groupId,o.composer?.modeGroups)){let P=y.groupId;if(f.has(P))return;f.add(P);let Y=pE(P);Y.action.order=kg(x),Y.action.label=o.composer?.modeGroups?.find(ne=>ne.id===P)?.label??P,i.push(Y.action);return}i.push({id:Ex(y.id),kind:"button",placement:"start",order:kg(x),presentation:y.presentation??"auto",label:y.label,shortLabel:y.shortLabel,iconName:y.iconName,pressed:c.includes(y.id),onSelect:()=>im(y.id)})}),o.composer?.models?.length&&!a.some(y=>y.renderComposer)){let y=o.composer?.modelPicker?.presentation??"native";(!$r||am!==y)&&(am=y,$r=Mx({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Fe.getState().selectedModelId,onSelect:x=>Wy(x),presentation:y,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push($r.action)}return i},cm=null,Oy=a.find(i=>i.renderHeader);if(Oy?.renderHeader){let i=Oy.renderHeader({config:o,defaultRenderer:()=>{let c=ii({config:o,showClose:Ie()});return cc(Pe,c,o),c.header},onClose:()=>Bt(!1,"user")});if(i){let c=ve;c&&(c.replaceWith(i),ve=i,an.header.element=i)}}let Dy=()=>{ae&&(le.style.display="none",Be.parentNode?.insertBefore(ae.element,Be),ae.update())},dm=()=>{if(!nt){me();return}if(A=!0,ae?Dy():Bh().then(c=>{ae||!A||!nt||(ae=c.createEventStreamView({buffer:nt,getFullHistory:()=>nt.getAllFromStore(),onClose:()=>Ai(),config:o,plugins:a,getThroughput:()=>tn?.getMetric()??{status:"idle"},renderIconByName:He}),Dy())}).catch(()=>{Ai()}),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${qn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&xt.classList.add(f))}let i=()=>{if(!A)return;let c=Date.now();c-V>=200&&(ae?.update(),V=c),T=requestAnimationFrame(i)};V=0,T=requestAnimationFrame(i),Cn(),L.emit("eventStream:opened",{timestamp:Date.now()})},Ai=()=>{if(A){if(A=!1,ae&&ae.element.remove(),le.style.display="",xt){xt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&xt.classList.remove(c))}T!==null&&(cancelAnimationFrame(T),T=null),Cn(),L.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(Ht){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:"");xt=v("button",c),xt.style.width="28px",xt.style.height="28px",xt.style.color=qn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let f=Ke(Dr.Activity,"18px","currentColor",1.5);f&&xt.appendChild(f);let y=Qe.clearChatButtonWrapper,x=Qe.closeButtonWrapper,P=y||x;P&&P.parentNode===ve?ve.insertBefore(xt,P):ve.appendChild(xt),xt.addEventListener("click",()=>{A?Ai():dm()})}let _y=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??Pr).join(","),x.multiple=(c.maxFiles??4)>1,x.style.display="none",x.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(x)}},Mi=!1,Ny=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:()=>Jv(),storage:u(c.id),onSubmit:x=>{!$||$.isStreaming()||Od(x.trim(),{consumeDraft:!1})},streaming:y,disabled:y,openAttachmentPicker:()=>{Qr()||qt?.click()},models:f?.models,selectedModelId:Fe.getState().selectedModelId??f?.selectedModelId,onModelChange:x=>Wy(x),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{cm?.()}:void 0})},Fy=Ny(()=>pc({config:o}).footer);Fy&&(an.replaceComposer(Fy),Be=an.composer.footer,Mi=!0);let St=null,mE=i=>{Bn=i.form,Ae=i.input,zo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ne=i.sendButton),i.micButton&&(ye=i.micButton,oo=i.micButton.parentElement),i.found.status&&(ft=i.found.status),i.found.suggestions&&(Po=i.found.suggestions),i.attachmentButton&&(Jt=i.attachmentButton,Gn=i.attachmentButton.parentElement),qt=i.attachmentInput??null,Yn=i.attachmentPreviews??null,i.found.actionsRow&&($o=i.found.actionsRow),Vo=i.found.actionsStart,Nr=i.found.actionsEnd};function pm(){let i=Ae;if(!i)return;let c=o.composer?.inputAttributes,f=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;Ep(i,c),f&&i.setAttribute("aria-label",f),Tp(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:$l(i)}),dx(i,Mp(o.composer?.maxLines,ke()?5:3))}let $y=i=>{St=ex(i,{debug:o.debug===!0}),St&&mE(St),pm()};_y(Be),$y(Be),qo();let qa=gs(o,ke());qa&&(We.style.maxWidth=qa,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",Pn.style.maxWidth=qa,Pn.style.marginLeft="auto",Pn.style.marginRight="auto",Pn.style.width="100%",Ci.style.maxWidth=qa,_r.style.maxWidth=qa,_r.style.marginLeft="auto",_r.style.marginRight="auto",_r.style.width="100%");let Vy=()=>{let i=gs(o,ke());if(!(!i||ke()))for(let c of[Bn,Po,Yn,ft])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Vy();let zy=()=>{!o.attachments?.enabled||!qt||!Yn||(vt?vt.remountPreviews(Yn):(vt=_l.fromConfig(o.attachments,Ry),vt.setPreviewsContainer(Yn)),St?.addListener(qt,"change",i=>{let c=i.target;vt?.handleFileSelect(c.files),c.value=""}),Pe.querySelector(".persona-attachment-drop-overlay")||Pe.appendChild(UT(o.attachments.dropOverlay)))};zy();let fE=()=>ln?.prefetch(),qy=()=>{if(!o.contextMentions?.enabled||!Ae)return;let i=St?.header??null,c=i?Eg(i):void 0;if(ln=kS({config:o,textarea:Ae,anchor:Bn??Ae,getMessages:()=>$.getMessages(),liveRegionHost:Pe,chipRow:c}),ln&&!c){let f=Ae;f.parentElement?.insertBefore(ln.contextRow,f)}};qy();let jo=null,gE={getState:()=>Fe.getState(),getValue:()=>Ae?.value??"",setValue:i=>{Ae&&(Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),qo())},submit:()=>{Vl(St?.form??null)},openAttachmentPicker:()=>{Qr()||qt?.click()},toggleVoice:()=>{cm?.()},requestRender:()=>jo?.resolve()},hE=()=>{let i=[];return(ln?.affordanceButtons??[]).forEach((f,y)=>{i.push({id:`core:mention-${y}`,placement:"start",order:sr.mention+y,element:f,managed:!0})}),Gn&&i.push({id:"core:attachment",placement:"start",order:sr.attachment,element:Gn}),oo&&i.push({id:"core:mic",placement:"end",order:sr.mic,element:oo}),zo&&i.push({id:"core:send",placement:"end",order:sr.send,element:zo}),i},Uy=()=>{jo?.destroy(),jo=xx({getBindings:()=>St,collect:()=>({builtIns:hE(),configActions:[...uE(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>Fe.getState(),requestRender:()=>jo?.resolve()},debug:o.debug===!0}),actionContext:gE,getState:()=>Fe.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),jo.resolve()};Uy();let um=()=>{if(pr?.destroy(),pr=null,!wi().length)return;let i=St?.header;i&&(pr=Tx({row:Eg(i),onRemove:c=>im(c),initialIds:Fe.getState().activeModeIds}),pr.render(Fe.getState().activeModeIds,wi()))};um();let jy=()=>{Vr?.destroy(),Vr=null,zr?.destroy(),zr=null;let i=St?.header;i&&(Vr=Wx({onDismiss:()=>Uo(void 0)}),i.appendChild(Vr.element),Vr.render(Fe.getState().quote),lm()==="defer-one"&&(zr=Bx({onEdit:()=>qk(),onRemove:()=>Si(void 0)}),i.appendChild(zr.element),zr.render(Fe.getState().pendingSubmission)))};jy();let mm=$x(),yE=()=>{let i=St?.header?.querySelector(Tg);if(i)return i.childElementCount>0;let c=Fe.getState();return c.mentionRefs.length>0||Np(c.activeModeIds,wi()).length>0},Ky=()=>!1;function Io(){let i=Fe.getState(),c=mm.observe(Vx(Ae),i.text);Be.toggleAttribute("data-persona-composer-compact",Fx({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:yE(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:Ky()}))}function Gy(){o.composer?.layout==="single-row"&&!ke()?Be.setAttribute("data-persona-composer-layout","single-row"):Be.removeAttribute("data-persona-composer-layout")}Gy(),Fe.subscribe(()=>{jo?.sync(),Im(),ad(),Io(),Tb()}),ad();let Yy=!1,bE=i=>{if(Yy||o.debug!==!0)return;let c=["messages","composer"].filter(f=>i[f]);c.length&&(Yy=!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??{};bE(i);let c=y=>{switch(y){case"body-top":return le.querySelector("[data-persona-intro-card]");case"messages":return We;case"footer-top":return Po;case"composer":return Bn;case"footer-bottom":return ft;default:return null}},f=(y,x)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")ve.insertBefore(x,ve.firstChild);else if(y==="header-right")ve.appendChild(x);else{let P=ve.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(x,P.nextSibling):ve.appendChild(x)}break;case"body-top":{let P=le.querySelector("[data-persona-intro-card]");P?P.replaceWith(x):le.insertBefore(x,le.firstChild);break}case"body-bottom":le.appendChild(x);break;case"footer-top":Po.replaceWith(x);break;case"footer-bottom":ft.replaceWith(x);break;default:break}};for(let[y,x]of Object.entries(i))if(x)try{let P=x({config:o,defaultContent:()=>c(y)});P&&f(y,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,P)}})();let Qy=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 P=f.getAttribute("data-bubble-type");if(P==="reasoning")Ma.has(x)?Ma.delete(x):Ma.add(x),KA(x,y);else if(P==="tool")Ta.has(x)?Ta.delete(x):Ta.add(x),YA(x,y,o);else if(P==="approval"&&m){let ne=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",te=m.approvalDetailsExpansionState.get(x)??ne;m.approvalDetailsExpansionState.set(x,!te),m.updateApprovalDetailsUI(x,y,o)}mn.delete(x)};We.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Qy(i))}),We.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Qy(i))}),We.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let f=We.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let x=y.toString(),P=FS(x);!P||P===x||(c.setData("text/plain",P),i.preventDefault())});let fm=new Map,Xy=null,Jy="idle",vE={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},CE=(i,c)=>{let{icon:f,label:y}=vE[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=He(f,14,"currentColor",2);x&&(i.innerHTML="",i.appendChild(x))},Zy=()=>{We.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let y=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;CE(c,y&&y===Xy?Jy:"idle")})};We.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 P=f.getAttribute("data-action");if(P==="copy"){let ne=$.getMessages().find(te=>te.id===x);if(ne&&Ze.onCopy){let te=ne.content||"";navigator.clipboard.writeText(te).then(()=>{f.classList.add("persona-message-action-success");let oe=Ke(Dr.Check,14,"currentColor",2);oe&&(f.innerHTML="",f.appendChild(oe)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let fe=Ke(Dr.Copy,14,"currentColor",2);fe&&(f.innerHTML="",f.appendChild(fe))},2e3)}).catch(oe=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",oe)}),Ze.onCopy(ne)}}else if(P==="read-aloud")$.toggleReadAloud(x);else if(P==="upvote"||P==="downvote"){let ne=(fm.get(x)??null)===P,te=P==="upvote"?"thumbs-up":"thumbs-down";if(ne){fm.delete(x),f.classList.remove("persona-message-action-active");let oe=He(te,14,"currentColor",2);oe&&(f.innerHTML="",f.appendChild(oe))}else{let oe=P==="upvote"?"downvote":"upvote",fe=y.querySelector(`[data-action="${oe}"]`);if(fe){fe.classList.remove("persona-message-action-active");let Ot=He(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ot&&(fe.innerHTML="",fe.appendChild(Ot))}fm.set(x,P),f.classList.add("persona-message-action-active");let Se=He(te,14,"currentColor",2);Se&&(Se.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(Se)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let yt=$.getMessages().find(Rt=>Rt.id===x);yt&&Ze.onFeedback&&Ze.onFeedback({type:P,messageId:yt.id,message:yt})}}else if(P==="regenerate")Nc?.regenerate(x);else if(P==="edit")Nc?.edit(x);else if(P==="quote")Nc?.quote(x);else if(P?.startsWith(vu)){let Y=P.slice(vu.length),ne=o.messageActions?.custom?.find(oe=>oe.id===Y),te=$.getMessages().find(oe=>oe.id===x);if(!ne||!te)return;try{ne.onSelect(te)}catch(oe){console.error(`[AgentWidget] messageActions.custom "${Y}" onSelect failed:`,oe)}}});let Nc=null;We.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 P=f.getAttribute("data-approval-action");if(!P)return;let Y=P==="approve"?"approved":"denied",te=$.getMessages().find(fe=>fe.id===x);if(!te?.approval)return;let oe=y.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(Se=>{Se.disabled=!0,Se.style.opacity="0.5",Se.style.cursor="not-allowed"}),te.approval.toolType==="webmcp"?$.resolveWebMcpApproval(x,Y):$.resolveApproval(te.approval,Y)});let ct=null,eb=!1,Ua=null,Ms=()=>{},ja="none",Fc=null,ho={artifacts:[],selectedId:null},ur=!1,Ho=!1,Ka=!1,Ti=!1,tb=()=>Ti||ho.artifacts.some(i=>os(o.features?.artifacts,i)==="panel"),$c=()=>ho.artifacts.length>0&&!ur&&tb(),It={current:null},gm=(i,c)=>{let f=$.getArtifactById(c),y=f?.markdown,x=f?.title||"artifact",P=f?.file,Y=f?.artifactType??"markdown";if(!y){let oe=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(oe){let Se=$.getMessages().find(Re=>Re.id===oe);if(Se?.rawContent)try{let Re=JSON.parse(Se.rawContent);y=Re?.props?.markdown,x=Re?.props?.title||x,Re?.props?.file&&typeof Re.props.file=="object"&&(P=Re.props.file),!f&&typeof Re?.props?.artifactType=="string"&&(Y=Re.props.artifactType)}catch{}}}return{markdown:y,title:x,file:P,artifactType:Y}};We.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:P,title:Y,file:ne}=gm(f,y);if(!P)return;let te=Wr();te&&te.triggerArtifactDownload(te.downloadInfoFor({title:Y,markdown:P,file:ne}))}),We.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]"),P=x?null:f.closest("[data-open-artifact]"),Y=x?x.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,te=(x?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Rt=>Rt.id===y);if(!te)return;let{markdown:oe,title:fe,file:Se,artifactType:Re}=gm(f,Y??""),yt={artifactId:Y,title:fe,artifactType:Re,markdown:oe,file:Se};try{Promise.resolve(te.onClick(yt)).catch(()=>{})}catch{}}),We.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),P=Wr();if(!P)return;let Y="";if(x)Y=P.artifactCopyText(x);else{let{markdown:ne,file:te,artifactType:oe}=gm(f,y);oe==="markdown"&&(Y=P.artifactCopyText({id:y,artifactType:"markdown",status:"complete",markdown:ne??"",...te?{file:te}:{}}))}Y&&navigator.clipboard.writeText(Y).then(()=>{let ne=Ke(Dr.Check,16,"currentColor",2);ne&&(f.replaceChildren(ne),setTimeout(()=>{let te=Ke(Dr.Copy,16,"currentColor",2);te&&f.replaceChildren(te)},1500))}).catch(()=>{})}),We.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||(ur=!1,Ti=!0,Ho=!0,Ka=!0,$.selectArtifact(y),Ro())}),We.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(),ur=!1,Ti=!0,$.selectArtifact(y),Ro())}),We.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 Ei=Qe.composerOverlay,ki=(i,c,f)=>{let y=c.trim();if(!y||!It.current)return;let x=i.getAttribute("data-tool-call-id")??"",P=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:P,source:f.source},bubbles:!0,composed:!0})),aa(Ei,x);let Y=It.current.getMessages().find(ne=>ne.toolCall?.id===x);Y?.agentMetadata?.awaitingLocalTool?It.current.resolveAskUserQuestion(Y,f.structured??y):It.current.sendMessage(y)},Ts=i=>{let c=It.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:tp(i,y),currentIndex:To(i)})},nb=i=>Object.entries(i).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),hm=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=To(i),f=ia(i);if(c>=f-1)return;let y=It.current?.getMessages().find(x=>x.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&(op(i,y,o,c+1),Ts(i))};Ei.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 P=y.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),aa(Ei,P);let Y=It.current?.getMessages().find(ne=>ne.toolCall?.id===P);Y?.agentMetadata?.awaitingLocalTool&&(It.current?.markAskUserQuestionResolved(Y),It.current?.resolveAskUserQuestion(Y,"(dismissed)"));return}if(x==="pick"){let P=f.getAttribute("data-option-label");if(!P)return;let Y=y.getAttribute("data-multi-select")==="true",ne=ss(y);if(ne&&Y){let te=ni(y)[To(y)],oe=new Set(Array.isArray(te)?te:[]);oe.has(P)?oe.delete(P):oe.add(P),is(y,Array.from(oe)),Ts(y);return}if(ne){is(y,P),Ts(y),hm(y);return}if(Y){let te=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",te?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!te);let oe=y.querySelector('[data-ask-user-action="submit-multi"]');oe&&(oe.disabled=jf(y).length===0);return}ki(y,P,{source:"pick",values:[P]});return}if(x==="submit-multi"){let P=jf(y);if(P.length===0)return;ki(y,P.join(", "),{source:"multi",values:P});return}if(x==="open-free-text"){let P=y.querySelector('[data-ask-free-text-row="true"]');P&&(P.classList.remove("persona-hidden"),P.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 Y=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Y.trim())return;if(ss(y)){is(y,Y.trim()),Ts(y),hm(y);return}ki(y,Y,{source:"free-text"});return}if(x==="next"||x==="back"){if(!It.current)return;let P=y.getAttribute("data-tool-call-id")??"",Y=It.current.getMessages().find(Se=>Se.toolCall?.id===P);if(!Y)return;let te=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(te){let Se=ni(y)[To(y)];(typeof Se!="string"||Se!==te)&&is(y,te)}let oe=x==="next"?1:-1,fe=To(y)+oe;op(y,Y,o,fe),Ts(y);return}if(x==="submit-all"){if(!It.current)return;let P=y.getAttribute("data-tool-call-id")??"",Y=It.current.getMessages().find(Se=>Se.toolCall?.id===P);if(!Y)return;let te=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";te&&is(y,te);let oe=tp(y,Y);It.current.persistAskUserQuestionProgress(Y,{answers:oe,currentIndex:To(y)});let fe=nb(oe);ki(y,fe||"(submitted)",{source:"submit-all",structured:oe});return}if(x==="skip"){if(!It.current)return;let P=y.getAttribute("data-tool-call-id")??"",Y=It.current.getMessages().find(Re=>Re.toolCall?.id===P);if(!Y)return;let ne=ss(y),te=To(y),oe=ia(y),fe=te>=oe-1;if(!ne){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),aa(Ei,P),Y.agentMetadata?.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Y),It.current.resolveAskUserQuestion(Y,"(dismissed)"));return}is(y,"");let Se=y.querySelector('[data-ask-free-text-input="true"]');if(Se&&(Se.value=""),fe){let Re=tp(y,Y),yt=nb(Re);ki(y,yt||"(skipped)",{source:"submit-all",structured:Re});return}op(y,Y,o,te+1),Ts(y);return}}),Ei.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(ss(y)){is(y,x.trim()),Ts(y),hm(y);return}ki(y,x,{source:"free-text"})}});let ob=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=Ei.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),P=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];P&&(i.preventDefault(),P.click())};document.addEventListener("keydown",ob);let Ko=null,Kt=null,Ga=null,Vc=null,zc=()=>{},rb=!1,qc="",Uc="";function ym(){Vc?.(),Vc=null}let wE=()=>{let i=$i&&js?.isConnected?js:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},sb=()=>{if(!Ko||!Kt)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){Kt.style.removeProperty("position"),Kt.style.removeProperty("left"),Kt.style.removeProperty("top"),Kt.style.removeProperty("bottom"),Kt.style.removeProperty("width"),Kt.style.removeProperty("z-index");return}let y=Ko.firstElementChild;if(!y||y===Kt)return;let x=10;Kt.style.position="absolute",Kt.style.top="0",Kt.style.bottom="0",Kt.style.width=`${x}px`,Kt.style.zIndex="5";let P=ey(Ko,c),Y=y.offsetWidth+P/2-x/2;Kt.style.left=`${Math.max(0,Y)}px`},jc=()=>{},xE=()=>{let i=t.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>f?!1:ue||cn(o)},Kc=()=>!jn(o)||!$c()||t.classList.contains("persona-artifact-narrow-host")||xE()||(t.ownerDocument.defaultView??window).innerWidth<RB?"none":Xh(o)?"detached":"welded",Ro=()=>{if(!ct||!jn(o))return;Ac(t,o),Mc(t,o),jc();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=$c();ct.setVisible(f),ct.update(ho),ur?(ct.setMobileOpen(!1),ct.element.classList.add("persona-hidden"),ct.backdrop?.classList.add("persona-hidden"),Ho=!1,Ka=!1):ho.artifacts.length>0&&tb()?(ct.element.classList.remove("persona-hidden"),ct.setMobileOpen(!0)):(ct.setMobileOpen(!1),ct.element.classList.add("persona-hidden"),ct.backdrop?.classList.add("persona-hidden"),Ho=!1,Ka=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(ct.setExpandToggleVisible(y),ct.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),ct.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),ct.setCustomActions(o.features?.artifacts?.toolbarActions??[]),ct.setTabFade(o.features?.artifacts?.layout?.tabFade),ct.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!Ka&&(Ho=!1),Ho!==rb){let P=ct.element;Ho?(qc=P.style.width,Uc=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(qc&&(P.style.width=qc),Uc&&(P.style.maxWidth=Uc),qc="",Uc=""),rb=Ho}t.classList.toggle("persona-artifact-expanded",Ho),ct.setExpanded(Ho);let x=Kc();x!==ja&&(ja=x,Ms()),zc()};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(Pe),Ko=c,c.appendChild(i),_e.appendChild(c);let f=x=>{eb||ct||(ct=x.createArtifactPane(o,{onSelect:P=>It.current?.selectArtifact(P),onDismiss:()=>{ur=!0,Ro()},onToggleExpand:()=>{let P=!Ho,Y=ho.selectedId??ho.artifacts[ho.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:Y,expanded:P})!==!0&&(Ho=P,P||(Ka=!1),Ro())}}),ct.element.classList.add("persona-hidden"),c.appendChild(ct.element),ct.backdrop&&_e.appendChild(ct.backdrop),zc(),Ro())},y=Wr();y?f(y):(Yh(()=>{let x=Wr();x&&f(x)}),zu().catch(()=>{})),zc=()=>{if(!Ko||!ct)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ga?.(),Ga=null,ym(),Kt&&(Kt.remove(),Kt=null),ct.element.style.removeProperty("width"),ct.element.style.removeProperty("maxWidth");return}if(!Kt){let P=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");P.setAttribute("role","separator"),P.setAttribute("aria-orientation","vertical"),P.setAttribute("aria-label","Resize artifacts panel"),P.tabIndex=0;let Y=t.ownerDocument,ne=Y.defaultView??window,te=oe=>{if(!ct||oe.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||ne.innerWidth<=640)return;oe.preventDefault(),ym();let fe=oe.clientX,Se=ct.element.getBoundingClientRect().width,Re=o.features?.artifacts?.layout,yt=Ot=>{let Sn=Ko.getBoundingClientRect().width,gn=t.classList.contains("persona-artifact-welded-split"),rn=ey(Ko,ne),On=gn?0:P.getBoundingClientRect().width||6,Ct=Se-(Ot.clientX-fe),Dn=tT(Ct,Sn,rn,On,Re?.resizableMinWidth,Re?.resizableMaxWidth,wE());ct.element.style.width=`${Dn}px`,ct.element.style.maxWidth="none",sb()},Rt=()=>{Y.removeEventListener("pointermove",yt),Y.removeEventListener("pointerup",Rt),Y.removeEventListener("pointercancel",Rt),Vc=null;try{P.releasePointerCapture(oe.pointerId)}catch{}};Vc=Rt,Y.addEventListener("pointermove",yt),Y.addEventListener("pointerup",Rt),Y.addEventListener("pointercancel",Rt);try{P.setPointerCapture(oe.pointerId)}catch{}};P.addEventListener("pointerdown",te),Kt=P,Ko.insertBefore(P,ct.element),Ga=()=>{P.removeEventListener("pointerdown",te)}}if(Kt){let P=$c();Kt.classList.toggle("persona-hidden",!P),sb()}},jc=()=>{if(!ue||!ct||(o.launcher?.sidebarMode??!1)||cn(o)&&ko(o).reveal==="emerge")return;let P=t.ownerDocument.defaultView??window,Y=o.launcher?.mobileFullscreen??!0,ne=o.launcher?.mobileBreakpoint??640;if(Y&&P.innerWidth<=ne||!YM(o,ue))return;let te=o.launcher?.width??o.launcherWidth??Ir,oe=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";$c()?(_e.style.width=oe,_e.style.maxWidth=oe):(_e.style.width=te,_e.style.maxWidth=te)},typeof ResizeObserver<"u"&&(Ua=new ResizeObserver(()=>{Ro()}),Ua.observe(_e))}else _e.appendChild(Pe);ke()&&Xt&&(Qe.peekBanner&&Xt.appendChild(Qe.peekBanner),Xt.appendChild(Be)),t.appendChild(rt),Xt&&t.appendChild(Xt);let bm=()=>{if(ke()){_e.style.width="100%",_e.style.maxWidth="100%";let ot=o.launcher?.composerBar??{},Ft=rt.dataset.state==="expanded",At=ot.expandedSize??"anchored";if(!(Ft&&At!=="fullscreen")){Pe.style.background="",Pe.style.border="",Pe.style.borderRadius="",Pe.style.overflow="",Pe.style.boxShadow="";return}let $t=o.theme?.components?.panel,Er=va(o),An=(Zs,Vd)=>Zs==null||Zs===""?Vd:zn(Er,Zs)??Zs,So="1px solid var(--persona-border)",Vt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Rf="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Pe.style.background="var(--persona-surface, #ffffff)",Pe.style.border=An($t?.border,So),Pe.style.borderRadius=An($t?.borderRadius,Rf),Pe.style.boxShadow=An($t?.shadow,Vt),Pe.style.overflow="hidden";return}let i=cn(o),c=o.launcher?.sidebarMode??!1,f=i||c||(o.launcher?.fullHeight??!1),y=o.launcher?.enabled===!1,x=o.launcher?.detachedPanel===!0,P=o.theme?.components?.panel,Y=va(o),ne=(ot,Ft)=>ot==null||ot===""?Ft:zn(Y,ot)??ot,te=t.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,Se=te.innerWidth<=fe,Re=oe&&Se&&ue,yt=i&&oe&&Se,Rt=o.launcher?.position??"bottom-left",Ot=Rt==="bottom-left"||Rt==="top-left",Sn=o.launcher?.zIndex??Rn,gn="var(--persona-panel-border, 1px solid var(--persona-border))",rn="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",On="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ct=x&&!Re&&!yt;Ct?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Dn=Ct?gn:c||Re?"none":gn,Zo=Ct?rn:Re?"none":c?Ot?"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":rn;i&&!Re&&!Ct&&(Zo="none",Dn="none");let Tr=Ct?On:c||Re?"0":On,er=ne(P?.border,Dn),Ji=ne(P?.shadow,Zo),Js=ne(P?.borderRadius,Tr),K=Kc(),ze=K==="detached",Xe=K==="welded";t.classList.toggle("persona-artifact-detached-split",ze),t.classList.toggle("persona-artifact-welded-split",Xe);let $e="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",Lt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&jn(o)&&Xh(o)&&y&&!i;t.classList.toggle("persona-artifact-chat-flush",Lt);let je=ze||Lt?"none":Ji,Oo=ze?gn:Xe?"none":er,Zt=ze?On:Js;Lt&&(Oo="none",Zt="0");let In=P?.borderRadius!=null&&P.borderRadius!=="",xn=Lt&&!In?"0":Js,sn=le.scrollTop;t.style.cssText="",rt.style.cssText="",_e.style.cssText="",Pe.style.cssText="",le.style.cssText="",Mi||(Be.style.cssText=""),A&&(le.style.display="none"),(f||y)&&(t.style.minWidth="0");let tt=()=>{if(sn<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===sn)return;let Ft=le.scrollHeight-le.clientHeight;Ft<=0||(le.scrollTop=Math.min(sn,Ft))})};if(Re){rt.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"),rt.style.cssText=`
|
|
1174
1174
|
position: fixed !important;
|
|
1175
1175
|
inset: 0 !important;
|
|
1176
1176
|
width: 100% !important;
|
|
@@ -1182,7 +1182,7 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1182
1182
|
flex-direction: column !important;
|
|
1183
1183
|
z-index: ${Sn} !important;
|
|
1184
1184
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
1185
|
-
`,
|
|
1185
|
+
`,_e.style.cssText=`
|
|
1186
1186
|
position: relative !important;
|
|
1187
1187
|
display: flex !important;
|
|
1188
1188
|
flex-direction: column !important;
|
|
@@ -1206,11 +1206,11 @@ _Details: ${n.message}_`:o}var ag=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
|
-
`,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",Be.style.flexShrink="0",
|
|
1209
|
+
`,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",Be.style.flexShrink="0",sm(),Ve=!0,tt();return}let it=o?.launcher?.width??o?.launcherWidth??Ir;if(!c&&!i)y&&f?(_e.style.width="100%",_e.style.maxWidth="100%"):(_e.style.width=it,_e.style.maxWidth=it);else if(i)if(ko(o).reveal==="emerge"&&!x){let Ft=ko(o).width;_e.style.width=Ft,_e.style.maxWidth=Ft}else _e.style.width="100%",_e.style.maxWidth="100%";if(jc(),_e.style.boxShadow=je,_e.style.borderRadius=xn,ze?_e.style.border="none":Xe&&(_e.style.border=er),Pe.style.border=Oo,Pe.style.borderRadius=Zt,Pe.style.boxShadow=ze&&!Lt?$e:"",Lt&&(Pe.style.background="transparent",le.style.background="transparent",Be.style.background="transparent",Be.style.borderTop="none"),Xe){let ot=o.features?.artifacts?.layout;Fc=ot?.unifiedSplitOuterRadius?.trim()||ot?.paneBorderRadius?.trim()||Js}else Fc=null;if(i&&!Re&&!Ct&&!ze&&!Xe&&P?.border===void 0&&(Pe.style.border="none",ko(o).side==="right"?Pe.style.borderLeft="1px solid var(--persona-border)":Pe.style.borderRight="1px solid var(--persona-border)"),i&&!Re&&Xe&&P?.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%"),rt.style.display="flex",rt.style.flexDirection="column",rt.style.flex="1 1 0%",rt.style.minHeight="0",rt.style.maxHeight="100%",rt.style.height="100%",y&&(rt.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%",ze||(_e.style.overflow="hidden"),Pe.style.display="flex",Pe.style.flexDirection="column",Pe.style.flex="1 1 0%",Pe.style.minHeight="0",Pe.style.maxHeight="100%",Pe.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",Be.style.flexShrink="0"),y&&(Ct||ze||Lt)&&!i&&(Lt||(rt.style.padding="var(--persona-panel-inset)"),rt.style.background="var(--persona-panel-canvas-bg)"),rt.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&&(mo[Rt]??mo["bottom-right"]).split(" ").forEach(Ft=>rt.classList.add(Ft)),c){let ot=o.launcher?.sidebarWidth??"420px";x?rt.style.cssText=`
|
|
1210
1210
|
position: fixed !important;
|
|
1211
1211
|
top: var(--persona-panel-inset) !important;
|
|
1212
1212
|
bottom: var(--persona-panel-inset) !important;
|
|
1213
|
-
width: ${
|
|
1213
|
+
width: ${ot} !important;
|
|
1214
1214
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
1215
1215
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
1216
1216
|
margin: 0 !important;
|
|
@@ -1218,12 +1218,12 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1218
1218
|
display: flex !important;
|
|
1219
1219
|
flex-direction: column !important;
|
|
1220
1220
|
z-index: ${Sn} !important;
|
|
1221
|
-
${
|
|
1222
|
-
`:
|
|
1221
|
+
${Ot?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
1222
|
+
`:rt.style.cssText=`
|
|
1223
1223
|
position: fixed !important;
|
|
1224
1224
|
top: 0 !important;
|
|
1225
1225
|
bottom: 0 !important;
|
|
1226
|
-
width: ${
|
|
1226
|
+
width: ${ot} !important;
|
|
1227
1227
|
height: 100vh !important;
|
|
1228
1228
|
max-height: 100vh !important;
|
|
1229
1229
|
margin: 0 !important;
|
|
@@ -1231,8 +1231,8 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1231
1231
|
display: flex !important;
|
|
1232
1232
|
flex-direction: column !important;
|
|
1233
1233
|
z-index: ${Sn} !important;
|
|
1234
|
-
${
|
|
1235
|
-
`,
|
|
1234
|
+
${Ot?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
1235
|
+
`,_e.style.cssText=`
|
|
1236
1236
|
position: relative !important;
|
|
1237
1237
|
display: flex !important;
|
|
1238
1238
|
flex-direction: column !important;
|
|
@@ -1243,10 +1243,10 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1243
1243
|
min-height: 0 !important;
|
|
1244
1244
|
margin: 0 !important;
|
|
1245
1245
|
padding: 0 !important;
|
|
1246
|
-
box-shadow: ${
|
|
1247
|
-
border-radius: ${
|
|
1248
|
-
${
|
|
1249
|
-
`,
|
|
1246
|
+
box-shadow: ${je} !important;
|
|
1247
|
+
border-radius: ${xn} !important;
|
|
1248
|
+
${ze?"border: none !important;":Xe?`border: ${er} !important;`:""}
|
|
1249
|
+
`,_e.style.setProperty("width","100%","important"),_e.style.setProperty("max-width","100%","important"),Pe.style.cssText=`
|
|
1250
1250
|
display: flex !important;
|
|
1251
1251
|
flex-direction: column !important;
|
|
1252
1252
|
flex: 1 1 0% !important;
|
|
@@ -1255,16 +1255,16 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1255
1255
|
min-height: 0 !important;
|
|
1256
1256
|
max-height: 100% !important;
|
|
1257
1257
|
overflow: hidden !important;
|
|
1258
|
-
border-radius: ${
|
|
1259
|
-
border: ${
|
|
1260
|
-
${
|
|
1261
|
-
${
|
|
1258
|
+
border-radius: ${Zt} !important;
|
|
1259
|
+
border: ${Oo} !important;
|
|
1260
|
+
${ze&&!Lt?`box-shadow: ${$e} !important;`:""}
|
|
1261
|
+
${Lt?"background: transparent !important;":""}
|
|
1262
1262
|
`,Mi||(Be.style.cssText=`
|
|
1263
1263
|
flex-shrink: 0 !important;
|
|
1264
1264
|
border-top: none !important;
|
|
1265
1265
|
padding: 8px 16px 12px 16px !important;
|
|
1266
|
-
${
|
|
1267
|
-
`)}if(!y&&!i){let Ne="max-height: -moz-available !important; max-height: stretch !important;",it=c?"":"padding-top: 1.25em !important;",Nt=c?"":`z-index: ${o.launcher?.zIndex??In} !important;`;st.style.cssText+=Ne+it+Nt}om(),er()},ym=()=>{t.style.setProperty("--persona-content-max-width",gs(o,ke()))},ob=!1,rb=()=>{let i=zg(o,ke());ke()&&o.composer?.placement&&o.debug===!0&&!ob&&(ob=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=Hr(o);t.setAttribute("data-persona-composer-placement",i),t.setAttribute("data-persona-conversation-state",Wc),t.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",c.composerGap??tu),Oc()},sb=()=>{if(ke())return;let i=an(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!ue)return;let y=t.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=P)return;let Y=y.innerHeight,ne=64,te=o.launcher?.heightOffset??0,oe=Math.max(200,Y-ne),fe=Math.min(640,oe);Fe.style.height=`${Math.max(200,fe-te)}px`};hm(),Gl(t,o),Sc(t,o),Ac(t,o),ym(),rb(),Ms=()=>{hm(),sb(),Gl(t,o),Sc(t,o),Ac(t,o),ym(),rb(),Nc?t.style.setProperty("--persona-artifact-welded-outer-radius",Nc):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Me(),Le()};let _e=[];_e.push(()=>{Xy=!0}),_e.push(()=>{d.forEach(i=>i()),l.destroy()}),_e.push(()=>{document.removeEventListener("keydown",eb)}),_e.push(()=>{$a!==null&&clearTimeout($a)});let Ko=null,Go=null;_e.push(()=>{Ko?.(),Ko=null,Go?.(),Go=null}),qa&&_e.push(()=>{qa?.disconnect(),qa=null}),_e.push(()=>{Ka?.(),Ka=null,gm(),qt&&(qt.remove(),qt=null),dt?.element.style.removeProperty("width"),dt?.element.style.removeProperty("maxWidth"),dt?.destroy()}),It&&_e.push(()=>{K=!0,ln=null,T!==null&&(cancelAnimationFrame(T),T=null),ae?.destroy(),ae=null,rt?.destroy(),rt=null,Lt=null});let Es=null,ib=()=>{Es&&(Es(),Es=null),o.colorScheme==="auto"&&(Es=eu(()=>{Gl(t,o)}))};ib(),_e.push(()=>{Es&&(Es(),Es=null)}),_e.push(()=>{b=!0,g?.()}),_e.push(()=>{E=!0});let ab=!1;_e.push(()=>{ab=!0});let bm=(i,c)=>{let f=Jl(i,c);return f||!GS.includes(i)?f:(mA().then(y=>{if(ab)return;ri(y.wipe),ri(y.glyphCycle);let x=Jl(i,c);x&&tc(x,t)}).catch(()=>{}),null)},Kc=o.features?.streamAnimation;if(Kc?.type&&Kc.type!=="none"){let i=bm(Kc.type,Kc.plugins);i&&tc(i,t),_e.push(()=>YS(t))}let mr=ac(Lo),lb=ac(Ci),cb=ac(Dr),ks=[mr,lb,cb];_e.push(()=>{ks.forEach(i=>i.destroy())});let Ls=null,$,Ps=null,db=!1,pb=0,ub=null,mb=i=>i.reduce((c,f)=>f.role==="user"?c+1:c,0),fb=i=>{for(let c=i.length-1;c>=0;c--)if(Tl(i[c]))return i[c].id??null;return null},gb=!1,vE=()=>{gb||o.debug!==!0||(gb=!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".'))},hb=!1,yb=!1,bb=(i,c)=>{hb||o.debug!==!0||!c.enabled||c.expose||db||yb&&($.isStreaming()||i.some(Tl)||(hb=!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.")))},Li=i=>{if(!$)return;let c=i??$.getMessages(),f=oe=>{oe.render([],$,Ae,c)},y=oe=>{ks.forEach(fe=>{fe!==oe&&f(fe)})};Ps&&(mb(c)>pb||fb(c)!==ub)&&(Ps=null);let x=ls(o);bb(c,x);let P=x.enabled?JC(c):null,Y=Ps??P,ne=Ps?"host":"agent";if(Y){let oe=o.suggestions?.followUps,fe=oe?.placement??(oe?"auto":"composer"),Re=(fe==="auto"?ke()?"composer":"after-message":fe)==="after-message"?cb:mr;y(Re),Re.render(Y,$,Ae,c,o.suggestionChipsConfig,{source:ne,surface:"followUp",variant:oe?.variant??"chip",behavior:oe?.behavior??"send",overflow:oe?.overflow??"wrap",maxItems:oe?.maxItems??4,config:o,plugins:a,submitPrompt:Wd});return}if(c.some(oe=>oe.role==="user")){ks.forEach(f);return}let te=o.suggestions?.starters;if(te){let oe=Sa(Hr(o),c),fe=te.placement??"auto",Se=fe==="auto"?oe?"welcome":"composer":fe;if(Se==="welcome"&&!oe){vE(),ks.forEach(f);return}let Re=Se==="welcome"?lb:mr;y(Re),Re.render(te.items??o.suggestionChips,$,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:te.variant??"card",behavior:te.behavior??"send",overflow:te.overflow??"wrap",maxItems:te.maxItems??4,config:o,plugins:a,submitPrompt:Wd});return}y(mr),mr.render(o.suggestionChips,$,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Wd})},vb=()=>{Ps&&(Ps=null,Li())},CE=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){vb();return}let f=$?$.getMessages():[];Ps=c,db=!0,pb=mb(f),ub=fb(f),Li(f)},ro=!1,pn=FS(),Pi=new Map,Is=new Map,zr=new Map,Hs=null,qr=null;function Rs(){if(!Hs)return;let i=Hs;Hs=null,qr?.destroy(),qr=null,pn.delete(i),Pe.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),$&&ho(We,$.getMessages(),je)}let Ws=0,wE=So()!==null,so=iu(),io=0,Ur=null,Yn=!1,Gc=!1,jr=0,yn=null,Bs=null,vm=!1,Ii=!1,Os=null,Ga=!0,Yc=!1,Hi=null,Qc=!1,Ds=()=>{Qc=!0,ME()},Cm=null,xE=4,fr=24,SE=80,AE=1e3,gr=null,Cb=()=>{t.setAttribute("data-persona-scrollbar",em()),em()!=="on-scroll"&&(gr!==null&&clearTimeout(gr),gr=null,le.removeAttribute("data-persona-scrollbar-visible"))},ME=()=>{em()==="on-scroll"&&(le.setAttribute("data-persona-scrollbar-visible",""),gr!==null&&clearTimeout(gr),gr=setTimeout(()=>{gr=null,Ir(le,fr)&&le.removeAttribute("data-persona-scrollbar-visible")},AE))};Cb(),_e.push(()=>{gr!==null&&clearTimeout(gr)});let wm=new Map,pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};qy=()=>pt.active,Po();let wb=o.voiceRecognition?.autoResume??!1,hr=i=>{L.emit("voice:state",{active:pt.active,source:i,timestamp:Date.now()})},Ro=()=>{Z(i=>({...i,voiceState:{active:pt.active,timestamp:Date.now(),manuallyDeactivated:pt.manuallyDeactivated}}))},TE=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=by(H.voiceState),c=!!i.active,f=Number(i.timestamp??0);pt.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-f<MB&&setTimeout(()=>{pt.active||(pt.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),hr("restore"),$.isVoiceActive()&&Qi()}):Dd("restore"))},1e3)},EE=()=>$?NT($.getMessages()).filter(i=>!i.__skipPersist):[],Xc=null,xb=(i,c)=>{typeof console<"u"&&console.error(i,c)},Jc=(i,c)=>{let f=()=>{try{let Y=i();return!Y||typeof Y.then!="function"?null:Promise.resolve(Y).catch(ne=>{xb(c,ne)})}catch(Y){return xb(c,Y),null}},y=Xc,x=y?y.then(()=>f()??void 0):f();if(!x)return;let P=x.finally(()=>{Xc===P&&(Xc=null)});Xc=P};function Ri(i){if(!W?.save)return;let c=i?NT(i):$?EE():[],f=z&&$?.getResumableHandle();f&&(H={...H,durableResume:{executionId:f.executionId,after:f.lastEventId}});let y={messages:c,metadata:H,artifacts:go.artifacts,selectedArtifactId:go.selectedId,..._s?{draft:_s}:{}};Jc(()=>W.save(y),"[AgentWidget] Failed to persist state:")}let _s,Zc=()=>!W?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Ya=Ox({write:()=>{if(!Zc())return;let i=Ve.getState(),c=Wx({text:i.text,mentionRefs:i.mentionRefs,contentSegments:yf(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(_s)&&(_s=c,Ri())}});function Sb(){Zc()&&Ya.schedule()}function xm(){Ya.flush()}function Ab(i){if(!Zc())return;let c=Bx(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(f=>f.id),modelIds:(o.composer?.models??[]).map(f=>f.id),modes:o.composer?.modes??[]});c&&(_s=i,Ae&&!Ae.value&&(Ae.value=c.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),zo()),c.selectedModelId&&(Ve.setSelectedModelId(c.selectedModelId),Fr?.repaint()),Dc(c.activeModeIds??[]),c.quote&&qo(c.quote),Ya.cancel())}function ed(){Ya.cancel(),_s&&(_s=void 0,Zc()&&Ri())}let Wi=null,Mb=()=>st.querySelector("#persona-scroll-container")||le,Bi=()=>{Wi!==null&&(cancelAnimationFrame(Wi),Wi=null),Yn=!1},Tb=()=>{Ur!==null&&(cancelAnimationFrame(Ur),Ur=null),Gc=!1,Bi()},kE=()=>ro&&Am()&&(oo()!=="anchor-top"||Ey()),Sm=()=>{let i=_a()||"Jump to latest",c=kE();dn.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),jr>0?(xs.textContent=String(jr),xs.style.display="",dn.setAttribute("aria-label",`${i} (${jr} new)`)):(xs.textContent="",xs.style.display="none",dn.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Eb=()=>{jr!==0&&(jr=0,Sm())},LE=()=>{let i=yn?.spacerHeight??0;return i<=0?Ir(le,fr):rd(i)-le.scrollTop-le.clientHeight<=fr},Am=()=>Nr()?!so.isFollowing():!LE(),Mm=()=>!!$&&$.getMessages().length>0,bn=()=>{if(!oE()||ft()){dn.parentNode&&dn.remove(),dn.style.display="none";return}dn.parentNode!==Pe&&Pe.appendChild(dn),Ss();let c=ir(le)>0&&Am()&&Mm();c?Sm():Eb(),dn.style.display=c?"":"none"},Qa=()=>{so.pause()&&(Tb(),bn())},Qn=()=>{so.resume(),Eb(),bn()},Kr=(i=!1)=>{Nr()&&Mm()&&so.isFollowing()&&(!i&&!ro||(Ur!==null&&(cancelAnimationFrame(Ur),Ur=null),Gc=!0,Ur=requestAnimationFrame(()=>{Ur=null,Gc=!1,so.isFollowing()&&PE(Mb(),i?220:140)})))},kb=(i,c,f,y=()=>!0)=>{let x=i.scrollTop,P=c(),Y=P-x;if(Bi(),Math.abs(Y)<1){Yn=!0,i.scrollTop=P,io=i.scrollTop,Yn=!1;return}let ne=performance.now();Yn=!0;let te=fe=>1-Math.pow(1-fe,3),oe=fe=>{if(!y()){Bi();return}let Se=c();Se!==P&&(P=Se,Y=P-x);let Re=fe-ne,bt=Math.min(Re/f,1),Ht=te(bt),Wt=x+Y*Ht;i.scrollTop=Wt,io=i.scrollTop,bt<1?Wi=requestAnimationFrame(oe):(i.scrollTop=P,io=i.scrollTop,Wi=null,Yn=!1)};Wi=requestAnimationFrame(oe)},PE=(i,c=500)=>{let f=ir(i)-i.scrollTop;if(Math.abs(f)<1){io=i.scrollTop;return}if(Math.abs(f)>=SE){Bi(),Yn=!0,i.scrollTop=ir(i),io=i.scrollTop,Yn=!1;return}kb(i,()=>ir(i),c,()=>so.isFollowing())},td=()=>{if(!Mm()){bn();return}let i=Mb();Yn=!0,i.scrollTop=ir(i),io=i.scrollTop,Yn=!1,bn()},Ns=i=>{let c=0,f=i;for(;f&&f!==le;)c+=f.offsetTop,f=f.offsetParent;return c},IE=()=>{let i=le.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??le.ownerDocument.getSelection()},nd=()=>US(IE(),le),Tm=()=>{if(rE()!=="last-user-turn")return!1;let i=$?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(P=>P.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=le.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let x=Math.min(Math.max(0,Ns(y)-Na()),ir(le));return Yn=!0,le.scrollTop=x,io=le.scrollTop,Yn=!1,oo()==="follow"&&!Ir(le,fr)&&so.pause(),bn(),!0},od=i=>{let c=Math.max(0,Math.round(i));fo.style.height=`${c}px`,fo.style.display=c>0?"":"none",yn&&(yn.spacerHeight=Math.max(0,i))},rd=i=>{let c=parseFloat(getComputedStyle(le).paddingBottom)||0,f=0;for(let x of Array.from(le.children)){if(x===fo||x.offsetHeight===0)continue;let P=Ns(x)+x.offsetHeight;P>f&&(f=P)}let y=le.scrollHeight-i;return f>0?Math.min(f+c,y):y},HE=()=>{if(!yn||yn.spacerHeight<=0)return;let i=rd(yn.spacerHeight),c=Math.max(0,Math.round(le.scrollTop)+le.clientHeight-i+fr);c<yn.spacerHeight&&(od(c),bn())},Wo=()=>{Bs!==null&&(cancelAnimationFrame(Bs),Bs=null),Bi(),yn=null,fo.style.height="0px",fo.style.display="none"},Lb=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Em=i=>le.querySelector(`[data-message-id="${Lb(i)}"]`),Pb=i=>{Bs!==null&&cancelAnimationFrame(Bs),Bs=requestAnimationFrame(()=>{Bs=null;let c=Lb(i),f=le.querySelector(`[data-message-id="${c}"]`);if(!f)return;let y=Ns(f),x=yn?.spacerHeight??0,P=rd(x),{targetScrollTop:Y,spacerHeight:ne}=jg({anchorOffsetTop:y,topOffset:Na(),viewportHeight:le.clientHeight,contentHeight:P,slack:fr});yn={initialSpacerHeight:ne,contentHeightAtAnchor:P,spacerHeight:ne},od(ne),kb(le,()=>f.isConnected?Math.max(0,Ns(f)-Na()):Y,220)})},Xn=()=>{if(oo()!=="anchor-top"||!yn||!Hi)return;let i=Em(Hi);if(!i)return;Bi();let c=yn.spacerHeight,f=rd(c),{targetScrollTop:y,spacerHeight:x}=jg({anchorOffsetTop:Ns(i),topOffset:Na(),viewportHeight:le.clientHeight,contentHeight:f,slack:fr});yn={initialSpacerHeight:x,contentHeightAtAnchor:f,spacerHeight:x},od(x),Yn=!0,le.scrollTop=y,io=le.scrollTop,Yn=!1,bn()},RE=()=>{if(Nr()){if(!so.isFollowing()||Ir(le,1))return;Kr(!ro);return}if(yn&&yn.initialSpacerHeight>0){let i=le.scrollHeight-yn.spacerHeight,c=jS({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:i});c!==yn.spacerHeight&&od(c)}bn()},WE=i=>{let c=oo();c==="follow"?(Qn(),Kr(!0)):c==="anchor-top"&&(Ga=!1,Yc=!0,Qc=!1,Hi=i,Pb(i))},BE=()=>{if(oo()==="anchor-top"){if(Yc){Ga=!1;return}Ga=!0,Wo(),Qn(),Kr(!0)}},OE=96,DE=i=>{if(Os===null)return!0;let c=Em(Os),f=Em(i);if(!c||!f)return!0;let y=Ns(f)-Ns(c);return Na()+y>le.clientHeight-OE},_E=i=>{if(oo()!=="anchor-top"||!Yc||Qc||nd())return;let c=Os===null;for(let f of i){if(!c){f.id===Os&&(c=!0);continue}if(qS(f)){if(f.id===Hi||!DE(f.id))return;Hi=f.id,Pb(f.id);return}}},NE=i=>{let c=new Map;i.forEach(f=>{let y=wm.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(L.emit("assistant:message",f),!Ii&&(oo()!=="anchor-top"||Ey())&&Am()&&(jr+=1,Sm(),bn(),Rc(jr===1?"1 new message below.":`${jr} new messages below.`))),f.role==="assistant"&&y?.streaming&&f.streaming===!1&&L.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&L.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):L.emit("approval:requested",{approval:f.approval,message:f}))}),wm.clear(),c.forEach((f,y)=>{wm.set(y,f)})},Xa=(i,c)=>{let f=c==="user"?"user":"assistant",y=o.layout?.messages?.[f],x=y?.width??"content",P=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),P?i.style.setProperty("--persona-message-row-max-width",P):i.style.removeProperty("--persona-message-row-max-width")},yr=(i,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),Xa(f,c),f},FE=(i,c,f)=>{let y=document.createElement("div"),P=(()=>{let G=a.find(tt=>tt.renderLoadingIndicator);if(G?.renderLoadingIndicator)return G.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Y=(G,tt)=>tt==null?!1:typeof tt=="string"?(G.textContent=tt,!0):(G.appendChild(tt),!0),ne=new Set,te=new Map,oe=new Set,fe=a.some(G=>G.renderAskUserQuestion),Se=[],Re=[],bt=o.enableComponentStreaming!==!1,Ht=o.approval!==!1,Wt=[],Sn=o.messageActions,mn=Sn?.showRegenerate===!0&&Sn.enabled!==!1&&Pt.current?.isStreaming()!==!0?kw(c):null,nn=Sn?.showEdit===!0&&Sn.enabled!==!1,Wn=Sn?.showQuote===!0&&Sn.enabled!==!1,wt=null,Bn=o.features?.reasoningDisplay?.completedVisibility==="removed";if(c.forEach(G=>{if(Bn&&G.variant==="reasoning"&&G.reasoning?.status==="complete")return;if(ne.add(G.id),te.set(G.id,G.role),Hs===G.id&&qr){let Ze=yr(G.id,G.role);Ze.setAttribute("data-persona-message-edit-stub","true"),Ze.setAttribute("data-preserve-runtime","true"),y.appendChild(Ze),wt={messageId:G.id,element:qr.element};return}let tt=fe&&ti(G),ot=Ht&&G.variant==="approval"&&!!G.approval,Oe=!tt&&G.role==="assistant"&&!G.variant&&bt&&yy(G);!ot&&zr.has(G.id)&&(i.querySelector(`#wrapper-${G.id}`)?.removeAttribute("data-preserve-runtime"),zr.delete(G.id)),!Oe&&Is.has(G.id)&&(i.querySelector(`#wrapper-${G.id}`)?.removeAttribute("data-preserve-runtime"),Is.delete(G.id));let _t=ti(G)?`:${G.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${G.agentMetadata?.askUserQuestionAnswers?Object.keys(G.agentMetadata.askUserQuestionAnswers).length:0}`:"",vn={canRegenerate:mn===G.id,canEdit:nn&&Xf(G),canQuote:Wn&&!G.variant&&(G.content?.trim().length??0)>0},On=`${vn.canRegenerate?"r":""}${vn.canEdit?"e":""}${vn.canQuote?"q":""}`,Dn=NS(G,Ws)+_t+`:${On}`,on=tt||ot||Oe?null:$S(pn,G.id,Dn);if(on){y.appendChild(on.cloneNode(!0)),ti(G)&&G.toolCall?.id&&G.agentMetadata?.awaitingLocalTool===!0&&!G.agentMetadata?.askUserQuestionAnswered&&(oe.add(G.toolCall.id),ep(G,o,Qe.composerOverlay));return}let ze=null,Cn=a.find(Ze=>!!(G.variant==="reasoning"&&Ze.renderReasoning||G.variant==="tool"&&Ze.renderToolCall||!G.variant&&Ze.renderMessage)),wn=o.layout?.messages;if(ti(G)&&G.agentMetadata?.askUserQuestionAnswered===!0){Pi.delete(G.id),i.querySelector(`#wrapper-${G.id}`)?.removeAttribute("data-preserve-runtime");return}if(Tl(G)&&ls(o).enabled)return;if(ti(G)&&o.features?.askUserQuestion?.enabled!==!1){let Ze=a.find(jt=>typeof jt.renderAskUserQuestion=="function");if(Ze&&Pt.current){let jt=Pi.get(G.id),er=jt!==Dn,Bo=null;if(er){let{payload:it,complete:Nt}=ra(G),ts=G.id,xn=()=>Pt.current?.getMessages().find(co=>co.id===ts);Bo=Ze.renderAskUserQuestion({message:G,payload:it,complete:Nt,resolve:co=>{let Js=xn();Js&&Pt.current?.resolveAskUserQuestion(Js,co)},dismiss:()=>{let co=xn();co?.agentMetadata?.awaitingLocalTool&&(Pt.current?.markAskUserQuestionResolved(co),Pt.current?.resolveAskUserQuestion(co,"(dismissed)"))},config:o})}let nt=jt!=null;if(er&&Bo===null&&!nt){G.agentMetadata?.awaitingLocalTool===!0&&!G.agentMetadata?.askUserQuestionAnswered&&(oe.add(G.toolCall.id),ep(G,o,Qe.composerOverlay));return}let Ne=yr(G.id,G.role);Ne.setAttribute("data-ask-plugin-stub","true"),Ne.setAttribute("data-preserve-runtime","true"),y.appendChild(Ne),Se.push({messageId:G.id,fingerprint:Dn,bubble:Bo});return}else{G.agentMetadata?.awaitingLocalTool===!0&&!G.agentMetadata?.askUserQuestionAnswered&&(oe.add(G.toolCall.id),ep(G,o,Qe.composerOverlay));return}}else if(ot){let Ze=I();if(!Ze){y.appendChild(yr(G.id,G.role));return}let jt=a.find(Ne=>typeof Ne.renderApproval=="function")??h,Bo=zr.get(G.id)!==Dn,nt=null;if(Bo&&jt?.renderApproval){let Ne=G.id,it=(Nt,ts)=>{let xn=Pt.current?.getMessages().find(co=>co.id===Ne);xn?.approval&&(xn.approval.toolType==="webmcp"?Pt.current?.resolveWebMcpApproval(xn.id,Nt):Pt.current?.resolveApproval(xn.approval,Nt,ts))};nt=jt.renderApproval({message:G,defaultRenderer:()=>Ze.createApprovalBubble(G,o),config:o,approve:Nt=>it("approved",Nt),deny:Nt=>it("denied",Nt)})}if(Bo&&nt===null)i.querySelector(`#wrapper-${G.id}`)?.removeAttribute("data-preserve-runtime"),zr.delete(G.id),ze=Ze.createApprovalBubble(G,o);else{let Ne=yr(G.id,G.role);Ne.setAttribute("data-approval-plugin-stub","true"),Ne.setAttribute("data-preserve-runtime","true"),y.appendChild(Ne),Wt.push({messageId:G.id,fingerprint:Dn,bubble:nt});return}}else if(Cn)if(G.variant==="reasoning"&&G.reasoning&&Cn.renderReasoning){if(!lt)return;ze=Cn.renderReasoning({message:G,defaultRenderer:()=>Ch(G,o),config:o})}else if(G.variant==="tool"&&G.toolCall&&Cn.renderToolCall){if(!Vt)return;ze=Cn.renderToolCall({message:G,defaultRenderer:()=>xh(G,o),config:o})}else Cn.renderMessage&&(ze=Cn.renderMessage({message:G,defaultRenderer:()=>{let Ze=ch(G,f,wn,o.messageActions,Je,{loadingIndicatorRenderer:P,widgetConfig:o,actionEligibility:vn});return G.role!=="user"&&D(Ze,G,o,$),Ze},config:o}));if(!ze&&Oe){let Ze=OT(G);if(Ze){let jt=Is.get(G.id),er=jt!==Dn,Bo=o.wrapComponentDirectiveInBubble!==!1&&No.getOptions(Ze.component)?.bubbleChrome!==!1,nt=null;if(er){let Ne=WT(Ze,{config:o,message:G,transform:f});if(Ne&&Ze.component==="PersonaArtifactInline"){let it=Ne.hasAttribute("data-artifact-inline")?Ne:Ne.querySelector("[data-artifact-inline]"),Nt=it?.getAttribute("data-artifact-inline")??"",ts=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Nt):Nt,xn=Nt?i.querySelector(`#wrapper-${G.id}`)?.querySelector(`[data-artifact-inline="${ts}"]`)??null:null;it&&xn&&xn!==it&&Rr()?.hasLiveInlineArtifactBlock(xn)&&(it===Ne?Ne=xn:it.replaceWith(xn))}if(Ne)if(Bo){let it=document.createElement("div");if(it.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),it.id=`bubble-${G.id}`,it.setAttribute("data-message-id",G.id),G.content&&G.content.trim()){let Nt=document.createElement("div");Nt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Nt.innerHTML=f({text:G.content,message:G,streaming:!!G.streaming,raw:G.rawContent}),it.appendChild(Nt)}it.appendChild(Ne),nt=it}else{let it=document.createElement("div");if(it.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",it.id=`bubble-${G.id}`,it.setAttribute("data-message-id",G.id),it.setAttribute("data-persona-component-directive","true"),G.content&&G.content.trim()){let Nt=document.createElement("div");Nt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Nt.innerHTML=f({text:G.content,message:G,streaming:!!G.streaming,raw:G.rawContent}),it.appendChild(Nt)}it.appendChild(Ne),nt=it}}if(nt||jt!=null){let Ne=yr(G.id,G.role);Ne.setAttribute("data-component-directive-stub","true"),Ne.setAttribute("data-preserve-runtime","true"),y.appendChild(Ne),Re.push({messageId:G.id,fingerprint:Dn,bubble:nt});return}}}if(!ze)if(G.variant==="reasoning"&&G.reasoning){if(!lt)return;ze=Ch(G,o)}else if(G.variant==="tool"&&G.toolCall){if(!Vt)return;ze=xh(G,o)}else if(G.variant==="approval"&&G.approval){if(o.approval===!1)return;let Ze=I();if(!Ze)return;ze=Ze.createApprovalBubble(G,o)}else{let Ze=o.layout?.messages;Ze?.renderUserMessage&&G.role==="user"?ze=Ze.renderUserMessage({message:G,config:o,streaming:!!G.streaming}):Ze?.renderAssistantMessage&&G.role==="assistant"?ze=Ze.renderAssistantMessage({message:G,config:o,streaming:!!G.streaming}):ze=ch(G,f,Ze,o.messageActions,Je,{loadingIndicatorRenderer:P,widgetConfig:o,actionEligibility:vn}),G.role!=="user"&&ze&&D(ze,G,o,$)}let xo=yr(G.id,G.role);xo.appendChild(ze),VS(pn,G.id,Dn,xo),y.appendChild(xo)}),Qe.composerOverlay&&Qe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(tt=>{let ot=tt.getAttribute("data-persona-ask-sheet-for");ot&&!oe.has(ot)&&ia(Qe.composerOverlay,ot)}),o.features?.toolCallDisplay?.grouped){let G=[],tt=[],ot=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&Vt){tt.push(Oe);return}Oe.variant==="reasoning"&&(!lt||Bn&&Oe.reasoning?.status==="complete")||((tt.length>1||ot&&tt.length>0)&&G.push(tt),tt=[])}),(tt.length>1||ot&&tt.length>0)&&G.push(tt),G.forEach(Oe=>{let _t=Oe.map(wn=>Array.from(y.children).find(xo=>xo instanceof HTMLElement&&xo.getAttribute("data-wrapper-id")===wn.id)).filter(wn=>!!wn);if(_t.length<(ot?1:2))return;let vn=yr(`tool-group-${Oe[0].id}`,"assistant");vn.setAttribute("data-persona-tool-group-row","true");let On=document.createElement("div");On.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",On.setAttribute("data-persona-tool-group","true");let Dn=document.createElement("div");Dn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Dn.id=`tool-group-summary-${Oe[0].id}`;let on=`Called ${Oe.length} ${Oe.length===1?"tool":"tools"}`,ze=o.toolCall?.renderGroupedSummary?.({messages:Oe,toolCalls:Oe.map(wn=>wn.toolCall).filter(wn=>!!wn),defaultSummary:on,config:o});Y(Dn,ze)||(Dn.textContent=on);let Cn=document.createElement("div");Cn.className="persona-tool-group-stack persona-flex persona-flex-col",Cn.id=`tool-group-stack-${Oe[0].id}`,Cn.setAttribute("data-persona-tool-group-stack","true"),On.appendChild(Dn),ot||On.appendChild(Cn),vn.appendChild(On),_t[0].before(vn),_t.forEach((wn,xo)=>{if(ot){wn.remove();return}wn.style.setProperty("--persona-message-row-max-width","100%");let Ze=document.createElement("div");Ze.className="persona-tool-group-item persona-relative",Ze.setAttribute("data-persona-tool-group-item","true"),xo<_t.length-1&&Ze.setAttribute("data-persona-tool-group-connector","true"),Ze.appendChild(wn),Cn.appendChild(Ze)})})}zS(pn,ne);let Tr=c.some(G=>G.role==="assistant"&&G.streaming),Jo=c[c.length-1],Zo=Jo?.role==="assistant"&&!Jo.streaming&&Jo.variant!=="approval";if(ro&&c.some(G=>G.role==="user")&&!Tr&&!Zo){let G={config:o,streaming:!0,location:"standalone",defaultRenderer:pc},tt=a.find(Oe=>Oe.renderLoadingIndicator),ot=null;if(tt?.renderLoadingIndicator&&(ot=tt.renderLoadingIndicator(G)),ot===null&&o.loadingIndicator?.render&&(ot=o.loadingIndicator.render(G)),ot===null&&(ot=pc()),ot){let Oe=document.createElement("div"),_t=o.loadingIndicator?.showBubble!==!1,vn=o.layout?.messages?.layout??"bubble";Oe.className=_t?uc("assistant",vn).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Oe.setAttribute("data-typing-indicator","true"),_t&&(Oe.style.color="var(--persona-message-assistant-text, var(--persona-text))",vn!=="flat"&&(Oe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Oe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Oe.appendChild(ot);let On=yr("typing-indicator","assistant");On.appendChild(Oe),y.appendChild(On)}}if(!ro&&c.length>0){let G=c[c.length-1],tt={config:o,lastMessage:G,messageCount:c.length},ot=a.find(_t=>_t.renderIdleIndicator),Oe=null;if(ot?.renderIdleIndicator&&(Oe=ot.renderIdleIndicator(tt)),Oe===null&&o.loadingIndicator?.renderIdle&&(Oe=o.loadingIndicator.renderIdle(tt)),Oe){let _t=document.createElement("div"),vn=o.loadingIndicator?.showBubble!==!1;_t.className=vn?["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(" "),_t.setAttribute("data-idle-indicator","true"),_t.appendChild(Oe);let On=yr("idle-indicator","assistant");On.appendChild(_t),y.appendChild(On)}}if(SC(y),su(i,y),Of(i),wt){let{messageId:G,element:tt}=wt,ot=i.querySelector(`#wrapper-${G}`);ot&&tt.parentElement!==ot&&(Xa(ot,te.get(G)??"user"),ot.replaceChildren(tt))}if(Se.length>0)for(let{messageId:G,fingerprint:tt,bubble:ot}of Se){let Oe=i.querySelector(`#wrapper-${G}`);Oe&&(Xa(Oe,te.get(G)??"assistant"),ot!==null&&(Oe.replaceChildren(ot),Oe.setAttribute("data-bubble-fp",tt),Pi.set(G,tt)))}if(Pi.size>0)for(let G of Pi.keys())ne.has(G)||Pi.delete(G);if(Re.length>0)for(let{messageId:G,fingerprint:tt,bubble:ot}of Re){let Oe=i.querySelector(`#wrapper-${G}`);Oe&&(Xa(Oe,te.get(G)??"assistant"),ot!==null&&(Oe.replaceChildren(ot),Oe.setAttribute("data-bubble-fp",tt),Is.set(G,tt)))}if(Is.size>0)for(let G of Is.keys())ne.has(G)||Is.delete(G);if(Wt.length>0)for(let{messageId:G,fingerprint:tt,bubble:ot}of Wt){let Oe=i.querySelector(`#wrapper-${G}`);Oe&&(Xa(Oe,te.get(G)??"assistant"),ot!==null&&(Oe.replaceChildren(ot),Oe.setAttribute("data-bubble-fp",tt),zr.set(G,tt)))}if(zr.size>0)for(let G of zr.keys())ne.has(G)||zr.delete(G)},km=!1,sd=()=>{km||(km=!0,gC().catch(()=>{km=!1}))},ho=(i,c,f)=>{c.length>0&&sd(),FE(i,c,f),Qy()},Ja=null,$E=()=>{if(Ja)return;let i=f=>{let y=f.composedPath();y.includes(st)||Yt&&y.includes(Yt)||Rt(!1,"user")};Ja=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Ib=()=>{if(!Ja)return;(t.ownerDocument??document).removeEventListener("pointerdown",Ja,!0),Ja=null};_e.push(()=>Ib());let Za=null,VE=()=>{if(Za)return;let i=f=>{f.key==="Escape"&&(f.isComposing||Rt(!1,"user"))};Za=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},Hb=()=>{if(!Za)return;(t.ownerDocument??document).removeEventListener("keydown",Za,!0),Za=null};_e.push(()=>Hb());let el=!1,Rb=new Set,zE=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Oi=()=>{if(!ke())return;let i=Qe.peekBanner,c=Qe.peekTextNode;if(!i||!c)return;if(Te){i.classList.remove("persona-pill-peek--visible");return}let f=$?.getMessages()??[],y;for(let mn=f.length-1;mn>=0;mn--){let nn=f[mn];if(nn.role==="assistant"&&nn.content){y=nn;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let x=y.content,P=!!y.streaming,Y=zE(),ne=cu(Y),te=ne.type!=="none"?bm(ne.type,Y?.plugins):null,oe=te?.isAnimating?.(y)===!0,fe=te!==null&&(P||oe);fe&&te&&!Rb.has(te.name)&&(tc(te,t),Rb.add(te.name));let Se=fe&&te?.containerClass?te.containerClass:null,Re=c.dataset.personaPeekStreamClass??null;Re&&Re!==Se&&(c.classList.remove(Re),delete c.dataset.personaPeekStreamClass),Se&&Re!==Se&&(c.classList.add(Se),c.dataset.personaPeekStreamClass=Se),fe?(c.style.setProperty("--persona-stream-step",`${ne.speed}ms`),c.style.setProperty("--persona-stream-duration",`${ne.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let bt=fe?du(x,ne.buffer,te,y,P):x;if(fe&&ne.placeholder==="skeleton"&&P&&(!bt||!bt.trim())){let mn=document.createElement("div"),nn=ec();nn.classList.add("persona-pill-peek__skeleton"),mn.appendChild(nn),su(c,mn)}else{let mn=Math.max(0,bt.length-100),nn=bt.length>100?bt.slice(-100):bt,Wn=Er(nn);if(!fe||!te){let wt=bt.length>100?`\u2026${nn}`:nn;c.textContent!==wt&&(c.textContent=wt)}else{let wt=Wn;(te.wrap==="char"||te.wrap==="word")&&(wt=Zl(Wn,te.wrap,`peek-${y.id}`,{skipTags:te.skipTags,startIndex:mn}));let Bn=document.createElement("div");if(Bn.innerHTML=wt,te.useCaret&&nn.length>0){let Tr=pu(),Jo=Bn.querySelectorAll(".persona-stream-char, .persona-stream-word"),Zo=Jo[Jo.length-1];Zo?.parentNode?Zo.parentNode.insertBefore(Tr,Zo.nextSibling):Bn.appendChild(Tr)}su(c,Bn),te.onAfterRender?.({container:c,bubble:i,messageId:y.id,message:y,speed:ne.speed,duration:ne.duration})}}let Sn=ro||el;i.classList.toggle("persona-pill-peek--visible",Sn)};if(ke()){let i=Qe.peekBanner;if(i){let y=x=>{x.preventDefault(),x.stopPropagation(),Rt(!0,"user")};i.addEventListener("pointerdown",y),_e.push(()=>{i.removeEventListener("pointerdown",y)})}let c=()=>{el||(el=!0,Oi())},f=()=>{el&&(el=!1,Oi())};Fe.addEventListener("pointerenter",c),Fe.addEventListener("pointerleave",f),_e.push(()=>{Fe.removeEventListener("pointerenter",c),Fe.removeEventListener("pointerleave",f)}),Yt&&(Yt.addEventListener("pointerenter",c),Yt.addEventListener("pointerleave",f),_e.push(()=>{Yt.removeEventListener("pointerenter",c),Yt.removeEventListener("pointerleave",f)}))}let qE=i=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",y=c.bottomOffset??"16px",x=c.collapsedMaxWidth,P=c.expandedMaxWidth??"880px",Y=c.expandedTopOffset??"5vh",ne=c.modalMaxWidth??"880px",te=c.modalMaxHeight??"min(90vh, 800px)",oe="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",Se=st.style;if(Se.left="",Se.right="",Se.top="",Se.bottom="",Se.transform="",Se.width="",Se.maxWidth="",Se.height="",Se.maxHeight="",Yt){let Re=Yt.style;Re.bottom=y,Re.width=x??""}if(i&&f!=="fullscreen"){if(f==="modal"){Se.top="50%",Se.left="50%",Se.transform="translate(-50%, -50%)",Se.bottom="auto",Se.right="auto",Se.width=ne,Se.maxWidth=oe,Se.maxHeight=te,Se.height=te;return}Se.left="50%",Se.transform="translateX(-50%)",Se.bottom=`calc(${y} + ${fe})`,Se.top=Y,Se.width=P,Se.maxWidth=oe}},tl=()=>{if(Te&&sd(),!Ie())return;if(ke()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Te?"expanded":"collapsed";st.dataset.state=fe,st.dataset.expandedSize=oe,Yt&&(Yt.dataset.state=fe,Yt.dataset.expandedSize=oe),st.style.removeProperty("display"),st.classList.remove("persona-pointer-events-none","persona-opacity-0"),Fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),qE(Te),Pe.style.display=Te?"flex":"none",Ms(),Te?($E(),VE()):(Ib(),Hb()),Oi();return}let i=an(o),c=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,x=c.innerWidth<=f,P=y&&x&&ue,Y=Eo(o).reveal;Te?(st.style.removeProperty("display"),st.style.display=i?"flex":"",st.classList.remove("persona-pointer-events-none","persona-opacity-0"),Fe.classList.remove("persona-scale-95","persona-opacity-0"),Fe.classList.add("persona-scale-100","persona-opacity-100"),en?(en.setPanelOpen(!0),en.element.style.display="none"):Nn&&(Nn.style.display="none")):(i?i&&(Y==="overlay"||Y==="push")&&!P?(st.style.removeProperty("display"),st.style.display="flex",st.classList.remove("persona-pointer-events-none","persona-opacity-0"),Fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(st.style.setProperty("display","none","important"),st.classList.remove("persona-pointer-events-none","persona-opacity-0"),Fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(st.style.display="",st.classList.add("persona-pointer-events-none","persona-opacity-0"),Fe.classList.remove("persona-scale-100","persona-opacity-100"),Fe.classList.add("persona-scale-95","persona-opacity-0")),en?(en.setPanelOpen(!1),en.element.style.display=i?"none":""):Nn&&(Nn.style.display=i?"none":""))},Rt=(i,c="user")=>{if(!Ie()||Te===i)return;let f=Te;Te=i,tl();let y=(()=>{let P=o.launcher?.sidebarMode??!1,Y=t.ownerDocument.defaultView??window,ne=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640,oe=Y.innerWidth<=te,fe=an(o)&&ne&&oe,Se=ke()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||ne&&oe&&ue||fe||Se})();if(Te&&y){if(!Ko){let P=t.getRootNode(),Y=P instanceof ShadowRoot?P.host:t.closest(".persona-host");Y&&(Ko=Zg(Y,o.launcher?.zIndex??In))}Go||(Go=eh(t.ownerDocument))}else Te||(Ko?.(),Ko=null,Go?.(),Go=null);Te&&(bl(),Tm()||(oo()==="follow"?Kr(!0):td()));let x={open:Te,source:c,timestamp:Date.now()};Te&&!f?L.emit("widget:opened",x):!Te&&f&&L.emit("widget:closed",x),L.emit("widget:state",{open:Te,launcherEnabled:ue,voiceActive:pt.active,streaming:$.isStreaming()})},Gr={inputDisabled:!1,sendDisabled:!1},Yr=()=>Gr.inputDisabled,Fs=()=>Gr.inputDisabled||Gr.sendDisabled,UE=()=>(Gr.inputDisabled?Gr.inputReason:void 0)??(Gr.sendDisabled?Gr.sendReason:void 0);function Lm(){if(!$e)return;if(Ve.getState().phase==="streaming"){$e.disabled=!1;return}let i=Ct?!Ct.isReady():!1;$e.disabled=Fs()||i}function id(){if(!Vo)return;let i=Ve.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;Vo.toggleAttribute("data-persona-send-hidden",c)}function jE(){let i=UE();if(ke()){let c=Rn??Be;i?c.setAttribute("title",i):c.removeAttribute("title"),Be.toggleAttribute(Wa,!!i);return}if(i){gt.setAttribute("role","status"),gt.setAttribute("aria-live","polite"),gt.setAttribute(Wa,""),gt.textContent=i;return}if(gt.hasAttribute(Wa)&&(gt.removeAttribute("role"),gt.removeAttribute("aria-live"),gt.removeAttribute(Wa),p)){let c=$.getStatus();Hn(gt,xt(c),o.statusIndicator??{},c)}}function Pm(){let i=hg(o.composer?.inputDisabled),c=hg(o.composer?.sendDisabled);Gr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},Ve.setInputDisabled(i.disabled),Ve.setSendDisabled(c.disabled);let f=Ve.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")),Qt&&(Qt.disabled=y),$t&&($t.disabled=y);for(let P of sn?.affordanceButtons??[])P.querySelectorAll("button").forEach(Y=>{Y.disabled=y});ye&&(ye.disabled=x),ks.forEach(P=>{P.elements.forEach(Y=>{Y.toggleAttribute("data-disabled",x),Y instanceof HTMLButtonElement||Y.setAttribute("aria-disabled",x?"true":"false")}),P.buttons.forEach(Y=>{Y.disabled=x})}),Bm.forEach(P=>{P.toggleAttribute("data-disabled",x),P instanceof HTMLButtonElement?P.disabled=x:P.setAttribute("aria-disabled",x?"true":"false"),P.querySelectorAll("button").forEach(Y=>{Y.disabled=x})}),Be.dataset.personaComposerStreaming=f?"true":"false",Be.dataset.personaComposerInputDisabled=y?"true":"false",Be.dataset.personaComposerSendDisabled=Fs()?"true":"false",Be.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(P=>{(P instanceof HTMLButtonElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P instanceof HTMLSelectElement)&&(P.disabled=f)}),Lm(),jE()}let nl=i=>{Ve.setStreaming(i),My(i?"stop":"send"),Pm()},$s=()=>{pt.active||Ae&&Ae.focus()};L.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>$s(),200)});let Vs=null,ol=!1,Im=!cn.hidden,Qr=null,Hm=!w,ad=null;_e.push(()=>{ad?.cancel(),ad=null});let KE=i=>{let c=WA(i);if(c===Wc)return;Wc=c,t.setAttribute("data-persona-conversation-state",c);let f=nm();Oc(),Hm&&(ad?.cancel(),ad=HA(Be,c==="active"?f:nm(),c==="active"?"drop":"rise")),Xn()},Wb=null,Bb,Ob=null,Di=null,Rm=!1,rl=i=>{let c=Hr(o),f=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(f!==Wb||c.icon!==Bb)&&(Wb=f,Bb=c.icon,vu({host:cn,iconHolder:Oa,kicker:Da,title:Ju,subtitle:Zu,starterSuggestions:Ci},c));let y=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;y!==Ob&&(Ob=y,Cu(Ln,c.message,o));let x=i??($?$.getMessages():o.initialMessages);KE(x);let P=ol,Y=!P&&Sa(c,x),ne=Y!==Im;if(Im=Y,Di){Qr?.cancel(),Qr=null,P!==Rm&&(Rm=P,P?uh(le,cn,null):ph(le,cn,Di)),xa(le,cn,!P);return}if(ne&&!Y&&!P&&c.dismiss==="on-first-message"&&Hm){Qr=IA(cn,oe=>{Qr===oe&&(Qr=null),!Im&&!Di&&(xa(le,cn,!1),Xn()),oe?.cancel()});return}if(Qr){if(!Y&&!P)return;Qr.cancel(),Qr=null}let te=!cn.hidden;xa(le,cn,Y),!Y&&te&&Xn()},Wm=[],Bm=[],Om=!1,Db=null,_b,Nb=()=>{Bm.length=0;let i=Wm.splice(0,Wm.length);for(let c of i)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};_e.push(Nb);let GE=(i,c)=>{let f=nh(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=oh({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:cn,submitPrompt:Wd});return Bm.push(x),x},Dm=()=>{if(Om)return;Om=!0;let i=Hr(o);Db=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,_b=i.icon;try{Nb(),uh(le,cn,Di),Di=null,Rm=!1;let c=$?$.getMessages():o.initialMessages,f=Sa(i,c),y=0,x=null;for(let P of a)if(P.renderWelcome&&(x=P.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>cn,sendMessage:Y=>{if(!$||$.isStreaming())return;let ne=Y.trim();ne&&$.sendMessage(ne)},requestRender:()=>Dm(),renderStarter:Y=>GE(Y,y++),storage:u(P.id),onCleanup:Y=>{Wm.push(Y)}}),x))break;x&&x!==cn&&(Di=x,ph(le,cn,x))}finally{Om=!1}rl()},YE=()=>{let i=Hr(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Db&&i.icon===_b||Dm()},ld=()=>{rl(),Mi||(Ae.placeholder=Lx(Ve.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!$?.isStreaming()&&($e.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))"},QE=!!o.setStoredConversationId,_i=i=>Z(c=>{let f={...c};return delete f[i],f}),cd=i=>{let c=H[i];return typeof c=="string"?c:null},Fb=()=>{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:()=>cd("sessionId"),setStoredSessionId:i=>{Z(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>_i("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>cd("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{Z(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>_i("conversationId"))});let $b=()=>o.clientToken??null,Vb=i=>pT(i,Ge(),o.persistState===!1),zb=$b(),br=zb?Vb(zb):null,vr={...br?{visitorStore:br}:{},historyBootstrapReady:R,getStoredMessageCursor:()=>cd("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){_i("historyMessageCursor");return}Z(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){_i("pendingDisplayProjections");return}Z(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:Fb,setStoredResumableHandle:i=>{if(!i){_i("durableResume");return}Z(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>z&&Fb()!==null,...QE?{}:{getStoredConversationRevision:()=>cd("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){_i("conversationRevision");return}Z(c=>({...c,conversationRevision:i}))}}};if(z){let i=o.onExecutionState,c=t.ownerDocument.defaultView,f=!1,y=()=>f=!0,x=()=>f=!1;c?.addEventListener("pagehide",y),c?.addEventListener("pageshow",x),_e.push(()=>{c?.removeEventListener("pagehide",y),c?.removeEventListener("pageshow",x)}),o={...o,reconnectStream:o.reconnectStream??(P=>$.getClient().reconnectClientTokenStream(P)),onExecutionState:P=>{(P||!f)&&vr.setStoredResumableHandle?.(P?{executionId:P.executionId,after:P.lastEventId}:null),i?.(P)}}}let XE=()=>{let i=$b();if(i&&br?.matches(i,Ge(),o.persistState===!1)||!i&&!br)return;br?.destroy(),br=i?Vb(i):null;let c={...vr};br?c.visitorStore=br:delete c.visitorStore,vr=c,$.setHistoryInternals(vr)},zs=null,JE=()=>{zs==null&&(zs=setInterval(()=>{let i=We.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(zs),zs=null;return}let c=Date.now();i.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=op(c-y))})},100))},_m=(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((Y,ne)=>_m(Y,c[ne]));let f=i,y=c,x=Object.keys(f),P=Object.keys(y);return x.length===P.length&&x.every(Y=>Object.prototype.hasOwnProperty.call(y,Y)&&_m(f[Y],y[Y]))},qb=i=>{let{content:c,rawContent:f,llmContent:y,...x}=i;return x},Nm=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!yy(i),ZE=(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))&&Nm(y)&&Nm(x)&&_m(qb(y),qb(x))},Fm=null,Ni=null,qs=null,Cr=null,$m=null,ek=i=>{if(!z)return Ri(i);$m=i,queueMicrotask(()=>{$m===i&&($m=null,Ri(i))})},dd=i=>{Fm=i;let c,f;Ni=null;for(let x=i.length-1;x>=0;x-=1){let P=i[x];if(!c&&P.role==="user"&&(c=P),!f&&P.role==="assistant"&&(f=P),!Ni&&Nm(P)&&(Ni={index:x,id:P.id}),c&&f&&Ni)break}ho(We,i,je),Rr()?.updateInlineArtifactBlocks(We,go.artifacts,{suppressTransition:ro}),JE(),rl(i),Li(i),Kr(!ro),NE(i),i.length===0&&(Wo(),Ga=!0,Yc=!1,Hi=null,Qc=!1),!vm||Ii?(vm=!0,Os=c?.id??null,Cm=f?.id??null):c&&c.id!==Os?(Os=c.id,WE(c.id)):f&&f.id!==Cm&&BE(),f&&(Cm=f.id),_E(i);let y=pt.lastUserMessageId;c&&c.id!==y&&(pt.lastUserMessageId=c.id,L.emit("user:message",c)),pt.lastUserMessageWasVoice=!!c?.viaVoice,ek(i),Oi()},Vm=()=>{Cr!==null&&(cancelAnimationFrame(Cr),Cr=null);let i=qs;qs=null,i&&dd(i)},Ub=()=>{Cr!==null&&cancelAnimationFrame(Cr),Cr=null,qs=null},tk=i=>{let c=qs??Fm;if(ro&&c&&Ni&&ZE(c,i,Ni)){qs=i,Cr===null&&(Cr=requestAnimationFrame(()=>{Cr=null;let f=qs;qs=null,f&&dd(f)}));return}if(i.length===0){Ub(),dd(i);return}Vm(),dd(i)};$=new fp(o,{onMessagesChanged(i){tk(i)},onStatusChanged(i){let c=o.statusIndicator??{};Hn(gt,(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),zt()},onStreamingChanged(i){i||($?.getMessages().length===0?Ub():Vm()),ro=i,nl(i),zt(),$&&ho(We,$.getMessages(),je),i||(Kr(!0),HE(),yb=!0,$&&bb($.getMessages(),ls(o))),bn(),Rc(i?"Responding\u2026":"Response complete."),Oi()},onVoiceStatusChanged(i){if(L.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Mr(),Qi();break;case"processing":Mr(),o0();break;case"speaking":Mr(),r0();break;default:i==="idle"&&$.isBargeInActive()?(Mr(),Qi(),ye?.setAttribute("aria-label","End voice session")):(pt.active=!1,Mr(),hr("system"),Ro());break}},onArtifactsState(i){go=i,i.artifacts.length===0&&(Ti=!1),Rr()?.updateInlineArtifactBlocks(We,i.artifacts,{suppressTransition:ro}),Ho(),Ri()},onHistoryStateChanged(i){mt(i)},onHistoryNotice(i){ct(i)},onReconnect(i){let{executionId:c,lastEventId:f}=i.handle;i.phase==="paused"?L.emit("stream:paused",{executionId:c,after:f}):i.phase==="resuming"?L.emit("stream:resuming",{executionId:c,after:f,attempt:i.attempt??1}):L.emit("stream:resumed",{executionId:c,after:f})}},vr),Pt.current=$,_e.push(()=>$.cancel()),_e.push(()=>{$.destroy(),br?.destroy()});let zm=null;if($.onReadAloudChange((i,c)=>{Gy=i,Yy=c,Qy();let f=i??zm;i&&(zm=i);let y=f?$.getMessages().find(x=>x.id===f)??null:null;L.emit("message:read-aloud",{messageId:f,message:y,state:c,timestamp:Date.now()}),c==="idle"&&(zm=null)}),p=!0,vm=!0,o.voiceRecognition?.provider?.type==="runtype")try{$.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let nk=720,ok=250,yt=oy(o.features?.history?.copy),ao=null,qm=!1,kt=null,pd=null,ud="conversation",Um=null,_n=null,Yo=null,md=$.getHistoryState(),jm=null,sl=0,Km=null,fd=null,gd=null,Gm=`persona-history-${Math.random().toString(36).slice(2,8)}`,Ym=()=>o.features?.history?.enabled===!0,Qo=()=>Ym()&&!!ao&&!qm,jb=()=>{let i=$.getStatus();return ro||i==="paused"||i==="resuming"},Qm=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",f=ao?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},Fi=()=>pd?.scope??Qm(),Kb=()=>$.getClientSession()?.targetId??null,Gb=i=>`${i.state}:${"reason"in i?i.reason:""}`,rk=i=>{let c=Gb(i);c!==jm&&(jm=c,L.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},hd=i=>{i&&(dr.textContent="",dr.textContent=i)},Yb=null,Qb=null,sk=()=>{if(!Ym())return null;let i=HT();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Yb!==c&&(Yb=c,Qb=c()),Qb):$.isClientTokenMode()?RT({client:$.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>$.bindActivatedSession(f),getClient:()=>$.getClient()}):null},Xb=()=>{fd?.(),fd=null,gd?.(),gd=null,qm=!1,ao=sk();let i={...vr};ao?i.historyProvider=ao:delete i.historyProvider,vr=i,$.setHistoryInternals(vr),ao&&(fd=ao.subscribeAvailability?.(c=>{qm=!c,c||Jn({restoreFocus:!1}),Jr()})??null,gd=ao.subscribeIdentityStatus(c=>rk(c)),jm=Gb(ao.getIdentityStatus()))},Xm=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!ue||an(o)))return"panel";let c=jo??Pe;return(c.getBoundingClientRect().width||c.clientWidth)>=nk?"rail":"panel"},yo=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},yd="data-persona-history-suppressed",lo=null,Xr=null,Us=null,il=null,Jm=null,Jb="",Zb=()=>ve===Jm?Jb:o.layout?.showHeader===!1?"none":"",ik=()=>re==="panel"&&!!Us&&il===Us.element&&o.layout?.showHeader!==!1&&Zb()!=="none",ak=()=>{for(let i of Array.from(ve.children))i!==lo&&i.setAttribute(yd,"")},lk=()=>{for(let i of Array.from(Pe.querySelectorAll(`[${yd}]`)))i.removeAttribute(yd)},ck=()=>{let i=Us;if(!i)return;if(Array.from(ve.children).some(y=>y!==lo&&!y.hasAttribute(yd))){Xr&&Xr!==ve&&(Xr.style.removeProperty("min-height"),Xr=null);let y=ve.offsetHeight;y>0&&(ve.style.minHeight=`${y}px`,Xr=ve)}lo||(lo=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==lo&&lo.replaceChildren(f),lo.parentNode!==ve&&ve.appendChild(lo),ak()},ev=()=>{Xr&&(Xr.style.removeProperty("min-height"),Xr=null),lo&&(Us?.setHeaderPlacement("inline"),lo.remove(),lo=null,lk())},bd=null,Zm=()=>{if(bd){if(le.style.display="none",yo(le,!0),Be.hidden=!0,yo(Be,!0),ik()){ck(),ve.style.display=Zb(),yo(ve,!1);return}ev(),ve.style.display="none",yo(ve,!0)}};Le=Zm;let dk=i=>{let c=le.style.display,f=Be.hidden,y=Be,x=ve,P=ve.style.display;Jm=x,Jb=P,bd=()=>{bd=null,ev(),Jm=null,le.style.display=c,yo(le,!1),y.hidden=f,yo(y,!1),Be!==y&&(Be.hidden=!1,yo(Be,!1)),x.style.display=P,yo(x,!1),ve!==x&&(ve.style.display=o.layout?.showHeader===!1?"none":"",yo(ve,!1))},Be.parentNode?.insertBefore(i,Be),Zm()},$i=null,js=null,al=null,Vi=null,tv=()=>[ve,Qe.closeButtonWrapper,Qe.clearChatButtonWrapper,le,Be],pk=52,vd=()=>o.features?.history?.rail?.collapsible!==!1,zi=()=>o.features?.history?.rail?.side==="right"?"right":"left",ef=200,tf=400,nf=i=>Math.min(tf,Math.max(ef,Math.round(i))),uk=()=>o.features?.history?.rail?.resizable===!0,ll,mk=()=>{if(ll===void 0&&(ll=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Ge()}rail-width`));i&&(ll=i)}catch{}return ll},cl=()=>nf(mk()??o.features?.history?.rail?.width??260),fk=i=>{if(ll=i,o.persistState!==!1)try{window.localStorage.setItem(`${Ge()}rail-width`,String(i))}catch{}},Cd=()=>vd()&&o.features?.history?.rail?.collapsedBehavior==="overlay",un=!1,nv=i=>{let c=v("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},gk=()=>{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=nv(i.iconUrl):f=i.icon?He(i.icon,20):null),f?f.cloneNode(!0):null}},hk=()=>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=nv(y.iconUrl):x=y.icon?He(y.icon,20):null}catch(P){f(P),x=null}return x},onSelect:()=>{try{y.onSelect()}catch(P){f(P)}}}})}})??[],yk=i=>{let c=hk();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},dl=null,ov=()=>`${Ge()}rail-collapsed`,of=()=>{if(dl===null&&(dl=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(ov());i&&(dl=i==="1")}catch{}return dl},rf=i=>{if(dl=i,o.persistState!==!1)try{window.localStorage.setItem(ov(),i?"1":"0")}catch{}},pl=()=>re==="rail"&&vd()&&!Cd()&&of(),sf=()=>{},rv=()=>{if(Cd()){sf();return}rf(!of()),kt?.view.setCollapsed(pl()),Me(),Xn()},af=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!ou(i)?null:{combo:i,hint:ru(i),aria:Ql(i)}},sv=()=>{d.forEach(c=>c()),d=[];let i=af();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>J&&re==="rail"&&vd()||Ui(),run:()=>Cd()?sf():rv()}));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}`}))};sv();let bk=300,wd="var(--persona-history-overlay-margin,8px)",bo=null,wr=null,xd=0,xr=null,qi=null,Ks=!1,lf=0,iv=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ui=()=>Qo()&&Cd()&&(re??Xm())==="rail",vk=()=>J&&!un,ul=()=>{qi!==null&&clearTimeout(qi),qi=null},Ck=()=>{my().catch(()=>{})},av=()=>{ul(),un&&(qi=setTimeout(()=>{qi=null,!(Ks||!un)&&(xr?.contains(document.activeElement)||Jn({restoreFocus:!1}))},bk))},wk=(i,c)=>{let f=xr?.getBoundingClientRect();if(!f)return!1;let y=bo?.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},cf=i=>{un&&(Ks=wk(i.clientX,i.clientY),Ks?ul():qi===null&&av())},lv=i=>{J||!Ui()||(un=!0,fl({invoker:bo,keyboard:i?.keyboard===!0}).then(()=>{J?!Ks&&document.activeElement!==bo&&Jn():un=!1}))},cv=()=>{let i=il?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",un?yt.expandLabel:yt.collapseLabel),i.setAttribute("aria-expanded",un?"false":"true"))},dv=()=>{rf(!1);let i=kt;if(!un||!i){fl({invoker:bo});return}let c=document.activeElement===bo;un=!1,Sd(),i.element.remove(),pf(i.element),cv(),c&&Md(),Xn(),Jr()},xk=()=>{rf(!0),Jn()};sf=()=>{!J||un?dv():xk()};let Sk=()=>{let i=af(),c=si({ariaLabel:yt.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":Gm,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{Ks=!0,ul(),!(iv()||Date.now()<lf)&&lv()}),f.addEventListener("mouseleave",()=>{Ks=!1,lf=0,av()}),f.addEventListener("focus",()=>{J||Ck()}),f.addEventListener("click",y=>{Qo()&&(y.detail!==0&&iv()&&!J?lv():dv())}),bo=f,wr=c.wrapper},ml=()=>{if(wr&&!wr.isConnected&&(wr=null,bo=null),!Ui()){wr?.remove(),wr=null,bo=null;return}bo||Sk();let i=wr,c=bo;if(!i||!c)return;let f=zi()!=="right"?ve.firstChild:null;(f??ve.lastChild)!==i&&ve.insertBefore(i,f),i.style.display=vk()||xd>0?"none":"",c.setAttribute("aria-label",yt.expandLabel),c.setAttribute("aria-expanded",J?"true":"false"),xr&&Me()},pv=i=>{if(!un)return;let c=i.target;c instanceof Node&&(xr?.contains(c)||wr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Jn({restoreFocus:!1}))};document.addEventListener("pointerdown",pv,!0),_e.push(()=>{document.removeEventListener("pointerdown",pv,!0),document.removeEventListener("pointermove",cf),ji?.(),ul()});let df=null,ji=null,uv=16,mv=i=>{fk(nf(i)),Me(),Xn()},Ak=()=>{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(ef)),i.setAttribute("aria-valuemax",String(tf)),i.addEventListener("pointerdown",c=>{let f=js;if(!f||c.button!==0)return;c.preventDefault(),ji?.();let y=c.clientX,x=f.getBoundingClientRect().width||cl(),P=zi()==="right"?-1:1,Y=x,ne=t.ownerDocument;f.style.transition="none";let te=fe=>{Y=nf(x+P*(fe.clientX-y)),f.style.flex=`0 0 ${Y}px`,i.setAttribute("aria-valuenow",String(Y))},oe=()=>{ji=null,ne.removeEventListener("pointermove",te),ne.removeEventListener("pointerup",oe),ne.removeEventListener("pointercancel",oe),f.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}mv(Y)};ji=oe,ne.addEventListener("pointermove",te),ne.addEventListener("pointerup",oe),ne.addEventListener("pointercancel",oe);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let f=zi()==="right"?-uv:uv,y=cl(),x=c.key==="ArrowRight"?y+f:c.key==="ArrowLeft"?y-f:c.key==="Home"?ef:c.key==="End"?tf:null;x!==null&&(c.preventDefault(),mv(x))}),i},Mk=(i,c)=>{if(!uk()||pl()){ji?.(),df?.remove();return}let f=df??Ak();df=f,f.setAttribute("aria-label",yt.resizeLabel),f.setAttribute("aria-valuenow",String(cl())),f.nextElementSibling!==c&&i.insertBefore(f,c)};Me=()=>{kt?.view.setRailSide(zi());let i=zi()==="right",c=xr;if(c){let ne=bo?bo.getBoundingClientRect().bottom-Pe.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(ne))}px + ${wd})`,c.style.width=`${cl()}px`,c.style.left=i?"":wd,c.style.right=i?wd:""}let f=js,y=$i,x=al;if(!f||!y||!x)return;f.style.flex=`0 0 ${pl()?pk:cl()}px`;let P="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":P,f.style.borderLeft=i?P:"";let Y=i?x:f;y.firstElementChild!==Y&&y.append(Y,i?f:x),Mk(y,i?f:x)};let fv=i=>{if(Vi&&js){Vi.replaceWith(i),Vi=null,Me();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",Pe.insertBefore(c,ve.parentNode===Pe?ve:le);for(let x of tv())x?.parentNode===Pe&&f.appendChild(x);c.append(y,f),y.appendChild(i),$i=c,js=y,al=f,Me()},Tk=()=>{if($i)return;let i=v("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",Vi=i,fv(i),Xn()},gv=()=>{Vi&&(Sd(),Xn())},Ek=i=>{let c=v("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${wd};display:flex;overflow:hidden;z-index:${ua-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Pe.style.position="relative",Pe.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",cf),xr=c,Me(),cv()},Sd=()=>{bd?.(),xr&&(Ks&&(lf=Date.now()+150),document.removeEventListener("pointermove",cf),xr.remove(),xr=null);let i=$i;if(i){ji?.();for(let c of tv())c&&i.contains(c)&&Pe.insertBefore(c,i);i.remove(),$i=null,js=null,al=null,Vi=null}},hv=i=>{il=i,i.id=Gm,i.style.flex="1 1 auto",i.style.minHeight="0"},pf=i=>{hv(i),(re!=="rail"||un)&&gv(),re!=="rail"?dk(i):un?Ek(i):fv(i)},Ad=()=>{if(ml(),Ev(),!J||!kt)return;let i=Xm();if(i===re)return;let c=document.activeElement,f=c instanceof HTMLElement&&(kt.element.contains(c)||lo?.contains(c)===!0)?c:null;Sd(),kt.element.remove(),kt.view.setHeaderPlacement("inline"),re=i,kt.view.setPresentation(i),kt.view.setCollapsed(pl()),kt.requestRender(),kt.element.isConnected||pf(kt.element),f?.isConnected?f.focus():Md(),bn(),Xn(),Jr()},yv=(i,c)=>lo?.querySelector(c)??i.querySelector(c),Md=()=>{let i=kt?.element??il;if(!i)return;let c=yv(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=yv(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},fl=async i=>{if(!Qo()||J)return;let c=ao;if(!c)return;if(!un&&Ui()&&of()){ml();return}Td();let f=++sl;ud=i?.returnSurface??"conversation",Um=i?.invoker??_n;let y=Ui()&&!un;y&&(xd+=1,ml(),Tk());let x;try{x=await my()}catch{hd(yt.openHistoryLabel),y&&(xd-=1,f===sl&&(gv(),ml()));return}if(y&&(xd-=1),f!==sl||J)return;pd={scope:Qm()},re=Xm(),J=!0;let P=re==="panel"&&o.layout?.showHeader!==!1&&ve.style.display!=="none"?"external":"inline",Y=o.features?.history?.rowAvatar,ne=af(),te=ne?{hint:ne.hint,aria:ne.aria}:null,oe={provider:c,context:pd,targetId:Kb(),presentation:re,collapsible:vd(),collapsed:pl(),railSide:zi(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:gk(),onToggleCollapse:rv,...te?{collapseShortcut:te}:{},headerPlacement:P,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:Y===!1?!1:typeof Y=="string"?Y: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:fe=>mf(fe,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:fe=>Gs(fe),attachTooltip:Tn,onStartNew:()=>ff({focusComposer:!0}),onClose:()=>Jn(),onRequestDeleteConversation:fe=>Tv(fe),onRequestClearHistory:()=>Rk(),...c.resetDevice?{onRequestResetIdentity:()=>Wk()}:{}};kt=IT({plugins:a,config:o,getPresentation:()=>re??"panel",getReturnSurface:()=>ud,close:()=>Jn(),createView:({slots:fe,renderDom:Se,onModelChange:Re,railSections:bt})=>(Us=x.createHistoryView({...oe,railSections:yk(bt),slots:fe,renderDom:Se,onModelChange:Re,onAnnounce:hd}),Us),onElementChanged:(fe,Se)=>{if(!Se?.isConnected)return pf(fe);hv(fe),Se.replaceWith(fe),Zm()}}),kt.view.setNewConversationRequired(md.recovery==="new_conversation_required"),i?.focus!==!1&&(re!=="rail"||i?.keyboard===!0)&&Md(),bn(),Xn(),Jr(),L.emit("history:opened",{presentation:re,returnSurface:ud,timestamp:Date.now()})},Td=()=>{},Jn=i=>{if(!J)return;sl+=1;let c=ud,f=Um,y=kt,x=i?.restoreFocus!==!1;J=!1;let P=!1,Y=null,ne=()=>{if(!P){if(P=!0,Td=()=>{},Y!==null&&clearTimeout(Y),un=!1,ul(),Sd(),y?.dispose(),y?.view.destroy(),y?.element.remove(),kt===y&&(kt=null,Us=null,il=null,re=null,pd=null,Um=null),bn(),Xn(),Jr(),x){let oe=f??_n;oe?.isConnected?oe.focus():$s()}L.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},te=y&&y.element===y.view.element?y.view.playExit():null;if(!te){ne();return}Td=ne,Y=setTimeout(ne,ok),te.then(ne)},bv=i=>{if(!(i.key!=="Escape"||!J||!kt)){if(re==="rail"){let c=i.target;if(!(c instanceof Node)||!(kt.element.contains(c)||un&&wr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Jn()}};Pe.addEventListener("keydown",bv),_e.push(()=>Pe.removeEventListener("keydown",bv));let Ed=null,vv=!1,gl=()=>{if(!De)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Ed?.trim()||null;De.textContent=c??o.launcher?.title??"Chat Assistant";let f=De.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")},kk=i=>{i!==Ed&&(Ed=i,gl())},Gs=i=>{vv=i?.starred===!0,kk(i&&i.title.trim()||null),gl()};gl(),Pe.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,f=$.getActiveConversationId();f&&(c==="delete"?Tv(f):c==="star"&&$.canUpdateConversations()&&gf(f,{starred:!vv}).catch(()=>{}))});let kd=0,Lk=250,Ld=null,Pd=()=>{Ld&&clearTimeout(Ld),Ld=null};_e.push(Pd);let Cv=()=>{Pd();let i=Vs;i&&(ol=!0,i.hidden=!1,We.style.display="none",rl())},Id=()=>{kd+=1,Pd(),Vs&&(Vs.remove(),Vs=null,ol=!1,We.style.removeProperty("display"),yo(Be,!1),rl())},Pk=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;We.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},uf=(i,c)=>q("div",{className:Bt("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),wv=()=>q("div",{className:"persona-conversation-loading-body"},uf("58%",!1),uf("72%",!0),uf("44%",!1)),xv=i=>{Vs?.remove(),Vs=i,i.hidden=!ol,le.insertBefore(i,We),Pd(),ol||(Ld=setTimeout(Cv,Lk)),yo(Be,!0)},Ik=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:wv},c=null,f=a.find(y=>y.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),xv(q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":yt.openConversationLoadingLabel}},c??wv()))},Hk=i=>{let c=()=>{mf(i,{focusComposer:!0}).catch(()=>{})},f=Qo()?()=>{Id(),fl()}:void 0,y=(ne,te)=>{let oe=q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:ne});return oe.addEventListener("click",te),oe},x=()=>q("div",{className:"persona-conversation-loading-error-body"},q("p",{className:"persona-conversation-loading-error-title",text:yt.openConversationErrorTitle}),q("div",{className:"persona-conversation-loading-error-actions"},y(yt.openConversationRetryLabel,c),f?y(yt.openConversationBackLabel,f):null)),P=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:yt.openConversationErrorTitle,retryLabel:yt.openConversationRetryLabel,backLabel:yt.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:x}),Y=null;for(let ne of a)if(ne.renderHistoryOpenError){try{Y=ne.renderHistoryOpenError(P)}catch(te){console.warn("[persona] renderHistoryOpenError threw",te),Y=null}if(Y)break}xv(q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Y??x())),Cv()};L.on("history:closed",()=>{Vs&&yo(Be,!0)});let mf=async(i,{focusComposer:c=!1}={})=>{let f=Fi(),y=!!kt;kt?.view.setActiveConversationId(i),Id();let x=kd;Ik(),J&&(re==="panel"||un)&&Jn({restoreFocus:!1}),Ii=!0;try{await $.openConversation(i,{scope:f})}catch(P){throw x===kd&&Hk(i),P}finally{Ii=!1}x===kd&&(Id(),pn.clear(),Wo(),Qn(),Tm()||td(),Pk(),Sr(),y||Gs(null),L.emit("history:conversationOpened",{conversationId:i,title:Ed,scope:f,timestamp:Date.now()}),c&&$s())},ff=async({focusComposer:i=!1}={})=>{Id(),await $.startNewConversation({scope:Fi()}),Gs(null),pn.clear(),Wo(),Qn(),td(),Sr();let c=$.getActiveConversationId();kt?.view.setActiveConversationId(c),L.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),J&&(re==="panel"||un)&&Jn({restoreFocus:!1}),i&&$s()},gf=async(i,c)=>{let f=await $.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return kt?.view.applyConversationSummary(f),!kt&&i===$.getActiveConversationId()&&Gs(f),f},Sv=async i=>{let c=Fi(),f=$.getActiveConversationId()===i;await $.deleteConversation(i,{scope:c}),kt?.view.removeConversationSummary(i),f&&(Gs(null),pn.clear(),Wo(),Qn(),Sr()),L.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:f,timestamp:Date.now()})},Av=async i=>{let c=i?.scope??Fi(),f=i?.allTargets?null:i?.targetId??Kb(),y=await $.clearConversationHistory({...f?{targetId:f}:{},scope:c});return Gs(null),pn.clear(),Wo(),Qn(),Sr(),L.emit("history:cleared",{deleted:y.deleted,scope:c,targetId:f,timestamp:Date.now()}),y},Mv=async()=>{if(!ao?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await $.resetHistoryDevice()).remoteRevocationConfirmed}finally{Gs(null),$.clearArtifacts(),pn.clear(),Fm=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),H={},pe.syncFromMetadata(),W?.clear&&Jc(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),Wo(),Qn(),Sr(),Jn({restoreFocus:!1}),$s(),Te||en?.launcher.element.focus()}return hd(i?yt.identityResetNotice:yt.identityResetUnconfirmedNotice),L.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},hf=()=>jo?Fe:Pe,Tv=async i=>await Yu({host:hf(),title:yt.deleteConversationConfirmTitle,description:yt.deleteConversationConfirm,confirmLabel:yt.deleteConversationConfirmLabel,cancelLabel:yt.confirmCancelLabel})?(await Sv(i),"deleted"):"cancelled",Rk=async()=>{let i=Fi()==="verified-user";return await Yu({host:hf(),title:yt.clearHistoryConfirmTitle,description:i?yt.clearHistoryVerifiedConfirm:yt.clearHistoryConfirm,confirmLabel:yt.clearHistoryConfirmLabel,cancelLabel:yt.confirmCancelLabel})?(await Av(),"cleared"):"cancelled"},Wk=async()=>{if(!await Yu({host:hf(),title:yt.resetIdentityConfirmTitle,description:yt.resetIdentityConfirm,confirmLabel:yt.resetIdentityConfirmLabel,cancelLabel:yt.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Mv();return{outcome:"reset",remoteRevocationConfirmed:c}},vo=v("button","persona-history-earlier");vo.type="button",vo.textContent=yt.showEarlierMessagesLabel,vo.setAttribute("data-persona-history-earlier",""),Object.assign(vo.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Sr=()=>{if(!(Qo()&&!!md.nextMessageCursor&&!!$.getActiveConversationId())){vo.remove();return}vo.textContent=yt.showEarlierMessagesLabel,vo.parentNode!==le&&le.insertBefore(vo,le.firstChild)};vo.addEventListener("click",()=>{let i=$.getActiveConversationId(),c=md.nextMessageCursor;if(!i||!c||vo.disabled)return;vo.disabled=!0;let f=le.scrollHeight,y=le.scrollTop;$.loadOlderMessages(i,c,{scope:Fi()}).then(()=>{le.scrollTop=y+(le.scrollHeight-f),Xn()}).catch(()=>{}).finally(()=>{vo.disabled=!1,Sr()})});let Bk=()=>{let i=si({ariaLabel:yt.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(!(!Qo()||jb())){if(J){Jn();return}fl({invoker:i.button,keyboard:c.detail===0})}}),i},Ev=()=>{if(!Qo()){Yo?.remove(),_n=null,Yo=null;return}if(Yo&&!Yo.isConnected&&(_n=null,Yo=null),!_n&&ve){let y=Bk();_n=y.button,Yo=y.wrapper;let x=Qe.clearChatButtonWrapper||Qe.closeButtonWrapper;x?.parentNode&&ve.contains(x)?x.parentNode.insertBefore(Yo,x):ve.appendChild(Yo)}if(!_n||!Yo)return;let i=Ui()||J&&re==="rail";if(Yo.style.display=i?"none":"",i){document.activeElement===_n&&Md();return}let c=jb();_n.disabled=c,_n.setAttribute("aria-disabled",c?"true":"false");let f=c?yt.openHistoryBusyLabel:yt.openHistoryLabel;_n.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(_n.removeAttribute("aria-expanded"),_n.removeAttribute("aria-controls")):(_n.setAttribute("aria-expanded",J?"true":"false"),_n.setAttribute("aria-controls",Gm))},Hd=!1,Ok=()=>{let i=Qe.clearChatButton;if(i){if(Qo()){Hd||(Km=i.getAttribute("aria-label")??"",Hd=!0),i.setAttribute("aria-label",yt.newConversationLabel),i.removeAttribute("title");return}Hd&&(Hd=!1,Km&&i.setAttribute("aria-label",Km))}},Jr=()=>{yt=oy(o.features?.history?.copy),Ev(),ml(),Ok(),Sr()};zt=Jr,mt=i=>{md=i,kt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),nl(i.sendBlocked||ro),Sr()},ct=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(pn.clear(),Wo(),Qn()),hd(i.message),kt?.view.refresh()},Xb(),Jr(),_e.push(()=>{fd?.(),gd?.(),sl+=1,Td(),kt?.dispose(),kt?.view.destroy(),kt=null}),o.clientToken&&$.initClientSession().then(()=>{if(Qo())return $.reconcileBootConversation({scope:Qm()})}).then(()=>{Sr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(It||o.onSSEEvent)&&$.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),ee(i,c)});let kv=()=>{let i=o.resume??(z?vr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(i)};w?w.then(i=>{if(i){if(i.metadata&&(H=by(i.metadata),pe.syncFromMetadata()),i.messages?.length){Ii=!0;try{$.hydrateMessages(i.messages)}finally{Ii=!1}sd()}i.artifacts?.length&&$.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),Ab(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Hm=!0,k(),kv()}):(Ab(_),kv());let Dk=()=>{!ke()||Te||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Rt(!0,"auto")},_k=(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),HB(x)}}:i:c,yf=()=>{let c=Ae.getInlineMessageFields?.();return c&&c.contentSegments.some(y=>y.kind==="mention")?c.contentSegments:void 0},Ar=!1,Ys=null,Rd=()=>{Ae.value="",Ae.style.height="auto",zo(),yl()},bf="data-persona-composer-notice",Ki=null;function Nk(i){Rc(i),!(ke()||!gt)&&(gt.hasAttribute(Wa)||(gt.setAttribute(bf,""),gt.setAttribute("role","status"),gt.setAttribute("aria-live","polite"),gt.textContent=i,Ki&&clearTimeout(Ki),Ki=setTimeout(()=>{if(Ki=null,!!gt?.hasAttribute(bf)&&(gt.removeAttribute(bf),gt.removeAttribute("role"),gt.removeAttribute("aria-live"),p)){let c=$.getStatus();Hn(gt,xt(c),o.statusIndicator??{},c)}},4e3)))}function Fk(){let i=Ve.getState().pendingSubmission;i&&(Si(void 0),Ae&&(Ae.value=i.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),zo()),i.options.selectedModelId&&(Ve.setSelectedModelId(i.options.selectedModelId),Fr?.repaint()),i.options.activeModeIds?.length&&Dc(i.options.activeModeIds),i.options.quote&&qo(i.options.quote),Ae?.focus())}let $k=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},Lv=(i={})=>{let c=(i.overrideText??Ae?.value??"").trim();return i.resolveInlineCommand&&c?(sn?.takeInlineCommand(c)??Promise.resolve(null)).then(f=>Pv(i,c,f)):Pv(i,c,null)},Pv=(i,c,f)=>{if(f?.kind==="action"){Rd(),sn?.clear(),As();return}let y=f?.kind==="server"?f.mentions:null,x=f?.kind==="prompt"?f.sendText:c,P=i.pending?.contentParts,Y=(Ct?.hasAttachments()??!1)||(P?.length??0)>0;if(!Vx({text:x,hasAttachments:Y,attachmentsReady:Ct?.isReady()??!0,hasMentions:sn?.hasMentions()??!1,hasServerMentions:!!y,inputDisabled:Yr(),sendDisabled:Fs()}))return;let ne=$.isStreaming()?im():"block";if(ne==="defer-one"&&!i.pending){if(Ve.getState().pendingSubmission){Nk("One message is already queued. Edit or remove it first.");return}Vk({intent:i,sendText:x,serverMentions:y});return}let te={text:x,mentionRefs:[...sn?.getMentionRefs()??[],...y?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:yf(),options:{...Ve.getState().selectedModelId&&{selectedModelId:Ve.getState().selectedModelId},...Ve.getState().activeModeIds.length>0&&{activeModeIds:[...Ve.getState().activeModeIds]},...Ve.getState().quote&&{quote:{...Ve.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(te.options={...i.pending.options},te.contentSegments=i.pending.contentSegments,te.mentionRefs=[...i.pending.mentionRefs],te.viaVoice=i.pending.viaVoice);let oe=()=>{if(P?.length)return[...P];if(!Ct?.hasAttachments())return;let Wt=[...Ct.getContentParts()];return te.text&&Wt.push(nr(te.text)),Wt};te.contentParts=oe();let fe=()=>{Rs(),Dk();let Wt=sn?.collectForSubmit()??null,Sn=_k(Wt,y),mn=oe();i.consumeDraft!==!1&&Rd();let nn={selectedModelId:te.options.selectedModelId,activeModeIds:te.options.activeModeIds},Wn=ne==="interrupt";Wn&&$.cancel(),$.sendMessage(te.text,{contentParts:mn,mentions:Sn??void 0,contentSegments:te.contentSegments,viaVoice:te.viaVoice,composerOptions:nn,...te.options.quote&&{quote:te.options.quote},...Wn&&{interrupt:!0}}),Ct?.hasAttachments()&&Ct.clearAttachments(),Wt&&sn?.clear(),As();let wt=Ve.getState().activeModeIds,Bn=kx(wt,o.composer?.modes);Bn.length!==wt.length&&Dc(Bn),Ve.getState().quote&&qo(void 0),ed(),pm.release(),Po()},Se=o.composer?.onBeforeSend;if(!Se){fe();return}let Re=new AbortController;Ys=Re;let bt=Wt=>{if(Ys=null,Wt.status==="error"){$k(Wt.error);return}Wt.status==="proceed"&&fe()},Ht=zx(Se,te,Re.signal);if(!(Ht instanceof Promise)){bt(Ht);return}return Ve.setPreparing(!0),Ht.then(bt).finally(()=>Ve.setPreparing(!1))};function Vk(i){let c=Ve.getState(),f=Ct?.hasAttachments()??!1,y=f?[...Ct.getContentParts()]:[];f&&i.sendText&&y.push(nr(i.sendText));let x=Eg({text:i.sendText,contentParts:y.length?y:void 0,mentionRefs:[...sn?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:yf(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Si(x),i.intent.consumeDraft!==!1&&Rd(),f&&Ct.clearAttachments(),sn?.clear(),As(),c.quote&&qo(void 0),ed(),pm.release(),Po(),Rc("Message queued. It sends when the response finishes.")}function zk(){let i=Ve.getState().pendingSubmission;i&&(Si(void 0),Bd(i.text,{consumeDraft:!1,pending:i}))}function qk(i){if(o.messageActions?.showEdit!==!0)return;let c=$.getMessages().find(f=>f.id===i);!c||!Xf(c)||Hs!==i&&(Rs(),Hs=i,qr=Rx({messageId:i,initialText:c.content,onSave:f=>Uk(i,f),onCancel:()=>Rs()}),pn.delete(i),ho(We,$.getMessages(),je),qr.focus())}function Uk(i,c){let f=qr;if(Hs=null,qr=null,f?.destroy(),pn.delete(i),!$.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){ho(We,$.getMessages(),je);return}Xn()}function jk(i){if($.isStreaming())return;let c=Qf($.getMessages(),i);c&&(Rs(),$.resubmitFrom(c,{reason:"retry"})&&Xn())}_c={regenerate:jk,edit:qk,quote:i=>{let f=$.getMessages().find(y=>y.id===i)?.content?.trim();f&&(qo({text:f,messageId:i}),Ae?.focus())}};let hl=async i=>{if(!Ar){Ar=!0;try{await Lv({resolveInlineCommand:!0,...i})}finally{Ar=!1}}};function Wd(i){Fs()||(Rd(),Bd(i,{consumeDraft:!1}))}let Bd=(i,c)=>{if(Ar)return;Ar=!0;let f=()=>{Ar=!1};try{let y=Lv({...c,overrideText:i});y instanceof Promise?y.finally(f):f()}catch(y){throw f(),y}},Kk=i=>{if(i.preventDefault(),$.isStreaming()){$.cancel(),Zt?.reset(),ae?.update();return}Ar||hl()},Gk=()=>o.features?.composerHistory!==!1,vf={...Ug},Cf=!1,yl=()=>{vf={...Ug}},Yk=()=>$.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Qk=i=>{if(!Ae)return;Cf=!0,Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Cf=!1;let c=Ae.value.length;Ae.setSelectionRange(c,c)},Xk=i=>{Cf||(i.isComposing||sn?.handleInput(i.inputType??void 0),yl())},Jk=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Fl(Ae)}),Zk=i=>{if(Ae&&!Yr()&&!(!i.isComposing&&sn?.handleKeydown(i))){if(Gk()&&(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=_S({direction:i.key==="ArrowUp"?"up":"down",history:Yk(),currentValue:Ae.value,atStart:c,state:vf});if(vf=f.state,f.handled){i.preventDefault(),f.value!==void 0&&Qk(f.value);return}}if(cx(i,Jk())){if($.isStreaming()){if(i.preventDefault(),im()==="block"||Ar||Fs())return;yl(),hl();return}if(Ar){i.preventDefault();return}if(Fs()){i.preventDefault();return}yl(),i.preventDefault(),$e.click()}}},Iv=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(Pe)){if(Ys){Ys.abort(),Ys=null,i.preventDefault(),i.stopImmediatePropagation();return}$.isStreaming()&&($.cancel(),Zt?.reset(),ae?.update(),yl(),i.preventDefault(),i.stopImmediatePropagation())}},e0=async i=>{if(o.attachments?.enabled!==!0||!Ct||Yr())return;let c=kB(i.clipboardData);c.length!==0&&(i.preventDefault(),await Ct.handleFiles(c))},Co=null,Xo=!1,Gi=null,Ut=null,wf=()=>o.voiceRecognition?.completionBehavior==="review";function Qs(i){ye?.setAttribute("data-state",i),i==="recording"?n0():Mf()}let Hv="--persona-voice-level",xf=.5,Yi=null,Sf=-1,Od=0,Rv=()=>{let i=[],c=no??ye?.parentElement??null;return c&&i.push(c),Be&&i.push(Be),i},Af=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Sf){Sf=c;for(let f of Rv())f.style.setProperty(Hv,String(c))}},t0=()=>{Sf=-1,Od=0;for(let i of Rv())i.style.removeProperty(Hv)};function n0(){if(Yi!==null)return;if(typeof requestAnimationFrame!="function"){Af(p?$.getVoiceLevel()??xf:xf);return}let i=()=>{Yi=requestAnimationFrame(i);let c=p?$.getVoiceLevel():null;if(c===null){Af(xf);return}Od+=(c-Od)*.3,Af(Od)};Yi=requestAnimationFrame(i)}function Mf(){Yi!==null&&(cancelAnimationFrame(Yi),Yi=null),t0()}let Wv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Dd=(i="user")=>{if(Xo||$.isStreaming())return;let c=Wv();if(!c)return;Co=new c;let f=o.voiceRecognition??{},y=f.pauseDuration??2e3;Co.continuous=f.provider?.browser?.continuous??!0,Co.interimResults=!0,Co.lang=f.provider?.browser?.language??"en-US";let x=Ae.value;Co.onresult=P=>{let Y="",ne="";for(let oe=0;oe<P.results.length;oe++){let fe=P.results[oe],Se=fe[0].transcript;fe.isFinal?Y+=Se+" ":ne=Se}let te=x+Y+ne;Ae.value=te,zo(),Gi&&clearTimeout(Gi),(Y||ne)&&(Gi=window.setTimeout(()=>{if(Ae.value.trim()&&Co&&Xo){if(Zr(),wf())return;hl({viaVoice:!0})}},y))},Co.onerror=P=>{P.error!=="no-speech"&&Zr()},Co.onend=()=>{if(Xo){let P=Ae.value.trim();!wf()&&P&&P!==x.trim()&&hl({viaVoice:!0}),Zr()}};try{if(Co.start(),Xo=!0,pt.active=!0,i!=="system"&&(pt.manuallyDeactivated=!1),hr(i),Ro(),Po(),ye){let P=o.voiceRecognition??{};Ut={backgroundColor:ye.style.backgroundColor,color:ye.style.color,borderColor:ye.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??"")||$n};let Y=P.recordingBackgroundColor,ne=P.recordingIconColor,te=P.recordingBorderColor;if(ye.classList.add("persona-voice-recording"),Qs("recording"),ye.style.backgroundColor=Y??"var(--persona-voice-recording-bg, #ef4444)",ye.style.color=ne??"var(--persona-voice-recording-indicator, #ffffff)",ne){let oe=ye.querySelector("svg");oe&&oe.setAttribute("stroke",ne)}te&&(ye.style.borderColor=te),ye.setAttribute("aria-label","Stop voice recognition")}}catch{Zr("system")}},Zr=(i="user")=>{if(Xo){if(Xo=!1,Gi&&(clearTimeout(Gi),Gi=null),Co){try{Co.stop()}catch{}Co=null}if(pt.active=!1,hr(i),Ro(),Po(),ye){if(ye.classList.remove("persona-voice-recording"),Qs("idle"),Ut){ye.style.backgroundColor=Ut.backgroundColor,ye.style.color=Ut.color,ye.style.borderColor=Ut.borderColor;let c=ye.querySelector("svg");c&&c.setAttribute("stroke",Ut.color||"currentColor"),Ut=null}ye.setAttribute("aria-label","Start voice recognition")}}},Tf=()=>{if(!ye||Ut)return;let i=o.voiceRecognition??{};Ut={backgroundColor:ye.style.backgroundColor,color:ye.style.color,borderColor:ye.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||$n}},Ef=(i,c)=>{if(!ye)return;let f=ye.querySelector("svg");f&&f.remove();let y=Ut?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||$n),x=He(i,y,c,1.5);x&&ye.appendChild(x)},_d=()=>{ye&&ye.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qi=()=>{if(!ye)return;Tf();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,f=i.recordingIconColor,y=i.recordingBorderColor;if(_d(),ye.classList.add("persona-voice-recording"),Qs("recording"),ye.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",ye.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let x=ye.querySelector("svg");x&&x.setAttribute("stroke",f)}y&&(ye.style.borderColor=y),ye.setAttribute("aria-label","Stop voice recognition")},o0=()=>{if(!ye)return;Tf();let i=o.voiceRecognition??{},c=$.getVoiceInterruptionMode(),f=i.processingIconName??"loader",y=i.processingIconColor??Ut?.color??"",x=i.processingBackgroundColor??Ut?.backgroundColor??"",P=i.processingBorderColor??Ut?.borderColor??"";_d(),ye.classList.add("persona-voice-processing"),Qs("processing"),ye.style.backgroundColor=x,ye.style.borderColor=P;let Y=y||"currentColor";ye.style.color=Y,Ef(f,Y),ye.setAttribute("aria-label","Processing voice input"),c==="none"&&(ye.style.cursor="default")},r0=()=>{if(!ye)return;Tf();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??Ut?.color??"":Ut?.color??""),P=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ut?.backgroundColor??""),Y=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Ut?.borderColor??"");_d(),ye.classList.add("persona-voice-speaking"),Qs("speaking"),ye.style.backgroundColor=P,ye.style.borderColor=Y;let ne=x||"currentColor";ye.style.color=ne,Ef(y,ne);let te=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";ye.setAttribute("aria-label",te),c==="none"&&(ye.style.cursor="default"),c==="barge-in"&&ye.classList.add("persona-voice-recording")},Mr=()=>{ye&&(_d(),Qs("idle"),Ut&&(ye.style.backgroundColor=Ut.backgroundColor??"",ye.style.color=Ut.color??"",ye.style.borderColor=Ut.borderColor??"",Ef(Ut.iconName,Ut.color||"currentColor"),Ut=null),ye.style.cursor="",ye.setAttribute("aria-label","Start voice recognition"))},kf=()=>{if(!Yr()){if(o.voiceRecognition?.provider?.type==="runtype"){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(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Ro(),hr("user"),Mr()});return}$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),pt.manuallyDeactivated=!$.isVoiceActive(),Ro(),hr("user"),$.isVoiceActive()?Qi():Mr()});return}if(Xo){let i=Ae.value.trim();pt.manuallyDeactivated=!0,Ro(),Zr("user"),i&&!wf()&&hl()}else pt.manuallyDeactivated=!1,Ro(),Dd("user")}};am=kf,ye&&_e.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Mr()):Zr("system")});let s0=L.on("assistant:complete",()=>{Ve.getState().pendingSubmission&&setTimeout(()=>{$.isStreaming()||zk()},0)});_e.push(s0);let i0=L.on("assistant:complete",()=>{wb&&(pt.active||pt.manuallyDeactivated||wb==="assistant"&&!pt.lastUserMessageWasVoice||setTimeout(()=>{!pt.active&&!pt.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),hr("auto"),$.isVoiceActive()&&Qi()}):Dd("auto"))},600))});_e.push(i0);let a0=L.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});_e.push(a0);let Bv=()=>{Rt(!Te,"user")},en=null,Nn=null;if(ue&&!ke()){let{instance:i,element:c}=bh({config:o,plugins:a,onToggle:Bv});en=i,i||(Nn=c)}en?t.appendChild(en.element):Nn&&t.appendChild(Nn),tl(),Li(),ld(),Dm(),nl($.isStreaming()),Tm()||(oo()==="follow"?Kr(!0):td()),TE(),be&&(!ue||ke()?setTimeout(()=>$s(),0):Te&&setTimeout(()=>$s(),200));let Xs=null,Ov=()=>{Xs&&(Xs.disconnect(),Xs.observe(Be),Xs.observe(Pe))},bl=()=>{if(ke()){Ss(),tl();return}let i=an(o),c=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640,P=f.innerWidth<=x,Y=y&&P&&ue;try{if(Y){Ms(),Ua=jc();return}let ne=!1;qe&&(qe=!1,Ms(),ne=!0);let te=jc();if(!ne&&te!==Ua&&(Ms(),ne=!0),Ua=te,ne&&Vc(),!ue&&!i){Fe.style.height="",Fe.style.width="";return}if(!c&&!i){let fe=o?.launcher?.width??o?.launcherWidth??Pr;Fe.style.width=fe,Fe.style.maxWidth=fe}Uc(),sb()}finally{if(Ss(),Oc(),tl(),Te&&ue){let te=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),oe=o.launcher?.sidebarMode??!1,fe=o.launcher?.mobileFullscreen??!0,Se=an(o)&&fe&&te,Re=oe||fe&&te&&ue||Se;if(Re&&!Go){let bt=t.getRootNode(),Ht=bt instanceof ShadowRoot?bt.host:t.closest(".persona-host");Ht&&!Ko&&(Ko=Zg(Ht,o.launcher?.zIndex??In)),Go=eh(t.ownerDocument)}else Re||(Ko?.(),Ko=null,Go?.(),Go=null)}}};bl();let Nd=t.ownerDocument.defaultView??window;if(Nd.addEventListener("resize",bl),_e.push(()=>Nd.removeEventListener("resize",bl)),typeof ResizeObserver<"u"){Xs=new ResizeObserver(()=>{Oc()}),Ov(),_e.push(()=>{Xs?.disconnect(),Xs=null});let i=new ResizeObserver(()=>{Ad()});i.observe(Pe),_e.push(()=>i.disconnect())}Nd.addEventListener("resize",Ad),_e.push(()=>Nd.removeEventListener("resize",Ad)),io=le.scrollTop;let Dv=ir(le),_v=()=>{let i=le.scrollTop,c=ir(le),f=c<Dv;if(Dv=c,!Nr()){io=i,bn();return}let{action:y,nextLastScrollTop:x}=au({following:so.isFollowing(),currentScrollTop:i,lastScrollTop:io,nearBottom:Ir(le,fr),userScrollThreshold:xE,isAutoScrolling:Yn||Gc||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(io=x,y==="resume"){nd()||Qn();return}y==="pause"&&Qa()};if(le.addEventListener("scroll",_v,{passive:!0}),_e.push(()=>le.removeEventListener("scroll",_v)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{RE(),Of(We)});i.observe(We),i.observe(le),_e.push(()=>i.disconnect())}let Nv=()=>{Nr()&&so.isFollowing()&&nd()&&Qa()},Fv=le.ownerDocument;Fv.addEventListener("selectionchange",Nv),_e.push(()=>{Fv.removeEventListener("selectionchange",Nv)});let l0=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),$v=i=>{l0.has(i.key)&&(Ds(),Ty()&&Nr()&&so.isFollowing()&&Qa())},Vv=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ds(),Ty()&&Nr()&&so.isFollowing()&&Qa())};le.addEventListener("keydown",$v),le.addEventListener("focusin",Vv),_e.push(()=>{le.removeEventListener("keydown",$v),le.removeEventListener("focusin",Vv)});let zv=i=>{if(i.deltaY!==0&&Ds(),!Nr())return;let c=lu({following:so.isFollowing(),deltaY:i.deltaY,nearBottom:Ir(le,fr),resumeWhenNearBottom:!0});c==="pause"?Qa():c==="resume"&&!nd()&&Qn()};le.addEventListener("wheel",zv,{passive:!0}),le.addEventListener("touchmove",Ds,{passive:!0}),le.addEventListener("pointerdown",Ds,{passive:!0}),_e.push(()=>{le.removeEventListener("touchmove",Ds),le.removeEventListener("pointerdown",Ds)}),_e.push(()=>le.removeEventListener("wheel",zv)),dn.addEventListener("click",()=>{Wo(),le.scrollTop=le.scrollHeight,io=le.scrollTop,Qn(),Kr(!0),bn()}),_e.push(()=>dn.remove()),_e.push(()=>{Tb(),Wo()});let qv=()=>{N&&(Ls&&(N.removeEventListener("click",Ls),Ls=null),Ie()?(N.style.display="",Ls=()=>{Rt(!1,"user")},N.addEventListener("click",Ls)):N.style.display="none")};qv(),(()=>{let{clearChatButton:i}=Qe;i&&i.addEventListener("click",()=>{if(Qo()){ff({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}$.clearMessages(),pn.clear(),Qn(),ia(Qe.composerOverlay);try{localStorage.removeItem(Ra),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ra}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ra)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),W?.clear&&Jc(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),H={},pe.syncFromMetadata(),Ct?.clearAttachments(),ed(),Si(void 0),qo(void 0),Rs(),rt?.clear(),Zt?.reset(),ae?.update()})})();let Uv=[["keydown",Zk],["input",Xk],["input",zo],["input",As],["keyup",As],["paste",e0],["focus",dE]],jv=i=>{if(i)for(let[c,f]of Uv)At?.addListener(i,c,f)},c0=i=>{if(i)for(let[c,f]of Uv)At?.removeListener(i,c,f)},Kv=()=>{At&&(At.addListener(At.form,"submit",Kk),At.addListener(At.footer,"click",As),jv(Ae),ye&&At.addListener(ye,"click",kf))};Kv();let Gv=()=>{sn?.onComposerSwap((i,c)=>{c0(c),Ae=i,At&&(At.input=i),jv(i),cm(),Pm(),zo()})};Gv();let Lf=!1;function Yv(){if(!Lf){Lf=!0;try{let i=Ae?.value??"",c=Be.ownerDocument??document,f=Ae?c.activeElement===Ae:!1;Mf(),At?.destroy(),At=null,sn?.destroy(),sn=null;let y=null,x=()=>(y=ke()?hu({config:o}):dc({config:o}),y.footer),P=Oy(x)??x();rn.replaceComposer(P),Be=rn.composer.footer;let Y=y!==null&&P===y.footer;Mi=!Y,My=Y?y.setSendButtonMode:()=>{},By(Be),_y(Be),Ny(),Fy(),$y(),Gv(),Vy(),dm(),zy(),Kv();let ne=ks.indexOf(mr);mr.destroy(),mr=ac(Lo),ne>=0&&(ks[ne]=mr),Ae&&(Ae.value=i),zo(),As(),ld(),Li(),nl($.isStreaming()),pt.active&&Qs("recording"),Ms(),Ov(),Ss(),Po(),id(),f&&Ae?.focus()}finally{Lf=!1}}}let vl=t.ownerDocument??document;vl.addEventListener("keydown",Iv,!0);let Qv=()=>{xm()},Xv=()=>{vl.visibilityState==="hidden"&&xm()};typeof window<"u"&&(window.addEventListener("pagehide",Qv),vl.addEventListener("visibilitychange",Xv),_e.push(()=>{window.removeEventListener("pagehide",Qv),vl.removeEventListener("visibilitychange",Xv)}));let Jv="persona-attachment-drop-active",Cl=0,Pf=()=>{Cl=0,Pe.classList.remove(Jv)},Xi=()=>o.attachments?.enabled===!0&&Ct!==null&&!Yr(),Zv=i=>{!Qu(i.dataTransfer)||!Xi()||(Cl++,Cl===1&&Pe.classList.add(Jv))},eC=i=>{!Qu(i.dataTransfer)||!Xi()||(Cl--,Cl<=0&&Pf())},tC=i=>{!Qu(i.dataTransfer)||!Xi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},nC=i=>{if(!Qu(i.dataTransfer)||!Xi())return;i.preventDefault(),i.stopPropagation(),Pf();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&Ct.handleFiles(c)},es=!0;Pe.addEventListener("dragenter",Zv,es),Pe.addEventListener("dragleave",eC,es),t.addEventListener("dragover",tC,es),t.addEventListener("drop",nC,es);let Fd=t.ownerDocument,oC=i=>{Xi()&&i.preventDefault()},rC=i=>{Xi()&&i.preventDefault()};Fd.addEventListener("dragover",oC),Fd.addEventListener("drop",rC),_e.push(()=>{At?.destroy(),At=null,Mf(),Uo?.destroy(),Uo=null,pr?.destroy(),pr=null,$r?.destroy(),$r=null,Vr?.destroy(),Vr=null,Fr=null,sm=null,xm(),Ya.destroy(),Ki&&clearTimeout(Ki),Rs(),Ys?.abort(),Ys=null,Ct?.destroy(),Ct=null,Ve.destroy(),vl.removeEventListener("keydown",Iv,!0),sn?.destroy()}),_e.push(()=>{Pe.removeEventListener("dragenter",Zv,es),Pe.removeEventListener("dragleave",eC,es),t.removeEventListener("dragover",tC,es),t.removeEventListener("drop",nC,es),Fd.removeEventListener("dragover",oC),Fd.removeEventListener("drop",rC),Pf()}),_e.push(()=>{$.cancel()}),en?_e.push(()=>{en?.destroy()}):Nn&&_e.push(()=>{Nn?.remove()});let tn={update(i){let c=o.toolCall,f=o.messageActions,y=o.layout?.messages,x=o.colorScheme,P=o.loadingIndicator,Y=o.iterationDisplay,ne=o.features?.showReasoning,te=o.features?.showToolCalls,oe=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,Se=o.features?.streamAnimation?.type,Re=o.features?.history?.enabled===!0,bt=o.features?.history?.provider,Ht=o.getIdentityProof,Wt=o.clientToken,Sn=o.contextMentions;o=iT({...o,features:s},i),s=o.features,o=Qh(o),r(),hm(),Gl(t,o),Sc(t,o),Ac(t,o),Me(),Ho(),o.colorScheme!==x&&ib();let mn=Zh.getForInstance(o.plugins);a.length=0,a.push(...mn),sv(),ue=o.launcher?.enabled??!0,xe=o.launcher?.autoExpand??!1,lt=o.features?.showReasoning??!0,Vt=o.features?.showToolCalls??!0,Gt=o.features?.scrollToBottom??{};let nn=oo();Ot=o.features?.scrollBehavior??{},nn!==oo()&&(Wo(),Qn()),Cb(),Ly(),bn();let Wn=It;if(It=o.features?.showEventStreamToggle??!1,It&&!Wn){if(rt||(me(),$.setSSEEventCallback((ge,ut)=>{o.onSSEEvent?.(ge,ut),ee(ge,ut)})),!St&&ve){let ge=o.features?.eventStream?.classNames,ut="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"+(ge?.toggleButton?" "+ge.toggleButton:"");St=v("button",ut),St.style.width="28px",St.style.height="28px",St.style.color=zn.actionIconColor,St.type="button",St.setAttribute("aria-label","Event Stream"),St.title="Event Stream";let ht=Ke(Or.Activity,"18px","currentColor",1.5);ht&&St.appendChild(ht);let Mt=Qe.clearChatButtonWrapper,Kt=Qe.closeButtonWrapper,Pn=Mt||Kt;Pn&&Pn.parentNode===ve?ve.insertBefore(St,Pn):ve.appendChild(St),St.addEventListener("click",()=>{A?Ai():lm()})}}else!It&&Wn&&(Ai(),St&&(St.remove(),St=null),rt?.clear(),Lt?.destroy(),rt=null,Lt=null,Zt?.reset(),Zt=null,ln=null);if(o.launcher?.enabled===!1&&en&&(en.destroy(),en=null),o.launcher?.enabled===!1&&Nn&&(Nn.remove(),Nn=null),o.launcher?.enabled!==!1&&!en&&!Nn){let{instance:ge,element:ut}=bh({config:o,plugins:a,onToggle:Bv});en=ge,ge||(Nn=ut),t.appendChild(ut)}en&&en.update(o),gl(),Xe&&o.launcher?.subtitle!==void 0&&(Xe.textContent=o.launcher.subtitle);let wt=o.layout?.header;if(wt?.layout!==Ee&&ve){let ge=wt?fu(o,wt,{showClose:Ie(),onClose:()=>Rt(!1,"user")}):ii({config:o,showClose:Ie(),onClose:()=>Rt(!1,"user")});rn.replaceHeader(ge),ve=rn.header.element,de=rn.header.iconHolder,De=rn.header.headerTitle,Xe=rn.header.headerSubtitle,N=rn.header.closeButton,Ee=wt?.layout,gl()}else if(wt){if(de&&(de.style.display=wt.showIcon===!1?"none":""),De&&(De.style.display=wt.showTitle===!1?"none":""),Xe&&(Xe.style.display=wt.showSubtitle===!1?"none":""),N){let ge=Ie()&&wt.showCloseButton!==!1;N.style.display=ge?"":"none"}if(Qe.clearChatButtonWrapper){let ge=wt.showClearChat;if(ge!==void 0){Qe.clearChatButtonWrapper.style.display=ge?"":"none";let{closeButtonWrapper:ut}=Qe;ut&&!ut.classList.contains("persona-absolute")&&(ge?ut.classList.remove("persona-ml-auto"):ut.classList.add("persona-ml-auto"))}}}let Tr=o.layout?.showHeader!==!1;ve&&(ve.style.display=Tr?"":"none");let Jo=o.layout?.showFooter!==!1;Be&&(Be.style.display=Jo?"":"none"),Ss(),bn(),ue!==Ce?ue?Rt(xe,"auto"):(Te=!0,tl()):xe!==F&&Rt(xe,"auto"),F=xe,Ce=ue,bl(),qv();let tt=JSON.stringify(o.toolCall)!==JSON.stringify(c),ot=JSON.stringify(o.messageActions)!==JSON.stringify(f),Oe=JSON.stringify(o.layout?.messages)!==JSON.stringify(y),_t=o.loadingIndicator?.render!==P?.render||o.loadingIndicator?.renderIdle!==P?.renderIdle||o.loadingIndicator?.showBubble!==P?.showBubble,vn=o.iterationDisplay!==Y,On=(o.features?.showReasoning??!0)!==(ne??!0)||(o.features?.showToolCalls??!0)!==(te??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(tt||ot||Oe||_t||vn||On)&&$&&(Ws++,ho(We,$.getMessages(),je));let on=o.features?.streamAnimation?.type;if(on!==Se&&on&&on!=="none"){let ge=bm(on,o.features?.streamAnimation?.plugins);ge&&tc(ge,t)}let ze=o.launcher??{},Cn=ze.headerIconHidden??!1,wn=o.layout?.header?.showIcon,xo=Cn||wn===!1,Ze=ze.headerIconName,jt=ze.headerIconSize??"48px";if(de){let ge=ve,ut=ge?.querySelector(".persona-flex-col");if(xo)de.style.display="none",ge&&ut&&!ge.contains(ut)&&ge.insertBefore(ut,ge.firstChild);else{if(de.style.display="",de.style.height=jt,de.style.width=jt,ge&&ut&&(ge.contains(de)?de.nextSibling!==ut&&(de.remove(),ge.insertBefore(de,ut)):ge.insertBefore(de,ut)),Ze){let Mt=parseFloat(jt)||24,Kt=He(Ze,Mt*.6,"currentColor",1);Kt?de.replaceChildren(Kt):de.textContent=ze.agentIconText??"\u{1F4AC}"}else if(ze.iconUrl){let Mt=de.querySelector("img");if(Mt)Mt.src=ze.iconUrl,Mt.style.height=jt,Mt.style.width=jt;else{let Kt=document.createElement("img");Kt.src=ze.iconUrl,Kt.alt="",Kt.className="persona-rounded-xl persona-object-cover",Kt.style.height=jt,Kt.style.width=jt,de.replaceChildren(Kt)}}else{let Mt=de.querySelector("svg"),Kt=de.querySelector("img");(Mt||Kt)&&de.replaceChildren(),de.textContent=ze.agentIconText??"\u{1F4AC}"}let ht=de.querySelector("img");ht&&(ht.style.height=jt,ht.style.width=jt)}}let er=o.layout?.header?.showTitle,Bo=o.layout?.header?.showSubtitle;if(De&&(De.style.display=er===!1?"none":""),Xe&&(Xe.style.display=Bo===!1?"none":""),N){let ge=Ie()&&o.layout?.header?.showCloseButton!==!1;if(N.style.display=ge?"":"none",!ke()){let An=ze.closeButtonSize??"";N.style.height=An,N.style.width=An,N.style.minWidth=An,N.style.minHeight=An}let ut=ze.closeButtonPlacement??"inline",{closeButtonWrapper:ht}=Qe,Mt=ut==="top-right",Kt=ht?.classList.contains("persona-absolute");if(ht&&Mt!==Kt)if(ht.remove(),Mt){ht.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let An=al??Pe;An.style.position="relative",An.appendChild(ht)}else{let An=ze.clearChat?.placement??"inline",Mn=ze.clearChat?.enabled??!0;ht.className=Mn&&An==="inline"?"":"persona-ml-auto",ve&&ve.appendChild(ht)}if(N.style.color=ze.closeButtonColor||zn.actionIconColor,ze.closeButtonBackgroundColor?(N.style.backgroundColor=ze.closeButtonBackgroundColor,N.classList.remove("hover:persona-bg-gray-100")):(N.style.backgroundColor="",N.classList.add("hover:persona-bg-gray-100")),ze.closeButtonBorderWidth||ze.closeButtonBorderColor){let An=ze.closeButtonBorderWidth||"0px",Mn=ze.closeButtonBorderColor||"transparent";N.style.border=`${An} solid ${Mn}`,N.classList.remove("persona-border-none")}else N.style.border="",N.classList.add("persona-border-none");ze.closeButtonBorderRadius?(N.style.borderRadius=ze.closeButtonBorderRadius,N.classList.remove("persona-rounded-full")):(N.style.borderRadius="",N.classList.add("persona-rounded-full")),ze.closeButtonPaddingX?(N.style.paddingLeft=ze.closeButtonPaddingX,N.style.paddingRight=ze.closeButtonPaddingX):(N.style.paddingLeft="",N.style.paddingRight=""),ze.closeButtonPaddingY?(N.style.paddingTop=ze.closeButtonPaddingY,N.style.paddingBottom=ze.closeButtonPaddingY):(N.style.paddingTop="",N.style.paddingBottom=""),uu(N,ze.closeButtonIconName??"x",{iconSize:ke()?fh:void 0,iconText:ze.closeButtonIconText??"\xD7"});let Pn=ze.closeButtonTooltipText??"Close chat",Oo=ze.closeButtonShowTooltip??!0;N.setAttribute("aria-label",Pn),ht&&Tn({anchor:N,trigger:ht,text:()=>N?.getAttribute("aria-label")??Pn,enabled:Oo})}let{clearChatButton:nt,clearChatButtonWrapper:Ne}=Qe;if(nt){let ge=ze.clearChat??{},ut=ge.enabled??!0,ht=o.layout?.header?.showClearChat,Mt=ht!==void 0?ht:ut,Kt=ge.placement??"inline";if(Ne){Ne.style.display=Mt?"":"none";let{closeButtonWrapper:Pn}=Qe;!ke()&&Pn&&!Pn.classList.contains("persona-absolute")&&(Mt?Pn.classList.remove("persona-ml-auto"):Pn.classList.add("persona-ml-auto"));let Oo=Kt==="top-right",An=Ne.classList.contains("persona-absolute");if(!ke()&&Oo!==An&&Mt){if(Ne.remove(),Oo){Ne.className="persona-absolute persona-top-4 persona-z-50",Ne.style.right="48px";let tr=al??Pe;tr.style.position="relative",tr.appendChild(Ne)}else{Ne.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ne.style.right="";let tr=Qe.closeButtonWrapper;ve&&tr&&tr.parentElement===ve?ve.insertBefore(Ne,tr):ve&&ve.appendChild(Ne)}let Mn=Qe.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(Oo?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(Mt){if(!ke()){let Mn=ge.size??"";nt.style.height=Mn,nt.style.width=Mn,nt.style.minWidth=Mn,nt.style.minHeight=Mn}let Pn=ge.iconColor??"";if(nt.style.color=Pn||zn.actionIconColor,uu(nt,ge.iconName??"refresh-cw",{iconSize:ke()?gh:void 0}),ge.backgroundColor?(nt.style.backgroundColor=ge.backgroundColor,nt.classList.remove("hover:persona-bg-gray-100")):(nt.style.backgroundColor="",nt.classList.add("hover:persona-bg-gray-100")),ge.borderWidth||ge.borderColor){let Mn=ge.borderWidth||"0px",tr=ge.borderColor||"transparent";nt.style.border=`${Mn} solid ${tr}`,nt.classList.remove("persona-border-none")}else nt.style.border="",nt.classList.add("persona-border-none");ge.borderRadius?(nt.style.borderRadius=ge.borderRadius,nt.classList.remove("persona-rounded-full")):(nt.style.borderRadius="",nt.classList.add("persona-rounded-full")),ge.paddingX?(nt.style.paddingLeft=ge.paddingX,nt.style.paddingRight=ge.paddingX):(nt.style.paddingLeft="",nt.style.paddingRight=""),ge.paddingY?(nt.style.paddingTop=ge.paddingY,nt.style.paddingBottom=ge.paddingY):(nt.style.paddingTop="",nt.style.paddingBottom="");let Oo=ge.tooltipText??"Clear chat",An=ge.showTooltip??!0;nt.setAttribute("aria-label",Oo),Ne&&Tn({anchor:nt,trigger:Ne,text:()=>nt?.getAttribute("aria-label")??Oo,enabled:An})}}let it=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ty],Nt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Mc.message,Mc.messageAndClick];pe=ny({parsers:it,handlers:Nt,getSessionMetadata:Q,updateSessionMetadata:Z,emit:L.emit,documentRef:typeof document<"u"?document:null}),je=FT(o,pe,Et),XE(),$.updateConfig(o),(o.features?.history?.enabled===!0!==Re||o.features?.history?.provider!==bt||o.getIdentityProof!==Ht||o.clientToken!==Wt)&&(Jn({restoreFocus:!1}),Xb()),Jr(),Ad(),ho(We,$.getMessages(),je),Li(),ld(),YE(),nl($.isStreaming()),Sn!==o.contextMentions&&Yv();let ts=o.voiceRecognition?.enabled===!0,xn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),co=o.voiceRecognition?.provider?.type==="runtype";if(ts&&(xn||co))if(!ye||!no){let ge=fa(o);if(ge){ye=ge.button,no=ge.wrapper;let ut=Vo&&Vo.parentElement===_r?Vo:null;_r?_r.insertBefore(no,ut):Rn?.appendChild(no),At&&(At.micButton=ye),At?.addListener(ye,"click",kf),ye.disabled=$.isStreaming()}}else{let ge=o.voiceRecognition??{},ut=o.sendButton??{},ht=ge.iconName??"mic",Mt=ge.iconSize,Kt=parseFloat(Mt??"")||$n;ye.classList.add(po),ye.classList.toggle(_o,!Mt),ye.style.width=Mt??"",ye.style.height=Mt??"",ye.style.minWidth=Mt??"",ye.style.minHeight=Mt??"";let Pn=ge.iconColor??ut.textColor;ye.innerHTML="";let Oo=He(ht,Kt,Pn||"currentColor",1.5);Oo?ye.appendChild(Oo):ye.textContent="\u{1F3A4}";let An=ge.backgroundColor??ut.backgroundColor;An?ye.style.backgroundColor=An:ye.style.backgroundColor="",Pn?ye.style.color=Pn:ye.style.color="var(--persona-text, #111827)",ge.borderWidth?(ye.style.borderWidth=ge.borderWidth,ye.style.borderStyle="solid"):(ye.style.borderWidth="",ye.style.borderStyle=""),ge.borderColor?ye.style.borderColor=ge.borderColor:ye.style.borderColor="",ge.paddingX?(ye.style.paddingLeft=ge.paddingX,ye.style.paddingRight=ge.paddingX):(ye.style.paddingLeft="",ye.style.paddingRight=""),ge.paddingY?(ye.style.paddingTop=ge.paddingY,ye.style.paddingBottom=ge.paddingY):(ye.style.paddingTop="",ye.style.paddingBottom="");let Mn=ge.tooltipText??"Start voice recognition",tr=ge.showTooltip??!1;ye.setAttribute("aria-label",Mn),no&&Tn({anchor:ye,trigger:no,text:()=>ye?.getAttribute("aria-label")??Mn,enabled:tr}),no.style.display="",ye.disabled=$.isStreaming()}else ye&&no&&(no.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():Xo&&Zr());if(o.attachments?.enabled===!0){if(!Kn||!Qt){let ge=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??Rn).insertBefore(Gn,Ae)),$t||($t=document.createElement("input"),$t.type="file",$t.accept=(ge.allowedTypes??Lr).join(","),$t.multiple=(ge.maxFiles??4)>1,$t.style.display="none",$t.setAttribute("aria-label","Attach files"),(Ae.parentElement??Rn).insertBefore($t,Ae)),Kn=v("div","persona-send-button-wrapper"),Qt=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${po} ${_o}`),Qt.type="button",Qt.setAttribute("aria-label",ge.buttonTooltipText??"Attach file");let ut=ge.buttonIconName??"paperclip";Qt.style.fontSize="18px",Qt.style.lineHeight="1";let ht=He(ut,$n,"currentColor",1.5);ht?Qt.appendChild(ht):Qt.textContent="\u{1F4CE}",Qt.addEventListener("click",Kt=>{Kt.preventDefault(),$t?.click()}),Kn.appendChild(Qt);let Mt=ge.buttonTooltipText??"Attach file";Tn({anchor:Qt,trigger:Kn,text:()=>Qt?.getAttribute("aria-label")??Mt}),$o?$o.append(Kn):Rn.appendChild(Kn),At&&(At.attachmentButton=Qt,At.attachmentInput=$t??void 0,At.attachmentPreviews=Gn??void 0),!Ct&&$t&&Gn&&(Ct=Dl.fromConfig(ge,Py),Ct.setPreviewsContainer(Gn),At?.addListener($t,"change",async()=>{Ct&&$t?.files&&(await Ct.handleFileSelect($t.files),$t.value="")}))}else{Kn.style.display="";let ge=o.attachments??{};$t&&($t.accept=(ge.allowedTypes??Lr).join(","),$t.multiple=(ge.maxFiles??4)>1),Ct&&Ct.updateConfig({allowedTypes:ge.allowedTypes,maxFileSize:ge.maxFileSize,maxFiles:ge.maxFiles,adapter:ge.adapter})}if(Pe.querySelector(".persona-attachment-drop-overlay")?.remove(),Pe.appendChild($T(o.attachments?.dropOverlay)),Qt){let ge=o.attachments??{},ut=ge.buttonTooltipText??"Attach file";Qt.setAttribute("aria-label",ut),Qt.textContent="";let ht=He(ge.buttonIconName??"paperclip",$n,"currentColor",1.5);ht?Qt.appendChild(ht):Qt.textContent="\u{1F4CE}",Kn&&Tn({anchor:Qt,trigger:Kn,text:()=>Qt?.getAttribute("aria-label")??ut})}}else Kn&&(Kn.style.display="none"),Ct&&Ct.clearAttachments(),Pe.querySelector(".persona-attachment-drop-overlay")?.remove();let Xt=o.sendButton??{},If=Xt.useIcon??!1,Zs=Xt.iconText??"\u2191",$d=Xt.iconName,iC=Xt.tooltipText??"Send message",u0=Xt.showTooltip??!1,wl=Xt.size,m0=parseFloat(wl??"")||bg,Vd=Xt.backgroundColor,xl=Xt.textColor;if(If){if($e.style.width=wl??"",$e.style.height=wl??"",$e.style.minWidth=wl??"",$e.style.minHeight=wl??"",$e.style.fontSize="18px",$e.style.lineHeight="1",xl?$e.style.color=xl:$e.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!$.isStreaming())if($e.innerHTML="",$d){let ge=parseFloat(Xt.iconSize??"")||Math.round(m0*.5),ut=xl?.trim()||"currentColor",ht=Xt.iconStrokeWidth??2,Mt=He($d,ge,ut,ht),Kt=He(Xt.stopIconName??"square",ge,ut,ht);Mt&&Kt?$e.appendChild(vg(Mt,Kt)):Mt?$e.appendChild(Mt):$e.textContent=Zs}else $e.textContent=Zs;$e.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${po}`,Vd?($e.style.backgroundColor=Vd,$e.classList.remove("persona-bg-persona-primary")):($e.style.backgroundColor="",$e.classList.add("persona-bg-persona-primary"))}else $e.textContent=o.copy?.sendButtonLabel??"Send",$e.style.width="",$e.style.height="",$e.style.minWidth="",$e.style.minHeight="",$e.style.fontSize="",$e.style.lineHeight="",$e.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",Vd?($e.style.backgroundColor=Vd,$e.classList.remove("persona-bg-persona-accent")):$e.classList.add("persona-bg-persona-accent"),xl?$e.style.color=xl:$e.classList.add("persona-text-white");Xt.borderWidth?($e.style.borderWidth=Xt.borderWidth,$e.style.borderStyle="solid"):($e.style.borderWidth="",$e.style.borderStyle=""),Xt.borderColor?$e.style.borderColor=Xt.borderColor:$e.style.borderColor="",Xt.paddingX?($e.style.paddingLeft=Xt.paddingX,$e.style.paddingRight=Xt.paddingX):($e.style.paddingLeft="",$e.style.paddingRight=""),Xt.paddingY?($e.style.paddingTop=Xt.paddingY,$e.style.paddingBottom=Xt.paddingY):($e.style.paddingTop="",$e.style.paddingBottom=""),$.isStreaming()||$e.setAttribute("aria-label",iC),id(),Vo&&Tn({anchor:$e,trigger:Vo,text:()=>$e.getAttribute("aria-label")??iC,enabled:u0}),Uy();let aC=Dp(Ve.getState().activeModeIds,o.composer?.modes);Ve.setActiveModeIds(aC),wi().length>0!==!!pr&&dm(),pr?.render(aC,wi());for(let ge of[...xi.keys()])Op(ge,o.composer?.modeGroups)||xi.delete(ge);xi.forEach(ge=>ge.repaint()),Fr?.repaint(),Uo?.resolve();let zd=gs(o,ke());if(ym(),zd){We.style.maxWidth=zd,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",Ln.style.maxWidth=zd,Ln.style.marginLeft="auto",Ln.style.marginRight="auto",Ln.style.width="100%";for(let ge of[Rn,Lo,Gn,gt])ge&&(ge.style.maxWidth=zd,ge.style.marginLeft="auto",ge.style.marginRight="auto",ge.style.width="100%")}else{We.style.maxWidth="",We.style.marginLeft="",We.style.marginRight="",We.style.width="",Ln.style.maxWidth="",Ln.style.marginLeft="",Ln.style.marginRight="",Ln.style.width="";for(let ge of[Rn,Lo,Gn,gt])ge&&(ge.style.maxWidth="",ge.style.marginLeft="",ge.style.marginRight="",ge.style.width="")}let ns=o.statusIndicator??{},f0=ns.visible??!0;if(gt.style.display=f0?"":"none",$){let ge=$.getStatus();Hn(gt,(ht=>ht==="idle"?ns.idleText??fn.idle:ht==="connecting"?ns.connectingText??fn.connecting:ht==="connected"?ns.connectedText??fn.connected:ht==="error"?ns.errorText??fn.error:fn[ht])(ge),ns,ge)}gt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let g0=ns.align==="left"?"persona-text-left":ns.align==="center"?"persona-text-center":"persona-text-right";gt.classList.add(g0),cm(),Pm(),Po(),Le()},open(){Ie()&&Rt(!0,"api")},close(){Ie()&&Rt(!1,"api")},toggle(){Ie()&&Rt(!Te,"api")},reconnect(){$.reconnectNow()},clearChat(){ur=!1,$.clearMessages(),pn.clear(),Qn();try{localStorage.removeItem(Ra),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ra}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ra)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),W?.clear&&Jc(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),H={},pe.syncFromMetadata(),Ct?.clearAttachments(),ed(),Si(void 0),qo(void 0),Rs(),rt?.clear(),Zt?.reset(),ae?.update()},setMessage(i){return!Ae||$.isStreaming()||Yr()?!1:(!Te&&Ie()&&Rt(!0,"system"),Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if($.isStreaming()||Fs())return!1;let c=i?.trim()||Ae.value.trim();return c?(!Te&&Ie()&&Rt(!0,"system"),Ae.value="",Ae.style.height="auto",zo(),Bd(c,{consumeDraft:!1}),!0):!1},getComposerState(){return Ve.getState()},setQuote(i){let c=i?.text?.trim();c&&qo({...i,text:c})},clearQuote(){qo(void 0)},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!Te&&Ie()&&Rt(!0,"system"),pt.manuallyDeactivated=!1,Ro(),$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),hr("user"),$.isVoiceActive()&&Qi()})),!0):Xo?!0:Wv()?(!Te&&Ie()&&Rt(!0,"system"),pt.manuallyDeactivated=!1,Ro(),Dd("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Ro(),hr("user"),Mr()}),!0):!1:Xo?(pt.manuallyDeactivated=!0,Ro(),Zr("user"),!0):!1},injectMessage(i){return!Te&&Ie()&&Rt(!0,"system"),$.injectMessage(i)},injectAssistantMessage(i){!Te&&Ie()&&Rt(!0,"system");let c=$.injectAssistantMessage(i);return vt&&(vt=!1,Ye&&(clearTimeout(Ye),Ye=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),c},injectUserMessage(i){return!Te&&Ie()&&Rt(!0,"system"),$.injectUserMessage(i)},injectSystemMessage(i){return!Te&&Ie()&&Rt(!0,"system"),$.injectSystemMessage(i)},injectMessageBatch(i){return!Te&&Ie()&&Rt(!0,"system"),$.injectMessageBatch(i)},injectComponentDirective(i){return!Te&&Ie()&&Rt(!0,"system"),$.injectComponentDirective(i)},injectTestMessage(i){!Te&&Ie()&&Rt(!0,"system"),$.injectTestEvent(i)},async connectStream(i,c){return $.connectStream(i,c)},__pushEventStreamEvent(i){It&&(me(),ee(i.type,i.payload))},showEventStream(){It&&lm()},hideEventStream(){A&&Ai()},isEventStreamVisible(){return A},listConversations(i){return $.listConversations(i)},getActiveConversationId(){return $.getActiveConversationId()},openConversation(i,c){return mf(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return ff({focusComposer:i?.focus===!0})},deleteConversation(i){return Sv(i)},renameConversation(i,c){return gf(i,{title:c})},setConversationStarred(i,c){return gf(i,{starred:c})},clearConversationHistory(i){return Av(i)},resetHistoryIdentity(){return Mv()},getHistoryIdentityStatus(){return ao?ao.getIdentityStatus():Ym()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return fl({...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 J},showArtifacts(){Un(o)&&(ur=!1,Ti=!0,Ho(),dt?.setMobileOpen(!0))},hideArtifacts(){Un(o)&&(ur=!0,Ho())},upsertArtifact(i){return Un(o)?(os(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(ur=!1,Ti=!0),$.upsertArtifact(i)):null},selectArtifact(i){Un(o)&&$.selectArtifact(i)},clearArtifacts(){Un(o)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return ue&&!Te&&!ke()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(i,c,f){let x=$.getMessages().find(P=>P.variant==="approval"&&P.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){CE(i)},clearFollowUpSuggestions(){vb()},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...H}},updatePersistentMetadata(i){Z(i)},on(i,c){return L.on(i,c)},off(i,c){L.off(i,c)},isOpen(){return Ie()&&Te},isVoiceActive(){return pt.active},toggleReadAloud(i){$.toggleReadAloud(i)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(i){return $.getReadAloudState(i)},onReadAloudChange(i){return $.onReadAloudChange(i)},getState(){return{open:Ie()&&Te,launcherEnabled:ue,voiceActive:pt.active,streaming:$.isStreaming()}},showCSATFeedback(i){!Te&&Ie()&&Rt(!0,"system");let c=We.querySelector(".persona-feedback-container");c&&c.remove();let f=DT({onSubmit:async(y,x)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});We.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Te&&Ie()&&Rt(!0,"system");let c=We.querySelector(".persona-feedback-container");c&&c.remove();let f=_T({onSubmit:async(y,x)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});We.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(){Vm(),zs!=null&&(clearInterval(zs),zs=null),_e.forEach(i=>i()),st.remove(),Yt?.remove(),en?.destroy(),Nn?.remove(),Ls&&N.removeEventListener("click",Ls)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:f=>f?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=c,_e.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=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",c),_e.push(()=>{window.removeEventListener("persona:focusInput",c)}),It){let oe=Se=>{let Re=Se.detail;(!Re?.instanceId||Re.instanceId===i)&&tn.showEventStream()},fe=Se=>{let Re=Se.detail;(!Re?.instanceId||Re.instanceId===i)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",oe),window.addEventListener("persona:hideEventStream",fe),_e.push(()=>{window.removeEventListener("persona:showEventStream",oe),window.removeEventListener("persona:hideEventStream",fe)})}let f=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&tn.showHistory()},y=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&tn.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",y),_e.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",y)});let x=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&tn.showArtifacts()},P=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&tn.hideArtifacts()},Y=oe=>{let fe=oe.detail;fe?.instanceId&&fe.instanceId!==i||fe?.artifact&&tn.upsertArtifact(fe.artifact)},ne=oe=>{let fe=oe.detail;fe?.instanceId&&fe.instanceId!==i||typeof fe?.id=="string"&&tn.selectArtifact(fe.id)},te=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",P),window.addEventListener("persona:upsertArtifact",Y),window.addEventListener("persona:selectArtifact",ne),window.addEventListener("persona:clearArtifacts",te),_e.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",P),window.removeEventListener("persona:upsertArtifact",Y),window.removeEventListener("persona:selectArtifact",ne),window.removeEventListener("persona:clearArtifacts",te)})}let wo=LB(o.persistState);if(wo&&Ie()){let i=PB(wo.storage),c=`${wo.keyPrefix}widget-open`,f=`${wo.keyPrefix}widget-voice`,y=`${wo.keyPrefix}widget-voice-mode`;if(i){let x=wo.persist?.openState&&i.getItem(c)==="true",P=wo.persist?.voiceState&&i.getItem(f)==="true",Y=wo.persist?.voiceState&&i.getItem(y)==="true";if(x&&(en?.setPanelOpen(!0,"auto"),setTimeout(()=>{tn.open(),setTimeout(()=>{if(P||Y)tn.startVoiceRecognition();else if(wo.persist?.focusInput){let ne=t.querySelector("textarea");ne&&ne.focus()}},100)},0)),wo.persist?.openState&&(L.on("widget:opened",()=>{i.setItem(c,"true")}),L.on("widget:closed",()=>{i.setItem(c,"false")})),wo.persist?.voiceState&&(L.on("voice:state",ne=>{i.setItem(f,ne.active?"true":"false")}),L.on("user:message",ne=>{i.setItem(y,ne.viaVoice?"true":"false")})),wo.clearOnChatClear){let ne=()=>{i.removeItem(c),i.removeItem(f),i.removeItem(y)},te=()=>ne();window.addEventListener("persona:clear-chat",te),_e.push(()=>{window.removeEventListener("persona:clear-chat",te)})}}}if(X&&Ie()&&(en?.setPanelOpen(!0,"auto"),setTimeout(()=>{tn.open()},0)),Oi(),!wE){let i=Ji(()=>{$&&(Ws++,pn.clear(),ho(We,$.getMessages(),je))});_e.push(i)}C=()=>{$&&(Ws++,pn.clear(),ho(We,$.getMessages(),je))},$.getMessages().length>0&&sd(),M=()=>{$&&(Ws++,pn.clear(),ho(We,$.getMessages(),je))};let d0=Kw(()=>{$&&(Ws++,pn.clear(),ho(We,$.getMessages(),je))});_e.push(d0);let p0=jh(()=>{$&&(Ws++,pn.clear(),ho(We,$.getMessages(),je),Rr()?.updateInlineArtifactBlocks(We,go.artifacts,{suppressTransition:!0}),Ho())});return _e.push(p0),tn};us();var zT=(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},RB=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},WB=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},BB=(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.")},qT=(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"},xy=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=""},UT=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",xy(t)},vy=t=>{t.style.transition=""},Cy=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=""},wy=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Xu=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},OB=(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))},DB=(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)},_B=t=>{let e=ba(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Vn(e,r)??r;return{inset:o(n?.inset,Jp),canvasBackground:o(n?.canvasBackground,Zp)}},jT=(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},NB=(t,e,n,o,r,s,a,l)=>{let d=Eo(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",h=l?.canvasBackground??"";OB(t,e,n,o,p),DB(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"),Cy(e),vy(o),UT(o),wy(n),Xu(r,o),jT(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??In),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"),UT(o),RB(o,d.maxHeight),jT(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",Cy(e),vy(o),wy(n),Xu(r,o);let E=d.animate?"transform 180ms ease":"none",O=d.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":O;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=E,o.style.transform=M,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",vy(o),xy(o),Xu(r,o);let E=zT(d.width,t.clientWidth),O=Math.max(0,t.clientWidth),M=d.animate?"margin-left 180ms ease":"none",D=d.side==="right"?a?-E:0:a?0:-E;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=`${O+E}px`,e.style.transition=M,e.style.marginLeft=`${D}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${O}px`,n.style.maxWidth=`${O}px`,n.style.minWidth=`${O}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="",Cy(e),xy(o),wy(n),Xu(r,o);let E=d.reveal==="emerge";E?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let O=a?d.width:"0px",M=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",D=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${O}`,o.style.width=O,o.style.maxWidth=O,o.style.minWidth=O,o.style.minHeight="0",WB(o,d.maxHeight),o.style.overflow=E||D?"hidden":"visible",o.style.transition=M,E){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let L=u?`calc(${zT(d.width,t.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=L,r.style.minWidth=L,r.style.maxWidth=L,r.style.boxSizing="border-box"}}},FB=(t,e)=>{let n=t.ownerDocument.createElement("div");return qT(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){qT(n,o)},destroy(){n.remove()}}},$B=(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?_B(e):null};C();let S=()=>{NB(a,l,d,p,u,e,m,b)},I=null,E=()=>{I?.(),I=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(I=eu(()=>{C(),S()}))},O=()=>{g(),Eo(e).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{S()}),h.observe(a)))},M=!1,D=()=>{S(),O(),m&&!M&&a.dataset.personaDockMobileFullscreen!=="true"&&(M=!0,BB(a,Eo(e)))},L=a.ownerDocument.defaultView,B=()=>{D()};return L?.addEventListener("resize",B),Eo(e).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),D(),E(),{mode:"docked",host:u,shell:a,syncWidgetState(W){let z=W.launcherEnabled?W.open:!0;m!==z&&(m=z,D())},updateConfig(W){e=W,(e?.launcher?.enabled??!0)===!1&&(m=!0),C(),D(),E()},destroy(){L?.removeEventListener("resize",B),I?.(),I=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},KT=(t,e)=>an(e)?$B(t,e):FB(t,e);var Ic={desktop:{w:1280,h:800},mobile:{w:390,h:844}},GT=.15,YT=1.5,Sy="persona-preview-shell-theme",VB={load:()=>null,save:()=>{},clear:()=>{}},zB=["How do I get started?","Pricing & plans","Talk to support"];function Ay(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function qB(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 QT(t){let e=qB(t);return`* { box-sizing: border-box; }
|
|
1266
|
+
${Lt?"background: transparent !important;":""}
|
|
1267
|
+
`)}if(!y&&!i){let ot="max-height: -moz-available !important; max-height: stretch !important;",Ft=c?"":"padding-top: 1.25em !important;",At=c?"":`z-index: ${o.launcher?.zIndex??Rn} !important;`;rt.style.cssText+=ot+Ft+At}sm(),tt()},vm=()=>{t.style.setProperty("--persona-content-max-width",gs(o,ke()))},ib=!1,ab=()=>{let i=Ug(o,ke());ke()&&o.composer?.placement&&o.debug===!0&&!ib&&(ib=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=Rr(o);t.setAttribute("data-persona-composer-placement",i),t.setAttribute("data-persona-conversation-state",Bc),t.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",c.composerGap??ou),Dc()},lb=()=>{if(ke())return;let i=cn(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!ue)return;let y=t.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=P)return;let Y=y.innerHeight,ne=64,te=o.launcher?.heightOffset??0,oe=Math.max(200,Y-ne),fe=Math.min(640,oe);_e.style.height=`${Math.max(200,fe-te)}px`};bm(),Yl(t,o),Ac(t,o),Mc(t,o),vm(),ab(),Ms=()=>{bm(),lb(),Yl(t,o),Ac(t,o),Mc(t,o),vm(),ab(),Fc?t.style.setProperty("--persona-artifact-welded-outer-radius",Fc):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Me(),Le()};let De=[];De.push(()=>{eb=!0}),De.push(()=>{d.forEach(i=>i()),l.destroy()}),De.push(()=>{document.removeEventListener("keydown",ob)}),De.push(()=>{Va!==null&&clearTimeout(Va)});let Go=null,Yo=null;De.push(()=>{Go?.(),Go=null,Yo?.(),Yo=null}),Ua&&De.push(()=>{Ua?.disconnect(),Ua=null}),De.push(()=>{Ga?.(),Ga=null,ym(),Kt&&(Kt.remove(),Kt=null),ct?.element.style.removeProperty("width"),ct?.element.style.removeProperty("maxWidth"),ct?.destroy()}),Ht&&De.push(()=>{G=!0,dn=null,T!==null&&(cancelAnimationFrame(T),T=null),ae?.destroy(),ae=null,nt?.destroy(),nt=null,Pt=null});let Es=null,cb=()=>{Es&&(Es(),Es=null),o.colorScheme==="auto"&&(Es=nu(()=>{Yl(t,o)}))};cb(),De.push(()=>{Es&&(Es(),Es=null)}),De.push(()=>{b=!0,g?.()}),De.push(()=>{E=!0});let db=!1;De.push(()=>{db=!0});let Cm=(i,c)=>{let f=Zl(i,c);return f||!XS.includes(i)?f:(hA().then(y=>{if(db)return;ri(y.wipe),ri(y.glyphCycle);let x=Zl(i,c);x&&nc(x,t)}).catch(()=>{}),null)},Gc=o.features?.streamAnimation;if(Gc?.type&&Gc.type!=="none"){let i=Cm(Gc.type,Gc.plugins);i&&nc(i,t),De.push(()=>JS(t))}let mr=lc(Po),pb=lc(Ci),ub=lc(_r),ks=[mr,pb,ub];De.push(()=>{ks.forEach(i=>i.destroy())});let Ls=null,$,Ps=null,mb=!1,fb=0,gb=null,hb=i=>i.reduce((c,f)=>f.role==="user"?c+1:c,0),yb=i=>{for(let c=i.length-1;c>=0;c--)if(El(i[c]))return i[c].id??null;return null},bb=!1,SE=()=>{bb||o.debug!==!0||(bb=!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".'))},vb=!1,Cb=!1,wb=(i,c)=>{vb||o.debug!==!0||!c.enabled||c.expose||mb||Cb&&($.isStreaming()||i.some(El)||(vb=!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.")))},Li=i=>{if(!$)return;let c=i??$.getMessages(),f=oe=>{oe.render([],$,Ae,c)},y=oe=>{ks.forEach(fe=>{fe!==oe&&f(fe)})};Ps&&(hb(c)>fb||yb(c)!==gb)&&(Ps=null);let x=ls(o);wb(c,x);let P=x.enabled?ew(c):null,Y=Ps??P,ne=Ps?"host":"agent";if(Y){let oe=o.suggestions?.followUps,fe=oe?.placement??(oe?"auto":"composer"),Re=(fe==="auto"?ke()?"composer":"after-message":fe)==="after-message"?ub:mr;y(Re),Re.render(Y,$,Ae,c,o.suggestionChipsConfig,{source:ne,surface:"followUp",variant:oe?.variant??"chip",behavior:oe?.behavior??"send",overflow:oe?.overflow??"wrap",maxItems:oe?.maxItems??4,config:o,plugins:a,submitPrompt:Bd});return}if(c.some(oe=>oe.role==="user")){ks.forEach(f);return}let te=o.suggestions?.starters;if(te){let oe=Aa(Rr(o),c),fe=te.placement??"auto",Se=fe==="auto"?oe?"welcome":"composer":fe;if(Se==="welcome"&&!oe){SE(),ks.forEach(f);return}let Re=Se==="welcome"?pb:mr;y(Re),Re.render(te.items??o.suggestionChips,$,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:te.variant??"card",behavior:te.behavior??"send",overflow:te.overflow??"wrap",maxItems:te.maxItems??4,config:o,plugins:a,submitPrompt:Bd});return}y(mr),mr.render(o.suggestionChips,$,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Bd})},xb=()=>{Ps&&(Ps=null,Li())},AE=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){xb();return}let f=$?$.getMessages():[];Ps=c,mb=!0,fb=hb(f),gb=yb(f),Li(f)},so=!1,mn=zS(),Pi=new Map,Is=new Map,qr=new Map,Hs=null,Ur=null;function Rs(){if(!Hs)return;let i=Hs;Hs=null,Ur?.destroy(),Ur=null,mn.delete(i),Pe.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),$&&yo(We,$.getMessages(),Ue)}let Ws=0,ME=Ao()!==null,io=lu(),ao=0,jr=null,Qn=!1,Yc=!1,Kr=0,vn=null,Bs=null,wm=!1,Ii=!1,Os=null,Ya=!0,Qc=!1,Hi=null,Xc=!1,Ds=()=>{Xc=!0,LE()},xm=null,TE=4,fr=24,EE=80,kE=1e3,gr=null,Sb=()=>{t.setAttribute("data-persona-scrollbar",nm()),nm()!=="on-scroll"&&(gr!==null&&clearTimeout(gr),gr=null,le.removeAttribute("data-persona-scrollbar-visible"))},LE=()=>{nm()==="on-scroll"&&(le.setAttribute("data-persona-scrollbar-visible",""),gr!==null&&clearTimeout(gr),gr=setTimeout(()=>{gr=null,Hr(le,fr)&&le.removeAttribute("data-persona-scrollbar-visible")},kE))};Sb(),De.push(()=>{gr!==null&&clearTimeout(gr)});let Sm=new Map,dt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Ky=()=>dt.active,Io();let Ab=o.voiceRecognition?.autoResume??!1,hr=i=>{L.emit("voice:state",{active:dt.active,source:i,timestamp:Date.now()})},Wo=()=>{Z(i=>({...i,voiceState:{active:dt.active,timestamp:Date.now(),manuallyDeactivated:dt.manuallyDeactivated}}))},PE=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=wy(H.voiceState),c=!!i.active,f=Number(i.timestamp??0);dt.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-f<HB&&setTimeout(()=>{dt.active||(dt.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{dt.active=$.isVoiceActive(),hr("restore"),$.isVoiceActive()&&Qi()}):_d("restore"))},1e3)},IE=()=>$?zT($.getMessages()).filter(i=>!i.__skipPersist):[],Jc=null,Mb=(i,c)=>{typeof console<"u"&&console.error(i,c)},Zc=(i,c)=>{let f=()=>{try{let Y=i();return!Y||typeof Y.then!="function"?null:Promise.resolve(Y).catch(ne=>{Mb(c,ne)})}catch(Y){return Mb(c,Y),null}},y=Jc,x=y?y.then(()=>f()??void 0):f();if(!x)return;let P=x.finally(()=>{Jc===P&&(Jc=null)});Jc=P};function Ri(i){if(!W?.save)return;let c=i?zT(i):$?IE():[],f=z&&$?.getResumableHandle();f&&(H={...H,durableResume:{executionId:f.executionId,after:f.lastEventId}});let y={messages:c,metadata:H,artifacts:ho.artifacts,selectedArtifactId:ho.selectedId,..._s?{draft:_s}:{}};Zc(()=>W.save(y),"[AgentWidget] Failed to persist state:")}let _s,ed=()=>!W?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Qa=Nx({write:()=>{if(!ed())return;let i=Fe.getState(),c=Dx({text:i.text,mentionRefs:i.mentionRefs,contentSegments:vf(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(_s)&&(_s=c,Ri())}});function Tb(){ed()&&Qa.schedule()}function Am(){Qa.flush()}function Eb(i){if(!ed())return;let c=_x(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(f=>f.id),modelIds:(o.composer?.models??[]).map(f=>f.id),modes:o.composer?.modes??[]});c&&(_s=i,Ae&&!Ae.value&&(Ae.value=c.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),qo()),c.selectedModelId&&(Fe.setSelectedModelId(c.selectedModelId),$r?.repaint()),_c(c.activeModeIds??[]),c.quote&&Uo(c.quote),Qa.cancel())}function td(){Qa.cancel(),_s&&(_s=void 0,ed()&&Ri())}let Wi=null,kb=()=>rt.querySelector("#persona-scroll-container")||le,Bi=()=>{Wi!==null&&(cancelAnimationFrame(Wi),Wi=null),Qn=!1},Lb=()=>{jr!==null&&(cancelAnimationFrame(jr),jr=null),Yc=!1,Bi()},HE=()=>so&&Tm()&&(ro()!=="anchor-top"||Py()),Mm=()=>{let i=Na()||"Jump to latest",c=HE();un.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Kr>0?(xs.textContent=String(Kr),xs.style.display="",un.setAttribute("aria-label",`${i} (${Kr} new)`)):(xs.textContent="",xs.style.display="none",un.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Pb=()=>{Kr!==0&&(Kr=0,Mm())},RE=()=>{let i=vn?.spacerHeight??0;return i<=0?Hr(le,fr):sd(i)-le.scrollTop-le.clientHeight<=fr},Tm=()=>Fr()?!io.isFollowing():!RE(),Em=()=>!!$&&$.getMessages().length>0,Cn=()=>{if(!aE()||mt()){un.parentNode&&un.remove(),un.style.display="none";return}un.parentNode!==Pe&&Pe.appendChild(un),Ss();let c=ir(le)>0&&Tm()&&Em();c?Mm():Pb(),un.style.display=c?"":"none"},Xa=()=>{io.pause()&&(Lb(),Cn())},Xn=()=>{io.resume(),Pb(),Cn()},Gr=(i=!1)=>{Fr()&&Em()&&io.isFollowing()&&(!i&&!so||(jr!==null&&(cancelAnimationFrame(jr),jr=null),Yc=!0,jr=requestAnimationFrame(()=>{jr=null,Yc=!1,io.isFollowing()&&WE(kb(),i?220:140)})))},Ib=(i,c,f,y=()=>!0)=>{let x=i.scrollTop,P=c(),Y=P-x;if(Bi(),Math.abs(Y)<1){Qn=!0,i.scrollTop=P,ao=i.scrollTop,Qn=!1;return}let ne=performance.now();Qn=!0;let te=fe=>1-Math.pow(1-fe,3),oe=fe=>{if(!y()){Bi();return}let Se=c();Se!==P&&(P=Se,Y=P-x);let Re=fe-ne,yt=Math.min(Re/f,1),Rt=te(yt),Ot=x+Y*Rt;i.scrollTop=Ot,ao=i.scrollTop,yt<1?Wi=requestAnimationFrame(oe):(i.scrollTop=P,ao=i.scrollTop,Wi=null,Qn=!1)};Wi=requestAnimationFrame(oe)},WE=(i,c=500)=>{let f=ir(i)-i.scrollTop;if(Math.abs(f)<1){ao=i.scrollTop;return}if(Math.abs(f)>=EE){Bi(),Qn=!0,i.scrollTop=ir(i),ao=i.scrollTop,Qn=!1;return}Ib(i,()=>ir(i),c,()=>io.isFollowing())},nd=()=>{if(!Em()){Cn();return}let i=kb();Qn=!0,i.scrollTop=ir(i),ao=i.scrollTop,Qn=!1,Cn()},Ns=i=>{let c=0,f=i;for(;f&&f!==le;)c+=f.offsetTop,f=f.offsetParent;return c},BE=()=>{let i=le.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??le.ownerDocument.getSelection()},od=()=>GS(BE(),le),km=()=>{if(lE()!=="last-user-turn")return!1;let i=$?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(P=>P.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=le.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let x=Math.min(Math.max(0,Ns(y)-Fa()),ir(le));return Qn=!0,le.scrollTop=x,ao=le.scrollTop,Qn=!1,ro()==="follow"&&!Hr(le,fr)&&io.pause(),Cn(),!0},rd=i=>{let c=Math.max(0,Math.round(i));go.style.height=`${c}px`,go.style.display=c>0?"":"none",vn&&(vn.spacerHeight=Math.max(0,i))},sd=i=>{let c=parseFloat(getComputedStyle(le).paddingBottom)||0,f=0;for(let x of Array.from(le.children)){if(x===go||x.offsetHeight===0)continue;let P=Ns(x)+x.offsetHeight;P>f&&(f=P)}let y=le.scrollHeight-i;return f>0?Math.min(f+c,y):y},OE=()=>{if(!vn||vn.spacerHeight<=0)return;let i=sd(vn.spacerHeight),c=Math.max(0,Math.round(le.scrollTop)+le.clientHeight-i+fr);c<vn.spacerHeight&&(rd(c),Cn())},Bo=()=>{Bs!==null&&(cancelAnimationFrame(Bs),Bs=null),Bi(),vn=null,go.style.height="0px",go.style.display="none"},Hb=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Lm=i=>le.querySelector(`[data-message-id="${Hb(i)}"]`),Rb=i=>{Bs!==null&&cancelAnimationFrame(Bs),Bs=requestAnimationFrame(()=>{Bs=null;let c=Hb(i),f=le.querySelector(`[data-message-id="${c}"]`);if(!f)return;let y=Ns(f),x=vn?.spacerHeight??0,P=sd(x),{targetScrollTop:Y,spacerHeight:ne}=Gg({anchorOffsetTop:y,topOffset:Fa(),viewportHeight:le.clientHeight,contentHeight:P,slack:fr});vn={initialSpacerHeight:ne,contentHeightAtAnchor:P,spacerHeight:ne},rd(ne),Ib(le,()=>f.isConnected?Math.max(0,Ns(f)-Fa()):Y,220)})},Jn=()=>{if(ro()!=="anchor-top"||!vn||!Hi)return;let i=Lm(Hi);if(!i)return;Bi();let c=vn.spacerHeight,f=sd(c),{targetScrollTop:y,spacerHeight:x}=Gg({anchorOffsetTop:Ns(i),topOffset:Fa(),viewportHeight:le.clientHeight,contentHeight:f,slack:fr});vn={initialSpacerHeight:x,contentHeightAtAnchor:f,spacerHeight:x},rd(x),Qn=!0,le.scrollTop=y,ao=le.scrollTop,Qn=!1,Cn()},DE=()=>{if(Fr()){if(!io.isFollowing()||Hr(le,1))return;Gr(!so);return}if(vn&&vn.initialSpacerHeight>0){let i=le.scrollHeight-vn.spacerHeight,c=YS({initialSpacerHeight:vn.initialSpacerHeight,contentHeightAtAnchor:vn.contentHeightAtAnchor,currentContentHeight:i});c!==vn.spacerHeight&&rd(c)}Cn()},_E=i=>{let c=ro();c==="follow"?(Xn(),Gr(!0)):c==="anchor-top"&&(Ya=!1,Qc=!0,Xc=!1,Hi=i,Rb(i))},NE=()=>{if(ro()==="anchor-top"){if(Qc){Ya=!1;return}Ya=!0,Bo(),Xn(),Gr(!0)}},FE=96,$E=i=>{if(Os===null)return!0;let c=Lm(Os),f=Lm(i);if(!c||!f)return!0;let y=Ns(f)-Ns(c);return Fa()+y>le.clientHeight-FE},VE=i=>{if(ro()!=="anchor-top"||!Qc||Xc||od())return;let c=Os===null;for(let f of i){if(!c){f.id===Os&&(c=!0);continue}if(KS(f)){if(f.id===Hi||!$E(f.id))return;Hi=f.id,Rb(f.id);return}}},zE=i=>{let c=new Map;i.forEach(f=>{let y=Sm.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(L.emit("assistant:message",f),!Ii&&(ro()!=="anchor-top"||Py())&&Tm()&&(Kr+=1,Mm(),Cn(),Wc(Kr===1?"1 new message below.":`${Kr} new messages below.`))),f.role==="assistant"&&y?.streaming&&f.streaming===!1&&L.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&L.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):L.emit("approval:requested",{approval:f.approval,message:f}))}),Sm.clear(),c.forEach((f,y)=>{Sm.set(y,f)})},Ja=(i,c)=>{let f=c==="user"?"user":"assistant",y=o.layout?.messages?.[f],x=y?.width??"content",P=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),P?i.style.setProperty("--persona-message-row-max-width",P):i.style.removeProperty("--persona-message-row-max-width")},yr=(i,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),Ja(f,c),f},qE=(i,c,f)=>{let y=document.createElement("div"),P=(()=>{let K=a.find(ze=>ze.renderLoadingIndicator);if(K?.renderLoadingIndicator)return K.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Y=(K,ze)=>ze==null?!1:typeof ze=="string"?(K.textContent=ze,!0):(K.appendChild(ze),!0),ne=new Set,te=new Map,oe=new Set,fe=a.some(K=>K.renderAskUserQuestion),Se=[],Re=[],yt=o.enableComponentStreaming!==!1,Rt=o.approval!==!1,Ot=[],Sn=o.messageActions,gn=Sn?.showRegenerate===!0&&Sn.enabled!==!1&&It.current?.isStreaming()!==!0?Iw(c):null,rn=Sn?.showEdit===!0&&Sn.enabled!==!1,On=Sn?.showQuote===!0&&Sn.enabled!==!1,Ct=null,Dn=o.features?.reasoningDisplay?.completedVisibility,Zo=K=>Dn==="removed"?!0:Dn==="removed-when-short"?ow(K,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Tr=o.features?.toolCallDisplay?.completedVisibility==="removed";if(c.forEach(K=>{if(K.variant==="reasoning"&&K.reasoning?.status==="complete"&&Zo(K.reasoning)||Tr&&K.variant==="tool"&&K.toolCall?.status==="complete")return;if(ne.add(K.id),te.set(K.id,K.role),Hs===K.id&&Ur){let tt=yr(K.id,K.role);tt.setAttribute("data-persona-message-edit-stub","true"),tt.setAttribute("data-preserve-runtime","true"),y.appendChild(tt),Ct={messageId:K.id,element:Ur.element};return}let ze=fe&&ti(K),Xe=Rt&&K.variant==="approval"&&!!K.approval,$e=!ze&&K.role==="assistant"&&!K.variant&&yt&&Cy(K);!Xe&&qr.has(K.id)&&(i.querySelector(`#wrapper-${K.id}`)?.removeAttribute("data-preserve-runtime"),qr.delete(K.id)),!$e&&Is.has(K.id)&&(i.querySelector(`#wrapper-${K.id}`)?.removeAttribute("data-preserve-runtime"),Is.delete(K.id));let wn=ti(K)?`:${K.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${K.agentMetadata?.askUserQuestionAnswers?Object.keys(K.agentMetadata.askUserQuestionAnswers).length:0}`:"",_n={canRegenerate:gn===K.id,canEdit:rn&&Zf(K),canQuote:On&&!K.variant&&(K.content?.trim().length??0)>0},Lt=`${_n.canRegenerate?"r":""}${_n.canEdit?"e":""}${_n.canQuote?"q":""}`,je=VS(K,Ws)+wn+`:${Lt}`,Oo=ze||Xe||$e?null:qS(mn,K.id,je);if(Oo){y.appendChild(Oo.cloneNode(!0)),ti(K)&&K.toolCall?.id&&K.agentMetadata?.awaitingLocalTool===!0&&!K.agentMetadata?.askUserQuestionAnswered&&(oe.add(K.toolCall.id),np(K,o,Qe.composerOverlay));return}let Zt=null,In=a.find(tt=>!!(K.variant==="reasoning"&&tt.renderReasoning||K.variant==="tool"&&tt.renderToolCall||!K.variant&&tt.renderMessage)),xn=o.layout?.messages;if(ti(K)&&K.agentMetadata?.askUserQuestionAnswered===!0){Pi.delete(K.id),i.querySelector(`#wrapper-${K.id}`)?.removeAttribute("data-preserve-runtime");return}if(El(K)&&ls(o).enabled)return;if(ti(K)&&o.features?.askUserQuestion?.enabled!==!1){let tt=a.find(po=>typeof po.renderAskUserQuestion=="function");if(tt&&It.current){let po=Pi.get(K.id),it=po!==je,ot=null;if(it){let{payload:Wt,complete:$t}=sa(K),Er=K.id,An=()=>It.current?.getMessages().find(So=>So.id===Er);ot=tt.renderAskUserQuestion({message:K,payload:Wt,complete:$t,resolve:So=>{let Vt=An();Vt&&It.current?.resolveAskUserQuestion(Vt,So)},dismiss:()=>{let So=An();So?.agentMetadata?.awaitingLocalTool&&(It.current?.markAskUserQuestionResolved(So),It.current?.resolveAskUserQuestion(So,"(dismissed)"))},config:o})}let Ft=po!=null;if(it&&ot===null&&!Ft){K.agentMetadata?.awaitingLocalTool===!0&&!K.agentMetadata?.askUserQuestionAnswered&&(oe.add(K.toolCall.id),np(K,o,Qe.composerOverlay));return}let At=yr(K.id,K.role);At.setAttribute("data-ask-plugin-stub","true"),At.setAttribute("data-preserve-runtime","true"),y.appendChild(At),Se.push({messageId:K.id,fingerprint:je,bubble:ot});return}else{K.agentMetadata?.awaitingLocalTool===!0&&!K.agentMetadata?.askUserQuestionAnswered&&(oe.add(K.toolCall.id),np(K,o,Qe.composerOverlay));return}}else if(Xe){let tt=I();if(!tt){y.appendChild(yr(K.id,K.role));return}let po=a.find(At=>typeof At.renderApproval=="function")??h,ot=qr.get(K.id)!==je,Ft=null;if(ot&&po?.renderApproval){let At=K.id,Wt=($t,Er)=>{let An=It.current?.getMessages().find(So=>So.id===At);An?.approval&&(An.approval.toolType==="webmcp"?It.current?.resolveWebMcpApproval(An.id,$t):It.current?.resolveApproval(An.approval,$t,Er))};Ft=po.renderApproval({message:K,defaultRenderer:()=>tt.createApprovalBubble(K,o),config:o,approve:$t=>Wt("approved",$t),deny:$t=>Wt("denied",$t)})}if(ot&&Ft===null)i.querySelector(`#wrapper-${K.id}`)?.removeAttribute("data-preserve-runtime"),qr.delete(K.id),Zt=tt.createApprovalBubble(K,o);else{let At=yr(K.id,K.role);At.setAttribute("data-approval-plugin-stub","true"),At.setAttribute("data-preserve-runtime","true"),y.appendChild(At),Ot.push({messageId:K.id,fingerprint:je,bubble:Ft});return}}else if(In)if(K.variant==="reasoning"&&K.reasoning&&In.renderReasoning){if(!at)return;Zt=In.renderReasoning({message:K,defaultRenderer:()=>xh(K,o),config:o})}else if(K.variant==="tool"&&K.toolCall&&In.renderToolCall){if(!Ut)return;Zt=In.renderToolCall({message:K,defaultRenderer:()=>Ah(K,o),config:o})}else In.renderMessage&&(Zt=In.renderMessage({message:K,defaultRenderer:()=>{let tt=ph(K,f,xn,o.messageActions,Ze,{loadingIndicatorRenderer:P,widgetConfig:o,actionEligibility:_n});return K.role!=="user"&&D(tt,K,o,$),tt},config:o}));if(!Zt&&$e){let tt=FT(K);if(tt){let po=Is.get(K.id),it=po!==je,ot=o.wrapComponentDirectiveInBubble!==!1&&Fo.getOptions(tt.component)?.bubbleChrome!==!1,Ft=null;if(it){let At=_T(tt,{config:o,message:K,transform:f});if(At&&tt.component==="PersonaArtifactInline"){let Wt=At.hasAttribute("data-artifact-inline")?At:At.querySelector("[data-artifact-inline]"),$t=Wt?.getAttribute("data-artifact-inline")??"",Er=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape($t):$t,An=$t?i.querySelector(`#wrapper-${K.id}`)?.querySelector(`[data-artifact-inline="${Er}"]`)??null:null;Wt&&An&&An!==Wt&&Wr()?.hasLiveInlineArtifactBlock(An)&&(Wt===At?At=An:Wt.replaceWith(An))}if(At)if(ot){let Wt=document.createElement("div");if(Wt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Wt.id=`bubble-${K.id}`,Wt.setAttribute("data-message-id",K.id),K.content&&K.content.trim()){let $t=document.createElement("div");$t.className="persona-mb-3 persona-text-sm persona-leading-relaxed",$t.innerHTML=f({text:K.content,message:K,streaming:!!K.streaming,raw:K.rawContent}),Wt.appendChild($t)}Wt.appendChild(At),Ft=Wt}else{let Wt=document.createElement("div");if(Wt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Wt.id=`bubble-${K.id}`,Wt.setAttribute("data-message-id",K.id),Wt.setAttribute("data-persona-component-directive","true"),K.content&&K.content.trim()){let $t=document.createElement("div");$t.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",$t.innerHTML=f({text:K.content,message:K,streaming:!!K.streaming,raw:K.rawContent}),Wt.appendChild($t)}Wt.appendChild(At),Ft=Wt}}if(Ft||po!=null){let At=yr(K.id,K.role);At.setAttribute("data-component-directive-stub","true"),At.setAttribute("data-preserve-runtime","true"),y.appendChild(At),Re.push({messageId:K.id,fingerprint:je,bubble:Ft});return}}}if(!Zt)if(K.variant==="reasoning"&&K.reasoning){if(!at)return;Zt=xh(K,o)}else if(K.variant==="tool"&&K.toolCall){if(!Ut)return;Zt=Ah(K,o)}else if(K.variant==="approval"&&K.approval){if(o.approval===!1)return;let tt=I();if(!tt)return;Zt=tt.createApprovalBubble(K,o)}else{let tt=o.layout?.messages;tt?.renderUserMessage&&K.role==="user"?Zt=tt.renderUserMessage({message:K,config:o,streaming:!!K.streaming}):tt?.renderAssistantMessage&&K.role==="assistant"?Zt=tt.renderAssistantMessage({message:K,config:o,streaming:!!K.streaming}):Zt=ph(K,f,tt,o.messageActions,Ze,{loadingIndicatorRenderer:P,widgetConfig:o,actionEligibility:_n}),K.role!=="user"&&Zt&&D(Zt,K,o,$)}let sn=yr(K.id,K.role);sn.appendChild(Zt),US(mn,K.id,je,sn),y.appendChild(sn)}),Qe.composerOverlay&&Qe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ze=>{let Xe=ze.getAttribute("data-persona-ask-sheet-for");Xe&&!oe.has(Xe)&&aa(Qe.composerOverlay,Xe)}),o.features?.toolCallDisplay?.grouped){let K=[],ze=[],Xe=o.features.toolCallDisplay.groupedMode==="summary";c.forEach($e=>{if($e.variant==="tool"&&$e.toolCall&&Ut){if(Tr&&$e.toolCall.status==="complete")return;ze.push($e);return}$e.variant==="reasoning"&&(!at||$e.reasoning?.status==="complete"&&Zo($e.reasoning))||((ze.length>1||Xe&&ze.length>0)&&K.push(ze),ze=[])}),(ze.length>1||Xe&&ze.length>0)&&K.push(ze),K.forEach($e=>{let wn=$e.map(xn=>Array.from(y.children).find(sn=>sn instanceof HTMLElement&&sn.getAttribute("data-wrapper-id")===xn.id)).filter(xn=>!!xn);if(wn.length<(Xe?1:2))return;let _n=yr(`tool-group-${$e[0].id}`,"assistant");_n.setAttribute("data-persona-tool-group-row","true");let Lt=document.createElement("div");Lt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Lt.setAttribute("data-persona-tool-group","true");let je=document.createElement("div");je.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",je.id=`tool-group-summary-${$e[0].id}`;let Oo=`Called ${$e.length} ${$e.length===1?"tool":"tools"}`,Zt=o.toolCall?.renderGroupedSummary?.({messages:$e,toolCalls:$e.map(xn=>xn.toolCall).filter(xn=>!!xn),defaultSummary:Oo,config:o});Y(je,Zt)||(je.textContent=Oo);let In=document.createElement("div");In.className="persona-tool-group-stack persona-flex persona-flex-col",In.id=`tool-group-stack-${$e[0].id}`,In.setAttribute("data-persona-tool-group-stack","true"),Lt.appendChild(je),Xe||Lt.appendChild(In),_n.appendChild(Lt),wn[0].before(_n),wn.forEach((xn,sn)=>{if(Xe){xn.remove();return}xn.style.setProperty("--persona-message-row-max-width","100%");let tt=document.createElement("div");tt.className="persona-tool-group-item persona-relative",tt.setAttribute("data-persona-tool-group-item","true"),sn<wn.length-1&&tt.setAttribute("data-persona-tool-group-connector","true"),tt.appendChild(xn),In.appendChild(tt)})})}jS(mn,ne);let er=c.some(K=>K.role==="assistant"&&K.streaming),Ji=c[c.length-1],Js=Ji?.role==="assistant"&&!Ji.streaming&&Ji.variant!=="approval";if(so&&c.some(K=>K.role==="user")&&!er&&!Js){let K={config:o,streaming:!0,location:"standalone",defaultRenderer:uc},ze=a.find($e=>$e.renderLoadingIndicator),Xe=null;if(ze?.renderLoadingIndicator&&(Xe=ze.renderLoadingIndicator(K)),Xe===null&&o.loadingIndicator?.render&&(Xe=o.loadingIndicator.render(K)),Xe===null&&(Xe=uc()),Xe){let $e=document.createElement("div"),wn=o.loadingIndicator?.showBubble!==!1,_n=o.layout?.messages?.layout??"bubble";$e.className=wn?mc("assistant",_n).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),$e.setAttribute("data-typing-indicator","true"),wn&&($e.style.color="var(--persona-message-assistant-text, var(--persona-text))",_n!=="flat"&&($e.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",$e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),$e.appendChild(Xe);let Lt=yr("typing-indicator","assistant");Lt.appendChild($e),y.appendChild(Lt)}}if(!so&&c.length>0){let K=c[c.length-1],ze={config:o,lastMessage:K,messageCount:c.length},Xe=a.find(wn=>wn.renderIdleIndicator),$e=null;if(Xe?.renderIdleIndicator&&($e=Xe.renderIdleIndicator(ze)),$e===null&&o.loadingIndicator?.renderIdle&&($e=o.loadingIndicator.renderIdle(ze)),$e){let wn=document.createElement("div"),_n=o.loadingIndicator?.showBubble!==!1;wn.className=_n?["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(" "),wn.setAttribute("data-idle-indicator","true"),wn.appendChild($e);let Lt=yr("idle-indicator","assistant");Lt.appendChild(wn),y.appendChild(Lt)}}if(MC(y),au(i,y),_f(i),Ct){let{messageId:K,element:ze}=Ct,Xe=i.querySelector(`#wrapper-${K}`);Xe&&ze.parentElement!==Xe&&(Ja(Xe,te.get(K)??"user"),Xe.replaceChildren(ze))}if(Se.length>0)for(let{messageId:K,fingerprint:ze,bubble:Xe}of Se){let $e=i.querySelector(`#wrapper-${K}`);$e&&(Ja($e,te.get(K)??"assistant"),Xe!==null&&($e.replaceChildren(Xe),$e.setAttribute("data-bubble-fp",ze),Pi.set(K,ze)))}if(Pi.size>0)for(let K of Pi.keys())ne.has(K)||Pi.delete(K);if(Re.length>0)for(let{messageId:K,fingerprint:ze,bubble:Xe}of Re){let $e=i.querySelector(`#wrapper-${K}`);$e&&(Ja($e,te.get(K)??"assistant"),Xe!==null&&($e.replaceChildren(Xe),$e.setAttribute("data-bubble-fp",ze),Is.set(K,ze)))}if(Is.size>0)for(let K of Is.keys())ne.has(K)||Is.delete(K);if(Ot.length>0)for(let{messageId:K,fingerprint:ze,bubble:Xe}of Ot){let $e=i.querySelector(`#wrapper-${K}`);$e&&(Ja($e,te.get(K)??"assistant"),Xe!==null&&($e.replaceChildren(Xe),$e.setAttribute("data-bubble-fp",ze),qr.set(K,ze)))}if(qr.size>0)for(let K of qr.keys())ne.has(K)||qr.delete(K)},Pm=!1,id=()=>{Pm||(Pm=!0,yC().catch(()=>{Pm=!1}))},yo=(i,c,f)=>{c.length>0&&id(),qE(i,c,f),Zy()},Za=null,UE=()=>{if(Za)return;let i=f=>{let y=f.composedPath();y.includes(rt)||Xt&&y.includes(Xt)||Bt(!1,"user")};Za=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Wb=()=>{if(!Za)return;(t.ownerDocument??document).removeEventListener("pointerdown",Za,!0),Za=null};De.push(()=>Wb());let el=null,jE=()=>{if(el)return;let i=f=>{f.key==="Escape"&&(f.isComposing||Bt(!1,"user"))};el=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},Bb=()=>{if(!el)return;(t.ownerDocument??document).removeEventListener("keydown",el,!0),el=null};De.push(()=>Bb());let tl=!1,Ob=new Set,KE=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Oi=()=>{if(!ke())return;let i=Qe.peekBanner,c=Qe.peekTextNode;if(!i||!c)return;if(Te){i.classList.remove("persona-pill-peek--visible");return}let f=$?.getMessages()??[],y;for(let gn=f.length-1;gn>=0;gn--){let rn=f[gn];if(rn.role==="assistant"&&rn.content){y=rn;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let x=y.content,P=!!y.streaming,Y=KE(),ne=pu(Y),te=ne.type!=="none"?Cm(ne.type,Y?.plugins):null,oe=te?.isAnimating?.(y)===!0,fe=te!==null&&(P||oe);fe&&te&&!Ob.has(te.name)&&(nc(te,t),Ob.add(te.name));let Se=fe&&te?.containerClass?te.containerClass:null,Re=c.dataset.personaPeekStreamClass??null;Re&&Re!==Se&&(c.classList.remove(Re),delete c.dataset.personaPeekStreamClass),Se&&Re!==Se&&(c.classList.add(Se),c.dataset.personaPeekStreamClass=Se),fe?(c.style.setProperty("--persona-stream-step",`${ne.speed}ms`),c.style.setProperty("--persona-stream-duration",`${ne.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let yt=fe?uu(x,ne.buffer,te,y,P):x;if(fe&&ne.placeholder==="skeleton"&&P&&(!yt||!yt.trim())){let gn=document.createElement("div"),rn=tc();rn.classList.add("persona-pill-peek__skeleton"),gn.appendChild(rn),au(c,gn)}else{let gn=Math.max(0,yt.length-100),rn=yt.length>100?yt.slice(-100):yt,On=kr(rn);if(!fe||!te){let Ct=yt.length>100?`\u2026${rn}`:rn;c.textContent!==Ct&&(c.textContent=Ct)}else{let Ct=On;(te.wrap==="char"||te.wrap==="word")&&(Ct=ec(On,te.wrap,`peek-${y.id}`,{skipTags:te.skipTags,startIndex:gn}));let Dn=document.createElement("div");if(Dn.innerHTML=Ct,te.useCaret&&rn.length>0){let Zo=mu(),Tr=Dn.querySelectorAll(".persona-stream-char, .persona-stream-word"),er=Tr[Tr.length-1];er?.parentNode?er.parentNode.insertBefore(Zo,er.nextSibling):Dn.appendChild(Zo)}au(c,Dn),te.onAfterRender?.({container:c,bubble:i,messageId:y.id,message:y,speed:ne.speed,duration:ne.duration})}}let Sn=so||tl;i.classList.toggle("persona-pill-peek--visible",Sn)};if(ke()){let i=Qe.peekBanner;if(i){let y=x=>{x.preventDefault(),x.stopPropagation(),Bt(!0,"user")};i.addEventListener("pointerdown",y),De.push(()=>{i.removeEventListener("pointerdown",y)})}let c=()=>{tl||(tl=!0,Oi())},f=()=>{tl&&(tl=!1,Oi())};_e.addEventListener("pointerenter",c),_e.addEventListener("pointerleave",f),De.push(()=>{_e.removeEventListener("pointerenter",c),_e.removeEventListener("pointerleave",f)}),Xt&&(Xt.addEventListener("pointerenter",c),Xt.addEventListener("pointerleave",f),De.push(()=>{Xt.removeEventListener("pointerenter",c),Xt.removeEventListener("pointerleave",f)}))}let GE=i=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",y=c.bottomOffset??"16px",x=c.collapsedMaxWidth,P=c.expandedMaxWidth??"880px",Y=c.expandedTopOffset??"5vh",ne=c.modalMaxWidth??"880px",te=c.modalMaxHeight??"min(90vh, 800px)",oe="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",Se=rt.style;if(Se.left="",Se.right="",Se.top="",Se.bottom="",Se.transform="",Se.width="",Se.maxWidth="",Se.height="",Se.maxHeight="",Xt){let Re=Xt.style;Re.bottom=y,Re.width=x??""}if(i&&f!=="fullscreen"){if(f==="modal"){Se.top="50%",Se.left="50%",Se.transform="translate(-50%, -50%)",Se.bottom="auto",Se.right="auto",Se.width=ne,Se.maxWidth=oe,Se.maxHeight=te,Se.height=te;return}Se.left="50%",Se.transform="translateX(-50%)",Se.bottom=`calc(${y} + ${fe})`,Se.top=Y,Se.width=P,Se.maxWidth=oe}},nl=()=>{if(Te&&id(),!Ie())return;if(ke()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Te?"expanded":"collapsed";rt.dataset.state=fe,rt.dataset.expandedSize=oe,Xt&&(Xt.dataset.state=fe,Xt.dataset.expandedSize=oe),rt.style.removeProperty("display"),rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),GE(Te),Pe.style.display=Te?"flex":"none",Ms(),Te?(UE(),jE()):(Wb(),Bb()),Oi();return}let i=cn(o),c=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,x=c.innerWidth<=f,P=y&&x&&ue,Y=ko(o).reveal;Te?(rt.style.removeProperty("display"),rt.style.display=i?"flex":"",rt.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"),nn?(nn.setPanelOpen(!0),nn.element.style.display="none"):Fn&&(Fn.style.display="none")):(i?i&&(Y==="overlay"||Y==="push")&&!P?(rt.style.removeProperty("display"),rt.style.display="flex",rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(rt.style.setProperty("display","none","important"),rt.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(rt.style.display="",rt.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")),nn?(nn.setPanelOpen(!1),nn.element.style.display=i?"none":""):Fn&&(Fn.style.display=i?"none":""))},Bt=(i,c="user")=>{if(!Ie()||Te===i)return;let f=Te;Te=i,nl();let y=(()=>{let P=o.launcher?.sidebarMode??!1,Y=t.ownerDocument.defaultView??window,ne=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640,oe=Y.innerWidth<=te,fe=cn(o)&&ne&&oe,Se=ke()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||ne&&oe&&ue||fe||Se})();if(Te&&y){if(!Go){let P=t.getRootNode(),Y=P instanceof ShadowRoot?P.host:t.closest(".persona-host");Y&&(Go=th(Y,o.launcher?.zIndex??Rn))}Yo||(Yo=nh(t.ownerDocument))}else Te||(Go?.(),Go=null,Yo?.(),Yo=null);Te&&(vl(),km()||(ro()==="follow"?Gr(!0):nd()));let x={open:Te,source:c,timestamp:Date.now()};Te&&!f?L.emit("widget:opened",x):!Te&&f&&L.emit("widget:closed",x),L.emit("widget:state",{open:Te,launcherEnabled:ue,voiceActive:dt.active,streaming:$.isStreaming()})},Yr={inputDisabled:!1,sendDisabled:!1},Qr=()=>Yr.inputDisabled,Fs=()=>Yr.inputDisabled||Yr.sendDisabled,YE=()=>(Yr.inputDisabled?Yr.inputReason:void 0)??(Yr.sendDisabled?Yr.sendReason:void 0);function Im(){if(!Ne)return;if(Fe.getState().phase==="streaming"){Ne.disabled=!1;return}let i=vt?!vt.isReady():!1;Ne.disabled=Fs()||i}function ad(){if(!zo)return;let i=Fe.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;zo.toggleAttribute("data-persona-send-hidden",c)}function QE(){let i=YE();if(ke()){let c=Bn??Be;i?c.setAttribute("title",i):c.removeAttribute("title"),Be.toggleAttribute(Ba,!!i);return}if(i){ft.setAttribute("role","status"),ft.setAttribute("aria-live","polite"),ft.setAttribute(Ba,""),ft.textContent=i;return}if(ft.hasAttribute(Ba)&&(ft.removeAttribute("role"),ft.removeAttribute("aria-live"),ft.removeAttribute(Ba),p)){let c=$.getStatus();Wn(ft,wt(c),o.statusIndicator??{},c)}}function Hm(){let i=bg(o.composer?.inputDisabled),c=bg(o.composer?.sendDisabled);Yr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},Fe.setInputDisabled(i.disabled),Fe.setSendDisabled(c.disabled);let f=Fe.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")),Jt&&(Jt.disabled=y),qt&&(qt.disabled=y);for(let P of ln?.affordanceButtons??[])P.querySelectorAll("button").forEach(Y=>{Y.disabled=y});ye&&(ye.disabled=x),ks.forEach(P=>{P.elements.forEach(Y=>{Y.toggleAttribute("data-disabled",x),Y instanceof HTMLButtonElement||Y.setAttribute("aria-disabled",x?"true":"false")}),P.buttons.forEach(Y=>{Y.disabled=x})}),Dm.forEach(P=>{P.toggleAttribute("data-disabled",x),P instanceof HTMLButtonElement?P.disabled=x:P.setAttribute("aria-disabled",x?"true":"false"),P.querySelectorAll("button").forEach(Y=>{Y.disabled=x})}),Be.dataset.personaComposerStreaming=f?"true":"false",Be.dataset.personaComposerInputDisabled=y?"true":"false",Be.dataset.personaComposerSendDisabled=Fs()?"true":"false",Be.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(P=>{(P instanceof HTMLButtonElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P instanceof HTMLSelectElement)&&(P.disabled=f)}),Im(),QE()}let ol=i=>{Fe.setStreaming(i),ky(i?"stop":"send"),Hm()},$s=()=>{dt.active||Ae&&Ae.focus()};L.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>$s(),200)});let Vs=null,rl=!1,Rm=!pn.hidden,Xr=null,Wm=!w,ld=null;De.push(()=>{ld?.cancel(),ld=null});let XE=i=>{let c=DA(i);if(c===Bc)return;Bc=c,t.setAttribute("data-persona-conversation-state",c);let f=rm();Dc(),Wm&&(ld?.cancel(),ld=BA(Be,c==="active"?f:rm(),c==="active"?"drop":"rise")),Jn()},Db=null,_b,Nb=null,Di=null,Bm=!1,sl=i=>{let c=Rr(o),f=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(f!==Db||c.icon!==_b)&&(Db=f,_b=c.icon,wu({host:pn,iconHolder:Da,kicker:_a,title:em,subtitle:tm,starterSuggestions:Ci},c));let y=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;y!==Nb&&(Nb=y,xu(Pn,c.message,o));let x=i??($?$.getMessages():o.initialMessages);XE(x);let P=rl,Y=!P&&Aa(c,x),ne=Y!==Rm;if(Rm=Y,Di){Xr?.cancel(),Xr=null,P!==Bm&&(Bm=P,P?fh(le,pn,null):mh(le,pn,Di)),Sa(le,pn,!P);return}if(ne&&!Y&&!P&&c.dismiss==="on-first-message"&&Wm){Xr=WA(pn,oe=>{Xr===oe&&(Xr=null),!Rm&&!Di&&(Sa(le,pn,!1),Jn()),oe?.cancel()});return}if(Xr){if(!Y&&!P)return;Xr.cancel(),Xr=null}let te=!pn.hidden;Sa(le,pn,Y),!Y&&te&&Jn()},Om=[],Dm=[],_m=!1,Fb=null,$b,Vb=()=>{Dm.length=0;let i=Om.splice(0,Om.length);for(let c of i)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};De.push(Vb);let JE=(i,c)=>{let f=rh(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=sh({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:pn,submitPrompt:Bd});return Dm.push(x),x},Nm=()=>{if(_m)return;_m=!0;let i=Rr(o);Fb=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,$b=i.icon;try{Vb(),fh(le,pn,Di),Di=null,Bm=!1;let c=$?$.getMessages():o.initialMessages,f=Aa(i,c),y=0,x=null;for(let P of a)if(P.renderWelcome&&(x=P.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>pn,sendMessage:Y=>{if(!$||$.isStreaming())return;let ne=Y.trim();ne&&$.sendMessage(ne)},requestRender:()=>Nm(),renderStarter:Y=>JE(Y,y++),storage:u(P.id),onCleanup:Y=>{Om.push(Y)}}),x))break;x&&x!==pn&&(Di=x,mh(le,pn,x))}finally{_m=!1}sl()},ZE=()=>{let i=Rr(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Fb&&i.icon===$b||Nm()},cd=()=>{sl(),Mi||(Ae.placeholder=Hx(Fe.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(Ne.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))"},ek=!!o.setStoredConversationId,_i=i=>Z(c=>{let f={...c};return delete f[i],f}),dd=i=>{let c=H[i];return typeof c=="string"?c:null},zb=()=>{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:()=>dd("sessionId"),setStoredSessionId:i=>{Z(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>_i("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>dd("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{Z(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>_i("conversationId"))});let qb=()=>o.clientToken??null,Ub=i=>gT(i,Ge(),o.persistState===!1),jb=qb(),br=jb?Ub(jb):null,vr={...br?{visitorStore:br}:{},historyBootstrapReady:R,getStoredMessageCursor:()=>dd("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){_i("historyMessageCursor");return}Z(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){_i("pendingDisplayProjections");return}Z(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:zb,setStoredResumableHandle:i=>{if(!i){_i("durableResume");return}Z(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>z&&zb()!==null,...ek?{}:{getStoredConversationRevision:()=>dd("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){_i("conversationRevision");return}Z(c=>({...c,conversationRevision:i}))}}};if(z){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??(P=>$.getClient().reconnectClientTokenStream(P)),onExecutionState:P=>{(P||!f)&&vr.setStoredResumableHandle?.(P?{executionId:P.executionId,after:P.lastEventId}:null),i?.(P)}}}let tk=()=>{let i=qb();if(i&&br?.matches(i,Ge(),o.persistState===!1)||!i&&!br)return;br?.destroy(),br=i?Ub(i):null;let c={...vr};br?c.visitorStore=br:delete c.visitorStore,vr=c,$.setHistoryInternals(vr)},zs=null,nk=()=>{zs==null&&(zs=setInterval(()=>{let i=We.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(zs),zs=null;return}let c=Date.now();i.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=sp(c-y))})},100))},Fm=(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((Y,ne)=>Fm(Y,c[ne]));let f=i,y=c,x=Object.keys(f),P=Object.keys(y);return x.length===P.length&&x.every(Y=>Object.prototype.hasOwnProperty.call(y,Y)&&Fm(f[Y],y[Y]))},Kb=i=>{let{content:c,rawContent:f,llmContent:y,...x}=i;return x},$m=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Cy(i),ok=(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))&&$m(y)&&$m(x)&&Fm(Kb(y),Kb(x))},Vm=null,Ni=null,qs=null,Cr=null,zm=null,rk=i=>{if(!z)return Ri(i);zm=i,queueMicrotask(()=>{zm===i&&(zm=null,Ri(i))})},pd=i=>{Vm=i;let c,f;Ni=null;for(let x=i.length-1;x>=0;x-=1){let P=i[x];if(!c&&P.role==="user"&&(c=P),!f&&P.role==="assistant"&&(f=P),!Ni&&$m(P)&&(Ni={index:x,id:P.id}),c&&f&&Ni)break}yo(We,i,Ue),Wr()?.updateInlineArtifactBlocks(We,ho.artifacts,{suppressTransition:so}),nk(),sl(i),Li(i),Gr(!so),zE(i),i.length===0&&(Bo(),Ya=!0,Qc=!1,Hi=null,Xc=!1),!wm||Ii?(wm=!0,Os=c?.id??null,xm=f?.id??null):c&&c.id!==Os?(Os=c.id,_E(c.id)):f&&f.id!==xm&&NE(),f&&(xm=f.id),VE(i);let y=dt.lastUserMessageId;c&&c.id!==y&&(dt.lastUserMessageId=c.id,L.emit("user:message",c)),dt.lastUserMessageWasVoice=!!c?.viaVoice,rk(i),Oi()},qm=()=>{Cr!==null&&(cancelAnimationFrame(Cr),Cr=null);let i=qs;qs=null,i&&pd(i)},Gb=()=>{Cr!==null&&cancelAnimationFrame(Cr),Cr=null,qs=null},sk=i=>{let c=qs??Vm;if(so&&c&&Ni&&ok(c,i,Ni)){qs=i,Cr===null&&(Cr=requestAnimationFrame(()=>{Cr=null;let f=qs;qs=null,f&&pd(f)}));return}if(i.length===0){Gb(),pd(i);return}qm(),pd(i)};$=new hp(o,{onMessagesChanged(i){sk(i)},onStatusChanged(i){let c=o.statusIndicator??{};Wn(ft,(y=>y==="idle"?c.idleText??hn.idle:y==="connecting"?c.connectingText??hn.connecting:y==="connected"?c.connectedText??hn.connected:y==="error"?c.errorText??hn.error:y==="paused"?c.pausedText??hn.paused:y==="resuming"?c.resumingText??hn.resuming:hn[y])(i),c,i),jt()},onStreamingChanged(i){i||($?.getMessages().length===0?Gb():qm()),so=i,ol(i),jt(),$&&yo(We,$.getMessages(),Ue),i||(Gr(!0),OE(),Cb=!0,$&&wb($.getMessages(),ls(o))),Cn(),Wc(i?"Responding\u2026":"Response complete."),Oi()},onVoiceStatusChanged(i){if(L.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Mr(),Qi();break;case"processing":Mr(),a0();break;case"speaking":Mr(),l0();break;default:i==="idle"&&$.isBargeInActive()?(Mr(),Qi(),ye?.setAttribute("aria-label","End voice session")):(dt.active=!1,Mr(),hr("system"),Wo());break}},onArtifactsState(i){ho=i,i.artifacts.length===0&&(Ti=!1),Wr()?.updateInlineArtifactBlocks(We,i.artifacts,{suppressTransition:so}),Ro(),Ri()},onHistoryStateChanged(i){ut(i)},onHistoryNotice(i){lt(i)},onReconnect(i){let{executionId:c,lastEventId:f}=i.handle;i.phase==="paused"?L.emit("stream:paused",{executionId:c,after:f}):i.phase==="resuming"?L.emit("stream:resuming",{executionId:c,after:f,attempt:i.attempt??1}):L.emit("stream:resumed",{executionId:c,after:f})}},vr),It.current=$,De.push(()=>$.cancel()),De.push(()=>{$.destroy(),br?.destroy()});let Um=null;if($.onReadAloudChange((i,c)=>{Xy=i,Jy=c,Zy();let f=i??Um;i&&(Um=i);let y=f?$.getMessages().find(x=>x.id===f)??null:null;L.emit("message:read-aloud",{messageId:f,message:y,state:c,timestamp:Date.now()}),c==="idle"&&(Um=null)}),p=!0,wm=!0,o.voiceRecognition?.provider?.type==="runtype")try{$.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let ik=720,ak=250,ht=iy(o.features?.history?.copy),lo=null,jm=!1,kt=null,ud=null,md="conversation",Km=null,Nn=null,Qo=null,fd=$.getHistoryState(),Gm=null,il=0,Ym=null,gd=null,hd=null,Qm=`persona-history-${Math.random().toString(36).slice(2,8)}`,Xm=()=>o.features?.history?.enabled===!0,Xo=()=>Xm()&&!!lo&&!jm,Yb=()=>{let i=$.getStatus();return so||i==="paused"||i==="resuming"},Jm=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",f=lo?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},Fi=()=>ud?.scope??Jm(),Qb=()=>$.getClientSession()?.targetId??null,Xb=i=>`${i.state}:${"reason"in i?i.reason:""}`,lk=i=>{let c=Xb(i);c!==Gm&&(Gm=c,L.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},yd=i=>{i&&(dr.textContent="",dr.textContent=i)},Jb=null,Zb=null,ck=()=>{if(!Xm())return null;let i=OT();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Jb!==c&&(Jb=c,Zb=c()),Zb):$.isClientTokenMode()?DT({client:$.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>$.bindActivatedSession(f),getClient:()=>$.getClient()}):null},ev=()=>{gd?.(),gd=null,hd?.(),hd=null,jm=!1,lo=ck();let i={...vr};lo?i.historyProvider=lo:delete i.historyProvider,vr=i,$.setHistoryInternals(vr),lo&&(gd=lo.subscribeAvailability?.(c=>{jm=!c,c||Zn({restoreFocus:!1}),Zr()})??null,hd=lo.subscribeIdentityStatus(c=>lk(c)),Gm=Xb(lo.getIdentityStatus()))},Zm=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!ue||cn(o)))return"panel";let c=Ko??Pe;return(c.getBoundingClientRect().width||c.clientWidth)>=ik?"rail":"panel"},bo=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},bd="data-persona-history-suppressed",co=null,Jr=null,Us=null,al=null,ef=null,tv="",nv=()=>ve===ef?tv:o.layout?.showHeader===!1?"none":"",dk=()=>re==="panel"&&!!Us&&al===Us.element&&o.layout?.showHeader!==!1&&nv()!=="none",pk=()=>{for(let i of Array.from(ve.children))i!==co&&i.setAttribute(bd,"")},uk=()=>{for(let i of Array.from(Pe.querySelectorAll(`[${bd}]`)))i.removeAttribute(bd)},mk=()=>{let i=Us;if(!i)return;if(Array.from(ve.children).some(y=>y!==co&&!y.hasAttribute(bd))){Jr&&Jr!==ve&&(Jr.style.removeProperty("min-height"),Jr=null);let y=ve.offsetHeight;y>0&&(ve.style.minHeight=`${y}px`,Jr=ve)}co||(co=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==co&&co.replaceChildren(f),co.parentNode!==ve&&ve.appendChild(co),pk()},ov=()=>{Jr&&(Jr.style.removeProperty("min-height"),Jr=null),co&&(Us?.setHeaderPlacement("inline"),co.remove(),co=null,uk())},vd=null,tf=()=>{if(vd){if(le.style.display="none",bo(le,!0),Be.hidden=!0,bo(Be,!0),dk()){mk(),ve.style.display=nv(),bo(ve,!1);return}ov(),ve.style.display="none",bo(ve,!0)}};Le=tf;let fk=i=>{let c=le.style.display,f=Be.hidden,y=Be,x=ve,P=ve.style.display;ef=x,tv=P,vd=()=>{vd=null,ov(),ef=null,le.style.display=c,bo(le,!1),y.hidden=f,bo(y,!1),Be!==y&&(Be.hidden=!1,bo(Be,!1)),x.style.display=P,bo(x,!1),ve!==x&&(ve.style.display=o.layout?.showHeader===!1?"none":"",bo(ve,!1))},Be.parentNode?.insertBefore(i,Be),tf()},$i=null,js=null,ll=null,Vi=null,rv=()=>[ve,Qe.closeButtonWrapper,Qe.clearChatButtonWrapper,le,Be],gk=52,Cd=()=>o.features?.history?.rail?.collapsible!==!1,zi=()=>o.features?.history?.rail?.side==="right"?"right":"left",nf=200,of=400,rf=i=>Math.min(of,Math.max(nf,Math.round(i))),hk=()=>o.features?.history?.rail?.resizable===!0,cl,yk=()=>{if(cl===void 0&&(cl=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Ge()}rail-width`));i&&(cl=i)}catch{}return cl},dl=()=>rf(yk()??o.features?.history?.rail?.width??260),bk=i=>{if(cl=i,o.persistState!==!1)try{window.localStorage.setItem(`${Ge()}rail-width`,String(i))}catch{}},wd=()=>Cd()&&o.features?.history?.rail?.collapsedBehavior==="overlay",fn=!1,sv=i=>{let c=v("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},vk=()=>{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=sv(i.iconUrl):f=i.icon?He(i.icon,20):null),f?f.cloneNode(!0):null}},Ck=()=>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=sv(y.iconUrl):x=y.icon?He(y.icon,20):null}catch(P){f(P),x=null}return x},onSelect:()=>{try{y.onSelect()}catch(P){f(P)}}}})}})??[],wk=i=>{let c=Ck();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},pl=null,iv=()=>`${Ge()}rail-collapsed`,sf=()=>{if(pl===null&&(pl=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(iv());i&&(pl=i==="1")}catch{}return pl},af=i=>{if(pl=i,o.persistState!==!1)try{window.localStorage.setItem(iv(),i?"1":"0")}catch{}},ul=()=>re==="rail"&&Cd()&&!wd()&&sf(),lf=()=>{},av=()=>{if(wd()){lf();return}af(!sf()),kt?.view.setCollapsed(ul()),Me(),Jn()},cf=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!su(i)?null:{combo:i,hint:iu(i),aria:Xl(i)}},lv=()=>{d.forEach(c=>c()),d=[];let i=cf();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>J&&re==="rail"&&Cd()||Ui(),run:()=>wd()?lf():av()}));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}`}))};lv();let xk=300,xd="var(--persona-history-overlay-margin,8px)",vo=null,wr=null,Sd=0,xr=null,qi=null,Ks=!1,df=0,cv=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ui=()=>Xo()&&wd()&&(re??Zm())==="rail",Sk=()=>J&&!fn,ml=()=>{qi!==null&&clearTimeout(qi),qi=null},Ak=()=>{hy().catch(()=>{})},dv=()=>{ml(),fn&&(qi=setTimeout(()=>{qi=null,!(Ks||!fn)&&(xr?.contains(document.activeElement)||Zn({restoreFocus:!1}))},xk))},Mk=(i,c)=>{let f=xr?.getBoundingClientRect();if(!f)return!1;let y=vo?.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},pf=i=>{fn&&(Ks=Mk(i.clientX,i.clientY),Ks?ml():qi===null&&dv())},pv=i=>{J||!Ui()||(fn=!0,gl({invoker:vo,keyboard:i?.keyboard===!0}).then(()=>{J?!Ks&&document.activeElement!==vo&&Zn():fn=!1}))},uv=()=>{let i=al?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",fn?ht.expandLabel:ht.collapseLabel),i.setAttribute("aria-expanded",fn?"false":"true"))},mv=()=>{af(!1);let i=kt;if(!fn||!i){gl({invoker:vo});return}let c=document.activeElement===vo;fn=!1,Ad(),i.element.remove(),mf(i.element),uv(),c&&Td(),Jn(),Zr()},Tk=()=>{af(!0),Zn()};lf=()=>{!J||fn?mv():Tk()};let Ek=()=>{let i=cf(),c=si({ariaLabel:ht.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":Qm,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{Ks=!0,ml(),!(cv()||Date.now()<df)&&pv()}),f.addEventListener("mouseleave",()=>{Ks=!1,df=0,dv()}),f.addEventListener("focus",()=>{J||Ak()}),f.addEventListener("click",y=>{Xo()&&(y.detail!==0&&cv()&&!J?pv():mv())}),vo=f,wr=c.wrapper},fl=()=>{if(wr&&!wr.isConnected&&(wr=null,vo=null),!Ui()){wr?.remove(),wr=null,vo=null;return}vo||Ek();let i=wr,c=vo;if(!i||!c)return;let f=zi()!=="right"?ve.firstChild:null;(f??ve.lastChild)!==i&&ve.insertBefore(i,f),i.style.display=Sk()||Sd>0?"none":"",c.setAttribute("aria-label",ht.expandLabel),c.setAttribute("aria-expanded",J?"true":"false"),xr&&Me()},fv=i=>{if(!fn)return;let c=i.target;c instanceof Node&&(xr?.contains(c)||wr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Zn({restoreFocus:!1}))};document.addEventListener("pointerdown",fv,!0),De.push(()=>{document.removeEventListener("pointerdown",fv,!0),document.removeEventListener("pointermove",pf),ji?.(),ml()});let uf=null,ji=null,gv=16,hv=i=>{bk(rf(i)),Me(),Jn()},kk=()=>{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(nf)),i.setAttribute("aria-valuemax",String(of)),i.addEventListener("pointerdown",c=>{let f=js;if(!f||c.button!==0)return;c.preventDefault(),ji?.();let y=c.clientX,x=f.getBoundingClientRect().width||dl(),P=zi()==="right"?-1:1,Y=x,ne=t.ownerDocument;f.style.transition="none";let te=fe=>{Y=rf(x+P*(fe.clientX-y)),f.style.flex=`0 0 ${Y}px`,i.setAttribute("aria-valuenow",String(Y))},oe=()=>{ji=null,ne.removeEventListener("pointermove",te),ne.removeEventListener("pointerup",oe),ne.removeEventListener("pointercancel",oe),f.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}hv(Y)};ji=oe,ne.addEventListener("pointermove",te),ne.addEventListener("pointerup",oe),ne.addEventListener("pointercancel",oe);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let f=zi()==="right"?-gv:gv,y=dl(),x=c.key==="ArrowRight"?y+f:c.key==="ArrowLeft"?y-f:c.key==="Home"?nf:c.key==="End"?of:null;x!==null&&(c.preventDefault(),hv(x))}),i},Lk=(i,c)=>{if(!hk()||ul()){ji?.(),uf?.remove();return}let f=uf??kk();uf=f,f.setAttribute("aria-label",ht.resizeLabel),f.setAttribute("aria-valuenow",String(dl())),f.nextElementSibling!==c&&i.insertBefore(f,c)};Me=()=>{kt?.view.setRailSide(zi());let i=zi()==="right",c=xr;if(c){let ne=vo?vo.getBoundingClientRect().bottom-Pe.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(ne))}px + ${xd})`,c.style.width=`${dl()}px`,c.style.left=i?"":xd,c.style.right=i?xd:""}let f=js,y=$i,x=ll;if(!f||!y||!x)return;f.style.flex=`0 0 ${ul()?gk:dl()}px`;let P="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":P,f.style.borderLeft=i?P:"";let Y=i?x:f;y.firstElementChild!==Y&&y.append(Y,i?f:x),Lk(y,i?f:x)};let yv=i=>{if(Vi&&js){Vi.replaceWith(i),Vi=null,Me();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",Pe.insertBefore(c,ve.parentNode===Pe?ve:le);for(let x of rv())x?.parentNode===Pe&&f.appendChild(x);c.append(y,f),y.appendChild(i),$i=c,js=y,ll=f,Me()},Pk=()=>{if($i)return;let i=v("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",Vi=i,yv(i),Jn()},bv=()=>{Vi&&(Ad(),Jn())},Ik=i=>{let c=v("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${xd};display:flex;overflow:hidden;z-index:${ma-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Pe.style.position="relative",Pe.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",pf),xr=c,Me(),uv()},Ad=()=>{vd?.(),xr&&(Ks&&(df=Date.now()+150),document.removeEventListener("pointermove",pf),xr.remove(),xr=null);let i=$i;if(i){ji?.();for(let c of rv())c&&i.contains(c)&&Pe.insertBefore(c,i);i.remove(),$i=null,js=null,ll=null,Vi=null}},vv=i=>{al=i,i.id=Qm,i.style.flex="1 1 auto",i.style.minHeight="0"},mf=i=>{vv(i),(re!=="rail"||fn)&&bv(),re!=="rail"?fk(i):fn?Ik(i):yv(i)},Md=()=>{if(fl(),Pv(),!J||!kt)return;let i=Zm();if(i===re)return;let c=document.activeElement,f=c instanceof HTMLElement&&(kt.element.contains(c)||co?.contains(c)===!0)?c:null;Ad(),kt.element.remove(),kt.view.setHeaderPlacement("inline"),re=i,kt.view.setPresentation(i),kt.view.setCollapsed(ul()),kt.requestRender(),kt.element.isConnected||mf(kt.element),f?.isConnected?f.focus():Td(),Cn(),Jn(),Zr()},Cv=(i,c)=>co?.querySelector(c)??i.querySelector(c),Td=()=>{let i=kt?.element??al;if(!i)return;let c=Cv(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=Cv(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},gl=async i=>{if(!Xo()||J)return;let c=lo;if(!c)return;if(!fn&&Ui()&&sf()){fl();return}Ed();let f=++il;md=i?.returnSurface??"conversation",Km=i?.invoker??Nn;let y=Ui()&&!fn;y&&(Sd+=1,fl(),Pk());let x;try{x=await hy()}catch{yd(ht.openHistoryLabel),y&&(Sd-=1,f===il&&(bv(),fl()));return}if(y&&(Sd-=1),f!==il||J)return;ud={scope:Jm()},re=Zm(),J=!0;let P=re==="panel"&&o.layout?.showHeader!==!1&&ve.style.display!=="none"?"external":"inline",Y=o.features?.history?.rowAvatar,ne=cf(),te=ne?{hint:ne.hint,aria:ne.aria}:null,oe={provider:c,context:ud,targetId:Qb(),presentation:re,collapsible:Cd(),collapsed:ul(),railSide:zi(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:vk(),onToggleCollapse:av,...te?{collapseShortcut:te}:{},headerPlacement:P,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:Y===!1?!1:typeof Y=="string"?Y: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:fe=>gf(fe,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:fe=>Gs(fe),attachTooltip:En,onStartNew:()=>hf({focusComposer:!0}),onClose:()=>Zn(),onRequestDeleteConversation:fe=>Lv(fe),onRequestClearHistory:()=>Dk(),...c.resetDevice?{onRequestResetIdentity:()=>_k()}:{}};kt=BT({plugins:a,config:o,getPresentation:()=>re??"panel",getReturnSurface:()=>md,close:()=>Zn(),createView:({slots:fe,renderDom:Se,onModelChange:Re,railSections:yt})=>(Us=x.createHistoryView({...oe,railSections:wk(yt),slots:fe,renderDom:Se,onModelChange:Re,onAnnounce:yd}),Us),onElementChanged:(fe,Se)=>{if(!Se?.isConnected)return mf(fe);vv(fe),Se.replaceWith(fe),tf()}}),kt.view.setNewConversationRequired(fd.recovery==="new_conversation_required"),i?.focus!==!1&&(re!=="rail"||i?.keyboard===!0)&&Td(),Cn(),Jn(),Zr(),L.emit("history:opened",{presentation:re,returnSurface:md,timestamp:Date.now()})},Ed=()=>{},Zn=i=>{if(!J)return;il+=1;let c=md,f=Km,y=kt,x=i?.restoreFocus!==!1;J=!1;let P=!1,Y=null,ne=()=>{if(!P){if(P=!0,Ed=()=>{},Y!==null&&clearTimeout(Y),fn=!1,ml(),Ad(),y?.dispose(),y?.view.destroy(),y?.element.remove(),kt===y&&(kt=null,Us=null,al=null,re=null,ud=null,Km=null),Cn(),Jn(),Zr(),x){let oe=f??Nn;oe?.isConnected?oe.focus():$s()}L.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},te=y&&y.element===y.view.element?y.view.playExit():null;if(!te){ne();return}Ed=ne,Y=setTimeout(ne,ak),te.then(ne)},wv=i=>{if(!(i.key!=="Escape"||!J||!kt)){if(re==="rail"){let c=i.target;if(!(c instanceof Node)||!(kt.element.contains(c)||fn&&wr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Zn()}};Pe.addEventListener("keydown",wv),De.push(()=>Pe.removeEventListener("keydown",wv));let kd=null,xv=!1,hl=()=>{if(!Oe)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&kd?.trim()||null;Oe.textContent=c??o.launcher?.title??"Chat Assistant";let f=Oe.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")},Hk=i=>{i!==kd&&(kd=i,hl())},Gs=i=>{xv=i?.starred===!0,Hk(i&&i.title.trim()||null),hl()};hl(),Pe.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,f=$.getActiveConversationId();f&&(c==="delete"?Lv(f):c==="star"&&$.canUpdateConversations()&&yf(f,{starred:!xv}).catch(()=>{}))});let Ld=0,Rk=250,Pd=null,Id=()=>{Pd&&clearTimeout(Pd),Pd=null};De.push(Id);let Sv=()=>{Id();let i=Vs;i&&(rl=!0,i.hidden=!1,We.style.display="none",sl())},Hd=()=>{Ld+=1,Id(),Vs&&(Vs.remove(),Vs=null,rl=!1,We.style.removeProperty("display"),bo(Be,!1),sl())},Wk=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;We.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},ff=(i,c)=>q("div",{className:Dt("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),Av=()=>q("div",{className:"persona-conversation-loading-body"},ff("58%",!1),ff("72%",!0),ff("44%",!1)),Mv=i=>{Vs?.remove(),Vs=i,i.hidden=!rl,le.insertBefore(i,We),Id(),rl||(Pd=setTimeout(Sv,Rk)),bo(Be,!0)},Bk=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Av},c=null,f=a.find(y=>y.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Mv(q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":ht.openConversationLoadingLabel}},c??Av()))},Ok=i=>{let c=()=>{gf(i,{focusComposer:!0}).catch(()=>{})},f=Xo()?()=>{Hd(),gl()}:void 0,y=(ne,te)=>{let oe=q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:ne});return oe.addEventListener("click",te),oe},x=()=>q("div",{className:"persona-conversation-loading-error-body"},q("p",{className:"persona-conversation-loading-error-title",text:ht.openConversationErrorTitle}),q("div",{className:"persona-conversation-loading-error-actions"},y(ht.openConversationRetryLabel,c),f?y(ht.openConversationBackLabel,f):null)),P=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:ht.openConversationErrorTitle,retryLabel:ht.openConversationRetryLabel,backLabel:ht.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:x}),Y=null;for(let ne of a)if(ne.renderHistoryOpenError){try{Y=ne.renderHistoryOpenError(P)}catch(te){console.warn("[persona] renderHistoryOpenError threw",te),Y=null}if(Y)break}Mv(q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Y??x())),Sv()};L.on("history:closed",()=>{Vs&&bo(Be,!0)});let gf=async(i,{focusComposer:c=!1}={})=>{let f=Fi(),y=!!kt;kt?.view.setActiveConversationId(i),Hd();let x=Ld;Bk(),J&&(re==="panel"||fn)&&Zn({restoreFocus:!1}),Ii=!0;try{await $.openConversation(i,{scope:f})}catch(P){throw x===Ld&&Ok(i),P}finally{Ii=!1}x===Ld&&(Hd(),mn.clear(),Bo(),Xn(),km()||nd(),Wk(),Sr(),y||Gs(null),L.emit("history:conversationOpened",{conversationId:i,title:kd,scope:f,timestamp:Date.now()}),c&&$s())},hf=async({focusComposer:i=!1}={})=>{Hd(),await $.startNewConversation({scope:Fi()}),Gs(null),mn.clear(),Bo(),Xn(),nd(),Sr();let c=$.getActiveConversationId();kt?.view.setActiveConversationId(c),L.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),J&&(re==="panel"||fn)&&Zn({restoreFocus:!1}),i&&$s()},yf=async(i,c)=>{let f=await $.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return kt?.view.applyConversationSummary(f),!kt&&i===$.getActiveConversationId()&&Gs(f),f},Tv=async i=>{let c=Fi(),f=$.getActiveConversationId()===i;await $.deleteConversation(i,{scope:c}),kt?.view.removeConversationSummary(i),f&&(Gs(null),mn.clear(),Bo(),Xn(),Sr()),L.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:f,timestamp:Date.now()})},Ev=async i=>{let c=i?.scope??Fi(),f=i?.allTargets?null:i?.targetId??Qb(),y=await $.clearConversationHistory({...f?{targetId:f}:{},scope:c});return Gs(null),mn.clear(),Bo(),Xn(),Sr(),L.emit("history:cleared",{deleted:y.deleted,scope:c,targetId:f,timestamp:Date.now()}),y},kv=async()=>{if(!lo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await $.resetHistoryDevice()).remoteRevocationConfirmed}finally{Gs(null),$.clearArtifacts(),mn.clear(),Vm=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),H={},pe.syncFromMetadata(),W?.clear&&Zc(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),Bo(),Xn(),Sr(),Zn({restoreFocus:!1}),$s(),Te||nn?.launcher.element.focus()}return yd(i?ht.identityResetNotice:ht.identityResetUnconfirmedNotice),L.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},bf=()=>Ko?_e:Pe,Lv=async i=>await Xu({host:bf(),title:ht.deleteConversationConfirmTitle,description:ht.deleteConversationConfirm,confirmLabel:ht.deleteConversationConfirmLabel,cancelLabel:ht.confirmCancelLabel})?(await Tv(i),"deleted"):"cancelled",Dk=async()=>{let i=Fi()==="verified-user";return await Xu({host:bf(),title:ht.clearHistoryConfirmTitle,description:i?ht.clearHistoryVerifiedConfirm:ht.clearHistoryConfirm,confirmLabel:ht.clearHistoryConfirmLabel,cancelLabel:ht.confirmCancelLabel})?(await Ev(),"cleared"):"cancelled"},_k=async()=>{if(!await Xu({host:bf(),title:ht.resetIdentityConfirmTitle,description:ht.resetIdentityConfirm,confirmLabel:ht.resetIdentityConfirmLabel,cancelLabel:ht.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await kv();return{outcome:"reset",remoteRevocationConfirmed:c}},Co=v("button","persona-history-earlier");Co.type="button",Co.textContent=ht.showEarlierMessagesLabel,Co.setAttribute("data-persona-history-earlier",""),Object.assign(Co.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Sr=()=>{if(!(Xo()&&!!fd.nextMessageCursor&&!!$.getActiveConversationId())){Co.remove();return}Co.textContent=ht.showEarlierMessagesLabel,Co.parentNode!==le&&le.insertBefore(Co,le.firstChild)};Co.addEventListener("click",()=>{let i=$.getActiveConversationId(),c=fd.nextMessageCursor;if(!i||!c||Co.disabled)return;Co.disabled=!0;let f=le.scrollHeight,y=le.scrollTop;$.loadOlderMessages(i,c,{scope:Fi()}).then(()=>{le.scrollTop=y+(le.scrollHeight-f),Jn()}).catch(()=>{}).finally(()=>{Co.disabled=!1,Sr()})});let Nk=()=>{let i=si({ariaLabel:ht.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(!(!Xo()||Yb())){if(J){Zn();return}gl({invoker:i.button,keyboard:c.detail===0})}}),i},Pv=()=>{if(!Xo()){Qo?.remove(),Nn=null,Qo=null;return}if(Qo&&!Qo.isConnected&&(Nn=null,Qo=null),!Nn&&ve){let y=Nk();Nn=y.button,Qo=y.wrapper;let x=Qe.clearChatButtonWrapper||Qe.closeButtonWrapper;x?.parentNode&&ve.contains(x)?x.parentNode.insertBefore(Qo,x):ve.appendChild(Qo)}if(!Nn||!Qo)return;let i=Ui()||J&&re==="rail";if(Qo.style.display=i?"none":"",i){document.activeElement===Nn&&Td();return}let c=Yb();Nn.disabled=c,Nn.setAttribute("aria-disabled",c?"true":"false");let f=c?ht.openHistoryBusyLabel:ht.openHistoryLabel;Nn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(Nn.removeAttribute("aria-expanded"),Nn.removeAttribute("aria-controls")):(Nn.setAttribute("aria-expanded",J?"true":"false"),Nn.setAttribute("aria-controls",Qm))},Rd=!1,Fk=()=>{let i=Qe.clearChatButton;if(i){if(Xo()){Rd||(Ym=i.getAttribute("aria-label")??"",Rd=!0),i.setAttribute("aria-label",ht.newConversationLabel),i.removeAttribute("title");return}Rd&&(Rd=!1,Ym&&i.setAttribute("aria-label",Ym))}},Zr=()=>{ht=iy(o.features?.history?.copy),Pv(),fl(),Fk(),Sr()};jt=Zr,ut=i=>{fd=i,kt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),ol(i.sendBlocked||so),Sr()},lt=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(mn.clear(),Bo(),Xn()),yd(i.message),kt?.view.refresh()},ev(),Zr(),De.push(()=>{gd?.(),hd?.(),il+=1,Ed(),kt?.dispose(),kt?.view.destroy(),kt=null}),o.clientToken&&$.initClientSession().then(()=>{if(Xo())return $.reconcileBootConversation({scope:Jm()})}).then(()=>{Sr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ht||o.onSSEEvent)&&$.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),ee(i,c)});let Iv=()=>{let i=o.resume??(z?vr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(i)};w?w.then(i=>{if(i){if(i.metadata&&(H=wy(i.metadata),pe.syncFromMetadata()),i.messages?.length){Ii=!0;try{$.hydrateMessages(i.messages)}finally{Ii=!1}id()}i.artifacts?.length&&$.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),Eb(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Wm=!0,k(),Iv()}):(Eb(_),Iv());let $k=()=>{!ke()||Te||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Bt(!0,"auto")},Vk=(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),NB(x)}}:i:c,vf=()=>{let c=Ae.getInlineMessageFields?.();return c&&c.contentSegments.some(y=>y.kind==="mention")?c.contentSegments:void 0},Ar=!1,Ys=null,Wd=()=>{Ae.value="",Ae.style.height="auto",qo(),bl()},Cf="data-persona-composer-notice",Ki=null;function zk(i){Wc(i),!(ke()||!ft)&&(ft.hasAttribute(Ba)||(ft.setAttribute(Cf,""),ft.setAttribute("role","status"),ft.setAttribute("aria-live","polite"),ft.textContent=i,Ki&&clearTimeout(Ki),Ki=setTimeout(()=>{if(Ki=null,!!ft?.hasAttribute(Cf)&&(ft.removeAttribute(Cf),ft.removeAttribute("role"),ft.removeAttribute("aria-live"),p)){let c=$.getStatus();Wn(ft,wt(c),o.statusIndicator??{},c)}},4e3)))}function qk(){let i=Fe.getState().pendingSubmission;i&&(Si(void 0),Ae&&(Ae.value=i.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),qo()),i.options.selectedModelId&&(Fe.setSelectedModelId(i.options.selectedModelId),$r?.repaint()),i.options.activeModeIds?.length&&_c(i.options.activeModeIds),i.options.quote&&Uo(i.options.quote),Ae?.focus())}let Uk=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},Hv=(i={})=>{let c=(i.overrideText??Ae?.value??"").trim();return i.resolveInlineCommand&&c?(ln?.takeInlineCommand(c)??Promise.resolve(null)).then(f=>Rv(i,c,f)):Rv(i,c,null)},Rv=(i,c,f)=>{if(f?.kind==="action"){Wd(),ln?.clear(),As();return}let y=f?.kind==="server"?f.mentions:null,x=f?.kind==="prompt"?f.sendText:c,P=i.pending?.contentParts,Y=(vt?.hasAttachments()??!1)||(P?.length??0)>0;if(!Ux({text:x,hasAttachments:Y,attachmentsReady:vt?.isReady()??!0,hasMentions:ln?.hasMentions()??!1,hasServerMentions:!!y,inputDisabled:Qr(),sendDisabled:Fs()}))return;let ne=$.isStreaming()?lm():"block";if(ne==="defer-one"&&!i.pending){if(Fe.getState().pendingSubmission){zk("One message is already queued. Edit or remove it first.");return}jk({intent:i,sendText:x,serverMentions:y});return}let te={text:x,mentionRefs:[...ln?.getMentionRefs()??[],...y?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:vf(),options:{...Fe.getState().selectedModelId&&{selectedModelId:Fe.getState().selectedModelId},...Fe.getState().activeModeIds.length>0&&{activeModeIds:[...Fe.getState().activeModeIds]},...Fe.getState().quote&&{quote:{...Fe.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(te.options={...i.pending.options},te.contentSegments=i.pending.contentSegments,te.mentionRefs=[...i.pending.mentionRefs],te.viaVoice=i.pending.viaVoice);let oe=()=>{if(P?.length)return[...P];if(!vt?.hasAttachments())return;let Ot=[...vt.getContentParts()];return te.text&&Ot.push(nr(te.text)),Ot};te.contentParts=oe();let fe=()=>{Rs(),$k();let Ot=ln?.collectForSubmit()??null,Sn=Vk(Ot,y),gn=oe();i.consumeDraft!==!1&&Wd();let rn={selectedModelId:te.options.selectedModelId,activeModeIds:te.options.activeModeIds},On=ne==="interrupt";On&&$.cancel(),$.sendMessage(te.text,{contentParts:gn,mentions:Sn??void 0,contentSegments:te.contentSegments,viaVoice:te.viaVoice,composerOptions:rn,...te.options.quote&&{quote:te.options.quote},...On&&{interrupt:!0}}),vt?.hasAttachments()&&vt.clearAttachments(),Ot&&ln?.clear(),As();let Ct=Fe.getState().activeModeIds,Dn=Ix(Ct,o.composer?.modes);Dn.length!==Ct.length&&_c(Dn),Fe.getState().quote&&Uo(void 0),td(),mm.release(),Io()},Se=o.composer?.onBeforeSend;if(!Se){fe();return}let Re=new AbortController;Ys=Re;let yt=Ot=>{if(Ys=null,Ot.status==="error"){Uk(Ot.error);return}Ot.status==="proceed"&&fe()},Rt=jx(Se,te,Re.signal);if(!(Rt instanceof Promise)){yt(Rt);return}return Fe.setPreparing(!0),Rt.then(yt).finally(()=>Fe.setPreparing(!1))};function jk(i){let c=Fe.getState(),f=vt?.hasAttachments()??!1,y=f?[...vt.getContentParts()]:[];f&&i.sendText&&y.push(nr(i.sendText));let x=Lg({text:i.sendText,contentParts:y.length?y:void 0,mentionRefs:[...ln?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:vf(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Si(x),i.intent.consumeDraft!==!1&&Wd(),f&&vt.clearAttachments(),ln?.clear(),As(),c.quote&&Uo(void 0),td(),mm.release(),Io(),Wc("Message queued. It sends when the response finishes.")}function Kk(){let i=Fe.getState().pendingSubmission;i&&(Si(void 0),Od(i.text,{consumeDraft:!1,pending:i}))}function Gk(i){if(o.messageActions?.showEdit!==!0)return;let c=$.getMessages().find(f=>f.id===i);!c||!Zf(c)||Hs!==i&&(Rs(),Hs=i,Ur=Ox({messageId:i,initialText:c.content,onSave:f=>Yk(i,f),onCancel:()=>Rs()}),mn.delete(i),yo(We,$.getMessages(),Ue),Ur.focus())}function Yk(i,c){let f=Ur;if(Hs=null,Ur=null,f?.destroy(),mn.delete(i),!$.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){yo(We,$.getMessages(),Ue);return}Jn()}function Qk(i){if($.isStreaming())return;let c=Jf($.getMessages(),i);c&&(Rs(),$.resubmitFrom(c,{reason:"retry"})&&Jn())}Nc={regenerate:Qk,edit:Gk,quote:i=>{let f=$.getMessages().find(y=>y.id===i)?.content?.trim();f&&(Uo({text:f,messageId:i}),Ae?.focus())}};let yl=async i=>{if(!Ar){Ar=!0;try{await Hv({resolveInlineCommand:!0,...i})}finally{Ar=!1}}};function Bd(i){Fs()||(Wd(),Od(i,{consumeDraft:!1}))}let Od=(i,c)=>{if(Ar)return;Ar=!0;let f=()=>{Ar=!1};try{let y=Hv({...c,overrideText:i});y instanceof Promise?y.finally(f):f()}catch(y){throw f(),y}},Xk=i=>{if(i.preventDefault(),$.isStreaming()){$.cancel(),tn?.reset(),ae?.update();return}Ar||yl()},Jk=()=>o.features?.composerHistory!==!1,wf={...Kg},xf=!1,bl=()=>{wf={...Kg}},Zk=()=>$.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),e0=i=>{if(!Ae)return;xf=!0,Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),xf=!1;let c=Ae.value.length;Ae.setSelectionRange(c,c)},t0=i=>{xf||(i.isComposing||ln?.handleInput(i.inputType??void 0),bl())},n0=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:$l(Ae)}),o0=i=>{if(Ae&&!Qr()&&!(!i.isComposing&&ln?.handleKeydown(i))){if(Jk()&&(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=$S({direction:i.key==="ArrowUp"?"up":"down",history:Zk(),currentValue:Ae.value,atStart:c,state:wf});if(wf=f.state,f.handled){i.preventDefault(),f.value!==void 0&&e0(f.value);return}}if(ux(i,n0())){if($.isStreaming()){if(i.preventDefault(),lm()==="block"||Ar||Fs())return;bl(),yl();return}if(Ar){i.preventDefault();return}if(Fs()){i.preventDefault();return}bl(),i.preventDefault(),Ne.click()}}},Wv=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(Pe)){if(Ys){Ys.abort(),Ys=null,i.preventDefault(),i.stopImmediatePropagation();return}$.isStreaming()&&($.cancel(),tn?.reset(),ae?.update(),bl(),i.preventDefault(),i.stopImmediatePropagation())}},r0=async i=>{if(o.attachments?.enabled!==!0||!vt||Qr())return;let c=BB(i.clipboardData);c.length!==0&&(i.preventDefault(),await vt.handleFiles(c))},wo=null,Jo=!1,Gi=null,Gt=null,Sf=()=>o.voiceRecognition?.completionBehavior==="review";function Qs(i){ye?.setAttribute("data-state",i),i==="recording"?i0():Ef()}let Bv="--persona-voice-level",Af=.5,Yi=null,Mf=-1,Dd=0,Ov=()=>{let i=[],c=oo??ye?.parentElement??null;return c&&i.push(c),Be&&i.push(Be),i},Tf=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Mf){Mf=c;for(let f of Ov())f.style.setProperty(Bv,String(c))}},s0=()=>{Mf=-1,Dd=0;for(let i of Ov())i.style.removeProperty(Bv)};function i0(){if(Yi!==null)return;if(typeof requestAnimationFrame!="function"){Tf(p?$.getVoiceLevel()??Af:Af);return}let i=()=>{Yi=requestAnimationFrame(i);let c=p?$.getVoiceLevel():null;if(c===null){Tf(Af);return}Dd+=(c-Dd)*.3,Tf(Dd)};Yi=requestAnimationFrame(i)}function Ef(){Yi!==null&&(cancelAnimationFrame(Yi),Yi=null),s0()}let Dv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,_d=(i="user")=>{if(Jo||$.isStreaming())return;let c=Dv();if(!c)return;wo=new c;let f=o.voiceRecognition??{},y=f.pauseDuration??2e3;wo.continuous=f.provider?.browser?.continuous??!0,wo.interimResults=!0,wo.lang=f.provider?.browser?.language??"en-US";let x=Ae.value;wo.onresult=P=>{let Y="",ne="";for(let oe=0;oe<P.results.length;oe++){let fe=P.results[oe],Se=fe[0].transcript;fe.isFinal?Y+=Se+" ":ne=Se}let te=x+Y+ne;Ae.value=te,qo(),Gi&&clearTimeout(Gi),(Y||ne)&&(Gi=window.setTimeout(()=>{if(Ae.value.trim()&&wo&&Jo){if(es(),Sf())return;yl({viaVoice:!0})}},y))},wo.onerror=P=>{P.error!=="no-speech"&&es()},wo.onend=()=>{if(Jo){let P=Ae.value.trim();!Sf()&&P&&P!==x.trim()&&yl({viaVoice:!0}),es()}};try{if(wo.start(),Jo=!0,dt.active=!0,i!=="system"&&(dt.manuallyDeactivated=!1),hr(i),Wo(),Io(),ye){let P=o.voiceRecognition??{};Gt={backgroundColor:ye.style.backgroundColor,color:ye.style.color,borderColor:ye.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??"")||Vn};let Y=P.recordingBackgroundColor,ne=P.recordingIconColor,te=P.recordingBorderColor;if(ye.classList.add("persona-voice-recording"),Qs("recording"),ye.style.backgroundColor=Y??"var(--persona-voice-recording-bg, #ef4444)",ye.style.color=ne??"var(--persona-voice-recording-indicator, #ffffff)",ne){let oe=ye.querySelector("svg");oe&&oe.setAttribute("stroke",ne)}te&&(ye.style.borderColor=te),ye.setAttribute("aria-label","Stop voice recognition")}}catch{es("system")}},es=(i="user")=>{if(Jo){if(Jo=!1,Gi&&(clearTimeout(Gi),Gi=null),wo){try{wo.stop()}catch{}wo=null}if(dt.active=!1,hr(i),Wo(),Io(),ye){if(ye.classList.remove("persona-voice-recording"),Qs("idle"),Gt){ye.style.backgroundColor=Gt.backgroundColor,ye.style.color=Gt.color,ye.style.borderColor=Gt.borderColor;let c=ye.querySelector("svg");c&&c.setAttribute("stroke",Gt.color||"currentColor"),Gt=null}ye.setAttribute("aria-label","Start voice recognition")}}},kf=()=>{if(!ye||Gt)return;let i=o.voiceRecognition??{};Gt={backgroundColor:ye.style.backgroundColor,color:ye.style.color,borderColor:ye.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||Vn}},Lf=(i,c)=>{if(!ye)return;let f=ye.querySelector("svg");f&&f.remove();let y=Gt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||Vn),x=He(i,y,c,1.5);x&&ye.appendChild(x)},Nd=()=>{ye&&ye.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qi=()=>{if(!ye)return;kf();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,f=i.recordingIconColor,y=i.recordingBorderColor;if(Nd(),ye.classList.add("persona-voice-recording"),Qs("recording"),ye.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",ye.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let x=ye.querySelector("svg");x&&x.setAttribute("stroke",f)}y&&(ye.style.borderColor=y),ye.setAttribute("aria-label","Stop voice recognition")},a0=()=>{if(!ye)return;kf();let i=o.voiceRecognition??{},c=$.getVoiceInterruptionMode(),f=i.processingIconName??"loader",y=i.processingIconColor??Gt?.color??"",x=i.processingBackgroundColor??Gt?.backgroundColor??"",P=i.processingBorderColor??Gt?.borderColor??"";Nd(),ye.classList.add("persona-voice-processing"),Qs("processing"),ye.style.backgroundColor=x,ye.style.borderColor=P;let Y=y||"currentColor";ye.style.color=Y,Lf(f,Y),ye.setAttribute("aria-label","Processing voice input"),c==="none"&&(ye.style.cursor="default")},l0=()=>{if(!ye)return;kf();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??Gt?.color??"":Gt?.color??""),P=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Gt?.backgroundColor??""),Y=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Gt?.borderColor??"");Nd(),ye.classList.add("persona-voice-speaking"),Qs("speaking"),ye.style.backgroundColor=P,ye.style.borderColor=Y;let ne=x||"currentColor";ye.style.color=ne,Lf(y,ne);let te=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";ye.setAttribute("aria-label",te),c==="none"&&(ye.style.cursor="default"),c==="barge-in"&&ye.classList.add("persona-voice-recording")},Mr=()=>{ye&&(Nd(),Qs("idle"),Gt&&(ye.style.backgroundColor=Gt.backgroundColor??"",ye.style.color=Gt.color??"",ye.style.borderColor=Gt.borderColor??"",Lf(Gt.iconName,Gt.color||"currentColor"),Gt=null),ye.style.cursor="",ye.setAttribute("aria-label","Start voice recognition"))},Pf=()=>{if(!Qr()){if(o.voiceRecognition?.provider?.type==="runtype"){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(()=>{dt.active=!1,dt.manuallyDeactivated=!0,Wo(),hr("user"),Mr()});return}$.toggleVoice().then(()=>{dt.active=$.isVoiceActive(),dt.manuallyDeactivated=!$.isVoiceActive(),Wo(),hr("user"),$.isVoiceActive()?Qi():Mr()});return}if(Jo){let i=Ae.value.trim();dt.manuallyDeactivated=!0,Wo(),es("user"),i&&!Sf()&&yl()}else dt.manuallyDeactivated=!1,Wo(),_d("user")}};cm=Pf,ye&&De.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Mr()):es("system")});let c0=L.on("assistant:complete",()=>{Fe.getState().pendingSubmission&&setTimeout(()=>{$.isStreaming()||Kk()},0)});De.push(c0);let d0=L.on("assistant:complete",()=>{Ab&&(dt.active||dt.manuallyDeactivated||Ab==="assistant"&&!dt.lastUserMessageWasVoice||setTimeout(()=>{!dt.active&&!dt.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{dt.active=$.isVoiceActive(),hr("auto"),$.isVoiceActive()&&Qi()}):_d("auto"))},600))});De.push(d0);let p0=L.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});De.push(p0);let _v=()=>{Bt(!Te,"user")},nn=null,Fn=null;if(ue&&!ke()){let{instance:i,element:c}=Ch({config:o,plugins:a,onToggle:_v});nn=i,i||(Fn=c)}nn?t.appendChild(nn.element):Fn&&t.appendChild(Fn),nl(),Li(),cd(),Nm(),ol($.isStreaming()),km()||(ro()==="follow"?Gr(!0):nd()),PE(),be&&(!ue||ke()?setTimeout(()=>$s(),0):Te&&setTimeout(()=>$s(),200));let Xs=null,Nv=()=>{Xs&&(Xs.disconnect(),Xs.observe(Be),Xs.observe(Pe))},vl=()=>{if(ke()){Ss(),nl();return}let i=cn(o),c=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640,P=f.innerWidth<=x,Y=y&&P&&ue;try{if(Y){Ms(),ja=Kc();return}let ne=!1;Ve&&(Ve=!1,Ms(),ne=!0);let te=Kc();if(!ne&&te!==ja&&(Ms(),ne=!0),ja=te,ne&&zc(),!ue&&!i){_e.style.height="",_e.style.width="";return}if(!c&&!i){let fe=o?.launcher?.width??o?.launcherWidth??Ir;_e.style.width=fe,_e.style.maxWidth=fe}jc(),lb()}finally{if(Ss(),Dc(),nl(),Te&&ue){let te=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),oe=o.launcher?.sidebarMode??!1,fe=o.launcher?.mobileFullscreen??!0,Se=cn(o)&&fe&&te,Re=oe||fe&&te&&ue||Se;if(Re&&!Yo){let yt=t.getRootNode(),Rt=yt instanceof ShadowRoot?yt.host:t.closest(".persona-host");Rt&&!Go&&(Go=th(Rt,o.launcher?.zIndex??Rn)),Yo=nh(t.ownerDocument)}else Re||(Go?.(),Go=null,Yo?.(),Yo=null)}}};vl();let Fd=t.ownerDocument.defaultView??window;if(Fd.addEventListener("resize",vl),De.push(()=>Fd.removeEventListener("resize",vl)),typeof ResizeObserver<"u"){Xs=new ResizeObserver(()=>{Dc()}),Nv(),De.push(()=>{Xs?.disconnect(),Xs=null});let i=new ResizeObserver(()=>{Md()});i.observe(Pe),De.push(()=>i.disconnect())}Fd.addEventListener("resize",Md),De.push(()=>Fd.removeEventListener("resize",Md)),ao=le.scrollTop;let Fv=ir(le),$v=()=>{let i=le.scrollTop,c=ir(le),f=c<Fv;if(Fv=c,!Fr()){ao=i,Cn();return}let{action:y,nextLastScrollTop:x}=cu({following:io.isFollowing(),currentScrollTop:i,lastScrollTop:ao,nearBottom:Hr(le,fr),userScrollThreshold:TE,isAutoScrolling:Qn||Yc||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ao=x,y==="resume"){od()||Xn();return}y==="pause"&&Xa()};if(le.addEventListener("scroll",$v,{passive:!0}),De.push(()=>le.removeEventListener("scroll",$v)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{DE(),_f(We)});i.observe(We),i.observe(le),De.push(()=>i.disconnect())}let Vv=()=>{Fr()&&io.isFollowing()&&od()&&Xa()},zv=le.ownerDocument;zv.addEventListener("selectionchange",Vv),De.push(()=>{zv.removeEventListener("selectionchange",Vv)});let u0=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),qv=i=>{u0.has(i.key)&&(Ds(),Ly()&&Fr()&&io.isFollowing()&&Xa())},Uv=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ds(),Ly()&&Fr()&&io.isFollowing()&&Xa())};le.addEventListener("keydown",qv),le.addEventListener("focusin",Uv),De.push(()=>{le.removeEventListener("keydown",qv),le.removeEventListener("focusin",Uv)});let jv=i=>{if(i.deltaY!==0&&Ds(),!Fr())return;let c=du({following:io.isFollowing(),deltaY:i.deltaY,nearBottom:Hr(le,fr),resumeWhenNearBottom:!0});c==="pause"?Xa():c==="resume"&&!od()&&Xn()};le.addEventListener("wheel",jv,{passive:!0}),le.addEventListener("touchmove",Ds,{passive:!0}),le.addEventListener("pointerdown",Ds,{passive:!0}),De.push(()=>{le.removeEventListener("touchmove",Ds),le.removeEventListener("pointerdown",Ds)}),De.push(()=>le.removeEventListener("wheel",jv)),un.addEventListener("click",()=>{Bo(),le.scrollTop=le.scrollHeight,ao=le.scrollTop,Xn(),Gr(!0),Cn()}),De.push(()=>un.remove()),De.push(()=>{Lb(),Bo()});let Kv=()=>{N&&(Ls&&(N.removeEventListener("click",Ls),Ls=null),Ie()?(N.style.display="",Ls=()=>{Bt(!1,"user")},N.addEventListener("click",Ls)):N.style.display="none")};Kv(),(()=>{let{clearChatButton:i}=Qe;i&&i.addEventListener("click",()=>{if(Xo()){hf({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}$.clearMessages(),mn.clear(),Xn(),aa(Qe.composerOverlay);try{localStorage.removeItem(Wa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Wa)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),W?.clear&&Zc(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),H={},pe.syncFromMetadata(),vt?.clearAttachments(),td(),Si(void 0),Uo(void 0),Rs(),nt?.clear(),tn?.reset(),ae?.update()})})();let Gv=[["keydown",o0],["input",t0],["input",qo],["input",As],["keyup",As],["paste",r0],["focus",fE]],Yv=i=>{if(i)for(let[c,f]of Gv)St?.addListener(i,c,f)},m0=i=>{if(i)for(let[c,f]of Gv)St?.removeListener(i,c,f)},Qv=()=>{St&&(St.addListener(St.form,"submit",Xk),St.addListener(St.footer,"click",As),Yv(Ae),ye&&St.addListener(ye,"click",Pf))};Qv();let Xv=()=>{ln?.onComposerSwap((i,c)=>{m0(c),Ae=i,St&&(St.input=i),Yv(i),pm(),Hm(),qo()})};Xv();let If=!1;function Jv(){if(!If){If=!0;try{let i=Ae?.value??"",c=Be.ownerDocument??document,f=Ae?c.activeElement===Ae:!1;Ef(),St?.destroy(),St=null,ln?.destroy(),ln=null;let y=null,x=()=>(y=ke()?bu({config:o}):pc({config:o}),y.footer),P=Ny(x)??x();an.replaceComposer(P),Be=an.composer.footer;let Y=y!==null&&P===y.footer;Mi=!Y,ky=Y?y.setSendButtonMode:()=>{},_y(Be),$y(Be),Vy(),zy(),qy(),Xv(),Uy(),um(),jy(),Qv();let ne=ks.indexOf(mr);mr.destroy(),mr=lc(Po),ne>=0&&(ks[ne]=mr),Ae&&(Ae.value=i),qo(),As(),cd(),Li(),ol($.isStreaming()),dt.active&&Qs("recording"),Ms(),Nv(),Ss(),Io(),ad(),f&&Ae?.focus()}finally{If=!1}}}let Cl=t.ownerDocument??document;Cl.addEventListener("keydown",Wv,!0);let Zv=()=>{Am()},eC=()=>{Cl.visibilityState==="hidden"&&Am()};typeof window<"u"&&(window.addEventListener("pagehide",Zv),Cl.addEventListener("visibilitychange",eC),De.push(()=>{window.removeEventListener("pagehide",Zv),Cl.removeEventListener("visibilitychange",eC)}));let tC="persona-attachment-drop-active",wl=0,Hf=()=>{wl=0,Pe.classList.remove(tC)},Xi=()=>o.attachments?.enabled===!0&&vt!==null&&!Qr(),nC=i=>{!Ju(i.dataTransfer)||!Xi()||(wl++,wl===1&&Pe.classList.add(tC))},oC=i=>{!Ju(i.dataTransfer)||!Xi()||(wl--,wl<=0&&Hf())},rC=i=>{!Ju(i.dataTransfer)||!Xi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},sC=i=>{if(!Ju(i.dataTransfer)||!Xi())return;i.preventDefault(),i.stopPropagation(),Hf();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&vt.handleFiles(c)},ts=!0;Pe.addEventListener("dragenter",nC,ts),Pe.addEventListener("dragleave",oC,ts),t.addEventListener("dragover",rC,ts),t.addEventListener("drop",sC,ts);let $d=t.ownerDocument,iC=i=>{Xi()&&i.preventDefault()},aC=i=>{Xi()&&i.preventDefault()};$d.addEventListener("dragover",iC),$d.addEventListener("drop",aC),De.push(()=>{St?.destroy(),St=null,Ef(),jo?.destroy(),jo=null,pr?.destroy(),pr=null,Vr?.destroy(),Vr=null,zr?.destroy(),zr=null,$r=null,am=null,Am(),Qa.destroy(),Ki&&clearTimeout(Ki),Rs(),Ys?.abort(),Ys=null,vt?.destroy(),vt=null,Fe.destroy(),Cl.removeEventListener("keydown",Wv,!0),ln?.destroy()}),De.push(()=>{Pe.removeEventListener("dragenter",nC,ts),Pe.removeEventListener("dragleave",oC,ts),t.removeEventListener("dragover",rC,ts),t.removeEventListener("drop",sC,ts),$d.removeEventListener("dragover",iC),$d.removeEventListener("drop",aC),Hf()}),De.push(()=>{$.cancel()}),nn?De.push(()=>{nn?.destroy()}):Fn&&De.push(()=>{Fn?.remove()});let on={update(i){let c=o.toolCall,f=o.messageActions,y=o.layout?.messages,x=o.colorScheme,P=o.loadingIndicator,Y=o.iterationDisplay,ne=o.features?.showReasoning,te=o.features?.showToolCalls,oe=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,Se=o.features?.streamAnimation?.type,Re=o.features?.history?.enabled===!0,yt=o.features?.history?.provider,Rt=o.getIdentityProof,Ot=o.clientToken,Sn=o.contextMentions;o=dT({...o,features:s},i),s=o.features,o=Zh(o),r(),bm(),Yl(t,o),Ac(t,o),Mc(t,o),Me(),Ro(),o.colorScheme!==x&&cb();let gn=ny.getForInstance(o.plugins);a.length=0,a.push(...gn),lv(),ue=o.launcher?.enabled??!0,xe=o.launcher?.autoExpand??!1,at=o.features?.showReasoning??!0,Ut=o.features?.showToolCalls??!0,Qt=o.features?.scrollToBottom??{};let rn=ro();_t=o.features?.scrollBehavior??{},rn!==ro()&&(Bo(),Xn()),Sb(),Hy(),Cn();let On=Ht;if(Ht=o.features?.showEventStreamToggle??!1,Ht&&!On){if(nt||(me(),$.setSSEEventCallback((ge,pt)=>{o.onSSEEvent?.(ge,pt),ee(ge,pt)})),!xt&&ve){let ge=o.features?.eventStream?.classNames,pt="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"+(ge?.toggleButton?" "+ge.toggleButton:"");xt=v("button",pt),xt.style.width="28px",xt.style.height="28px",xt.style.color=qn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let gt=Ke(Dr.Activity,"18px","currentColor",1.5);gt&&xt.appendChild(gt);let Mt=Qe.clearChatButtonWrapper,Yt=Qe.closeButtonWrapper,Hn=Mt||Yt;Hn&&Hn.parentNode===ve?ve.insertBefore(xt,Hn):ve.appendChild(xt),xt.addEventListener("click",()=>{A?Ai():dm()})}}else!Ht&&On&&(Ai(),xt&&(xt.remove(),xt=null),nt?.clear(),Pt?.destroy(),nt=null,Pt=null,tn?.reset(),tn=null,dn=null);if(o.launcher?.enabled===!1&&nn&&(nn.destroy(),nn=null),o.launcher?.enabled===!1&&Fn&&(Fn.remove(),Fn=null),o.launcher?.enabled!==!1&&!nn&&!Fn){let{instance:ge,element:pt}=Ch({config:o,plugins:a,onToggle:_v});nn=ge,ge||(Fn=pt),t.appendChild(pt)}nn&&nn.update(o),hl(),Je&&o.launcher?.subtitle!==void 0&&(Je.textContent=o.launcher.subtitle);let Ct=o.layout?.header;if(Ct?.layout!==Ee&&ve){let ge=Ct?hu(o,Ct,{showClose:Ie(),onClose:()=>Bt(!1,"user")}):ii({config:o,showClose:Ie(),onClose:()=>Bt(!1,"user")});an.replaceHeader(ge),ve=an.header.element,de=an.header.iconHolder,Oe=an.header.headerTitle,Je=an.header.headerSubtitle,N=an.header.closeButton,Ee=Ct?.layout,hl()}else if(Ct){if(de&&(de.style.display=Ct.showIcon===!1?"none":""),Oe&&(Oe.style.display=Ct.showTitle===!1?"none":""),Je&&(Je.style.display=Ct.showSubtitle===!1?"none":""),N){let ge=Ie()&&Ct.showCloseButton!==!1;N.style.display=ge?"":"none"}if(Qe.clearChatButtonWrapper){let ge=Ct.showClearChat;if(ge!==void 0){Qe.clearChatButtonWrapper.style.display=ge?"":"none";let{closeButtonWrapper:pt}=Qe;pt&&!pt.classList.contains("persona-absolute")&&(ge?pt.classList.remove("persona-ml-auto"):pt.classList.add("persona-ml-auto"))}}}let Zo=o.layout?.showHeader!==!1;ve&&(ve.style.display=Zo?"":"none");let Tr=o.layout?.showFooter!==!1;Be&&(Be.style.display=Tr?"":"none"),Ss(),Cn(),ue!==Ce?ue?Bt(xe,"auto"):(Te=!0,nl()):xe!==F&&Bt(xe,"auto"),F=xe,Ce=ue,vl(),Kv();let Js=JSON.stringify(o.toolCall)!==JSON.stringify(c),K=JSON.stringify(o.messageActions)!==JSON.stringify(f),ze=JSON.stringify(o.layout?.messages)!==JSON.stringify(y),Xe=o.loadingIndicator?.render!==P?.render||o.loadingIndicator?.renderIdle!==P?.renderIdle||o.loadingIndicator?.showBubble!==P?.showBubble,$e=o.iterationDisplay!==Y,wn=(o.features?.showReasoning??!0)!==(ne??!0)||(o.features?.showToolCalls??!0)!==(te??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(Js||K||ze||Xe||$e||wn)&&$&&(Ws++,yo(We,$.getMessages(),Ue));let Lt=o.features?.streamAnimation?.type;if(Lt!==Se&&Lt&&Lt!=="none"){let ge=Cm(Lt,o.features?.streamAnimation?.plugins);ge&&nc(ge,t)}let je=o.launcher??{},Oo=je.headerIconHidden??!1,Zt=o.layout?.header?.showIcon,In=Oo||Zt===!1,xn=je.headerIconName,sn=je.headerIconSize??"48px";if(de){let ge=ve,pt=ge?.querySelector(".persona-flex-col");if(In)de.style.display="none",ge&&pt&&!ge.contains(pt)&&ge.insertBefore(pt,ge.firstChild);else{if(de.style.display="",de.style.height=sn,de.style.width=sn,ge&&pt&&(ge.contains(de)?de.nextSibling!==pt&&(de.remove(),ge.insertBefore(de,pt)):ge.insertBefore(de,pt)),xn){let Mt=parseFloat(sn)||24,Yt=He(xn,Mt*.6,"currentColor",1);Yt?de.replaceChildren(Yt):de.textContent=je.agentIconText??"\u{1F4AC}"}else if(je.iconUrl){let Mt=de.querySelector("img");if(Mt)Mt.src=je.iconUrl,Mt.style.height=sn,Mt.style.width=sn;else{let Yt=document.createElement("img");Yt.src=je.iconUrl,Yt.alt="",Yt.className="persona-rounded-xl persona-object-cover",Yt.style.height=sn,Yt.style.width=sn,de.replaceChildren(Yt)}}else{let Mt=de.querySelector("svg"),Yt=de.querySelector("img");(Mt||Yt)&&de.replaceChildren(),de.textContent=je.agentIconText??"\u{1F4AC}"}let gt=de.querySelector("img");gt&&(gt.style.height=sn,gt.style.width=sn)}}let tt=o.layout?.header?.showTitle,po=o.layout?.header?.showSubtitle;if(Oe&&(Oe.style.display=tt===!1?"none":""),Je&&(Je.style.display=po===!1?"none":""),N){let ge=Ie()&&o.layout?.header?.showCloseButton!==!1;if(N.style.display=ge?"":"none",!ke()){let Mn=je.closeButtonSize??"";N.style.height=Mn,N.style.width=Mn,N.style.minWidth=Mn,N.style.minHeight=Mn}let pt=je.closeButtonPlacement??"inline",{closeButtonWrapper:gt}=Qe,Mt=pt==="top-right",Yt=gt?.classList.contains("persona-absolute");if(gt&&Mt!==Yt)if(gt.remove(),Mt){gt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Mn=ll??Pe;Mn.style.position="relative",Mn.appendChild(gt)}else{let Mn=je.clearChat?.placement??"inline",Tn=je.clearChat?.enabled??!0;gt.className=Tn&&Mn==="inline"?"":"persona-ml-auto",ve&&ve.appendChild(gt)}if(N.style.color=je.closeButtonColor||qn.actionIconColor,je.closeButtonBackgroundColor?(N.style.backgroundColor=je.closeButtonBackgroundColor,N.classList.remove("hover:persona-bg-gray-100")):(N.style.backgroundColor="",N.classList.add("hover:persona-bg-gray-100")),je.closeButtonBorderWidth||je.closeButtonBorderColor){let Mn=je.closeButtonBorderWidth||"0px",Tn=je.closeButtonBorderColor||"transparent";N.style.border=`${Mn} solid ${Tn}`,N.classList.remove("persona-border-none")}else N.style.border="",N.classList.add("persona-border-none");je.closeButtonBorderRadius?(N.style.borderRadius=je.closeButtonBorderRadius,N.classList.remove("persona-rounded-full")):(N.style.borderRadius="",N.classList.add("persona-rounded-full")),je.closeButtonPaddingX?(N.style.paddingLeft=je.closeButtonPaddingX,N.style.paddingRight=je.closeButtonPaddingX):(N.style.paddingLeft="",N.style.paddingRight=""),je.closeButtonPaddingY?(N.style.paddingTop=je.closeButtonPaddingY,N.style.paddingBottom=je.closeButtonPaddingY):(N.style.paddingTop="",N.style.paddingBottom=""),fu(N,je.closeButtonIconName??"x",{iconSize:ke()?hh:void 0,iconText:je.closeButtonIconText??"\xD7"});let Hn=je.closeButtonTooltipText??"Close chat",Do=je.closeButtonShowTooltip??!0;N.setAttribute("aria-label",Hn),gt&&En({anchor:N,trigger:gt,text:()=>N?.getAttribute("aria-label")??Hn,enabled:Do})}let{clearChatButton:it,clearChatButtonWrapper:ot}=Qe;if(it){let ge=je.clearChat??{},pt=ge.enabled??!0,gt=o.layout?.header?.showClearChat,Mt=gt!==void 0?gt:pt,Yt=ge.placement??"inline";if(ot){ot.style.display=Mt?"":"none";let{closeButtonWrapper:Hn}=Qe;!ke()&&Hn&&!Hn.classList.contains("persona-absolute")&&(Mt?Hn.classList.remove("persona-ml-auto"):Hn.classList.add("persona-ml-auto"));let Do=Yt==="top-right",Mn=ot.classList.contains("persona-absolute");if(!ke()&&Do!==Mn&&Mt){if(ot.remove(),Do){ot.className="persona-absolute persona-top-4 persona-z-50",ot.style.right="48px";let tr=ll??Pe;tr.style.position="relative",tr.appendChild(ot)}else{ot.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ot.style.right="";let tr=Qe.closeButtonWrapper;ve&&tr&&tr.parentElement===ve?ve.insertBefore(ot,tr):ve&&ve.appendChild(ot)}let Tn=Qe.closeButtonWrapper;Tn&&!Tn.classList.contains("persona-absolute")&&(Do?Tn.classList.add("persona-ml-auto"):Tn.classList.remove("persona-ml-auto"))}}if(Mt){if(!ke()){let Tn=ge.size??"";it.style.height=Tn,it.style.width=Tn,it.style.minWidth=Tn,it.style.minHeight=Tn}let Hn=ge.iconColor??"";if(it.style.color=Hn||qn.actionIconColor,fu(it,ge.iconName??"refresh-cw",{iconSize:ke()?yh:void 0}),ge.backgroundColor?(it.style.backgroundColor=ge.backgroundColor,it.classList.remove("hover:persona-bg-gray-100")):(it.style.backgroundColor="",it.classList.add("hover:persona-bg-gray-100")),ge.borderWidth||ge.borderColor){let Tn=ge.borderWidth||"0px",tr=ge.borderColor||"transparent";it.style.border=`${Tn} solid ${tr}`,it.classList.remove("persona-border-none")}else it.style.border="",it.classList.add("persona-border-none");ge.borderRadius?(it.style.borderRadius=ge.borderRadius,it.classList.remove("persona-rounded-full")):(it.style.borderRadius="",it.classList.add("persona-rounded-full")),ge.paddingX?(it.style.paddingLeft=ge.paddingX,it.style.paddingRight=ge.paddingX):(it.style.paddingLeft="",it.style.paddingRight=""),ge.paddingY?(it.style.paddingTop=ge.paddingY,it.style.paddingBottom=ge.paddingY):(it.style.paddingTop="",it.style.paddingBottom="");let Do=ge.tooltipText??"Clear chat",Mn=ge.showTooltip??!0;it.setAttribute("aria-label",Do),ot&&En({anchor:it,trigger:ot,text:()=>it?.getAttribute("aria-label")??Do,enabled:Mn})}}let Ft=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ry],At=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Tc.message,Tc.messageAndClick];pe=sy({parsers:Ft,handlers:At,getSessionMetadata:Q,updateSessionMetadata:Z,emit:L.emit,documentRef:typeof document<"u"?document:null}),Ue=qT(o,pe,Et),tk(),$.updateConfig(o),(o.features?.history?.enabled===!0!==Re||o.features?.history?.provider!==yt||o.getIdentityProof!==Rt||o.clientToken!==Ot)&&(Zn({restoreFocus:!1}),ev()),Zr(),Md(),yo(We,$.getMessages(),Ue),Li(),cd(),ZE(),ol($.isStreaming()),Sn!==o.contextMentions&&Jv();let Wt=o.voiceRecognition?.enabled===!0,$t=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Er=o.voiceRecognition?.provider?.type==="runtype";if(Wt&&($t||Er))if(!ye||!oo){let ge=ga(o);if(ge){ye=ge.button,oo=ge.wrapper;let pt=zo&&zo.parentElement===Nr?zo:null;Nr?Nr.insertBefore(oo,pt):Bn?.appendChild(oo),St&&(St.micButton=ye),St?.addListener(ye,"click",Pf),ye.disabled=$.isStreaming()}}else{let ge=o.voiceRecognition??{},pt=o.sendButton??{},gt=ge.iconName??"mic",Mt=ge.iconSize,Yt=parseFloat(Mt??"")||Vn;ye.classList.add(uo),ye.classList.toggle(No,!Mt),ye.style.width=Mt??"",ye.style.height=Mt??"",ye.style.minWidth=Mt??"",ye.style.minHeight=Mt??"";let Hn=ge.iconColor??pt.textColor;ye.innerHTML="";let Do=He(gt,Yt,Hn||"currentColor",1.5);Do?ye.appendChild(Do):ye.textContent="\u{1F3A4}";let Mn=ge.backgroundColor??pt.backgroundColor;Mn?ye.style.backgroundColor=Mn:ye.style.backgroundColor="",Hn?ye.style.color=Hn:ye.style.color="var(--persona-text, #111827)",ge.borderWidth?(ye.style.borderWidth=ge.borderWidth,ye.style.borderStyle="solid"):(ye.style.borderWidth="",ye.style.borderStyle=""),ge.borderColor?ye.style.borderColor=ge.borderColor:ye.style.borderColor="",ge.paddingX?(ye.style.paddingLeft=ge.paddingX,ye.style.paddingRight=ge.paddingX):(ye.style.paddingLeft="",ye.style.paddingRight=""),ge.paddingY?(ye.style.paddingTop=ge.paddingY,ye.style.paddingBottom=ge.paddingY):(ye.style.paddingTop="",ye.style.paddingBottom="");let Tn=ge.tooltipText??"Start voice recognition",tr=ge.showTooltip??!1;ye.setAttribute("aria-label",Tn),oo&&En({anchor:ye,trigger:oo,text:()=>ye?.getAttribute("aria-label")??Tn,enabled:tr}),oo.style.display="",ye.disabled=$.isStreaming()}else ye&&oo&&(oo.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():Jo&&es());if(o.attachments?.enabled===!0){if(!Gn||!Jt){let ge=o.attachments??{};Yn||(Yn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Yn.style.display="none",(Ae.parentElement??Bn).insertBefore(Yn,Ae)),qt||(qt=document.createElement("input"),qt.type="file",qt.accept=(ge.allowedTypes??Pr).join(","),qt.multiple=(ge.maxFiles??4)>1,qt.style.display="none",qt.setAttribute("aria-label","Attach files"),(Ae.parentElement??Bn).insertBefore(qt,Ae)),Gn=v("div","persona-send-button-wrapper"),Jt=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${uo} ${No}`),Jt.type="button",Jt.setAttribute("aria-label",ge.buttonTooltipText??"Attach file");let pt=ge.buttonIconName??"paperclip";Jt.style.fontSize="18px",Jt.style.lineHeight="1";let gt=He(pt,Vn,"currentColor",1.5);gt?Jt.appendChild(gt):Jt.textContent="\u{1F4CE}",Jt.addEventListener("click",Yt=>{Yt.preventDefault(),qt?.click()}),Gn.appendChild(Jt);let Mt=ge.buttonTooltipText??"Attach file";En({anchor:Jt,trigger:Gn,text:()=>Jt?.getAttribute("aria-label")??Mt}),Vo?Vo.append(Gn):Bn.appendChild(Gn),St&&(St.attachmentButton=Jt,St.attachmentInput=qt??void 0,St.attachmentPreviews=Yn??void 0),!vt&&qt&&Yn&&(vt=_l.fromConfig(ge,Ry),vt.setPreviewsContainer(Yn),St?.addListener(qt,"change",async()=>{vt&&qt?.files&&(await vt.handleFileSelect(qt.files),qt.value="")}))}else{Gn.style.display="";let ge=o.attachments??{};qt&&(qt.accept=(ge.allowedTypes??Pr).join(","),qt.multiple=(ge.maxFiles??4)>1),vt&&vt.updateConfig({allowedTypes:ge.allowedTypes,maxFileSize:ge.maxFileSize,maxFiles:ge.maxFiles,adapter:ge.adapter})}if(Pe.querySelector(".persona-attachment-drop-overlay")?.remove(),Pe.appendChild(UT(o.attachments?.dropOverlay)),Jt){let ge=o.attachments??{},pt=ge.buttonTooltipText??"Attach file";Jt.setAttribute("aria-label",pt),Jt.textContent="";let gt=He(ge.buttonIconName??"paperclip",Vn,"currentColor",1.5);gt?Jt.appendChild(gt):Jt.textContent="\u{1F4CE}",Gn&&En({anchor:Jt,trigger:Gn,text:()=>Jt?.getAttribute("aria-label")??pt})}}else Gn&&(Gn.style.display="none"),vt&&vt.clearAttachments(),Pe.querySelector(".persona-attachment-drop-overlay")?.remove();let Vt=o.sendButton??{},Rf=Vt.useIcon??!1,Zs=Vt.iconText??"\u2191",Vd=Vt.iconName,lC=Vt.tooltipText??"Send message",h0=Vt.showTooltip??!1,xl=Vt.size,y0=parseFloat(xl??"")||Cg,zd=Vt.backgroundColor,Sl=Vt.textColor;if(Rf){if(Ne.style.width=xl??"",Ne.style.height=xl??"",Ne.style.minWidth=xl??"",Ne.style.minHeight=xl??"",Ne.style.fontSize="18px",Ne.style.lineHeight="1",Sl?Ne.style.color=Sl:Ne.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!$.isStreaming())if(Ne.innerHTML="",Vd){let ge=parseFloat(Vt.iconSize??"")||Math.round(y0*.5),pt=Sl?.trim()||"currentColor",gt=Vt.iconStrokeWidth??2,Mt=He(Vd,ge,pt,gt),Yt=He(Vt.stopIconName??"square",ge,pt,gt);Mt&&Yt?Ne.appendChild(wg(Mt,Yt)):Mt?Ne.appendChild(Mt):Ne.textContent=Zs}else Ne.textContent=Zs;Ne.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${uo}`,zd?(Ne.style.backgroundColor=zd,Ne.classList.remove("persona-bg-persona-primary")):(Ne.style.backgroundColor="",Ne.classList.add("persona-bg-persona-primary"))}else Ne.textContent=o.copy?.sendButtonLabel??"Send",Ne.style.width="",Ne.style.height="",Ne.style.minWidth="",Ne.style.minHeight="",Ne.style.fontSize="",Ne.style.lineHeight="",Ne.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",zd?(Ne.style.backgroundColor=zd,Ne.classList.remove("persona-bg-persona-accent")):Ne.classList.add("persona-bg-persona-accent"),Sl?Ne.style.color=Sl:Ne.classList.add("persona-text-white");Vt.borderWidth?(Ne.style.borderWidth=Vt.borderWidth,Ne.style.borderStyle="solid"):(Ne.style.borderWidth="",Ne.style.borderStyle=""),Vt.borderColor?Ne.style.borderColor=Vt.borderColor:Ne.style.borderColor="",Vt.paddingX?(Ne.style.paddingLeft=Vt.paddingX,Ne.style.paddingRight=Vt.paddingX):(Ne.style.paddingLeft="",Ne.style.paddingRight=""),Vt.paddingY?(Ne.style.paddingTop=Vt.paddingY,Ne.style.paddingBottom=Vt.paddingY):(Ne.style.paddingTop="",Ne.style.paddingBottom=""),$.isStreaming()||Ne.setAttribute("aria-label",lC),ad(),zo&&En({anchor:Ne,trigger:zo,text:()=>Ne.getAttribute("aria-label")??lC,enabled:h0}),Gy();let cC=Np(Fe.getState().activeModeIds,o.composer?.modes);Fe.setActiveModeIds(cC),wi().length>0!==!!pr&&um(),pr?.render(cC,wi());for(let ge of[...xi.keys()])_p(ge,o.composer?.modeGroups)||xi.delete(ge);xi.forEach(ge=>ge.repaint()),$r?.repaint(),jo?.resolve();let qd=gs(o,ke());if(vm(),qd){We.style.maxWidth=qd,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",Pn.style.maxWidth=qd,Pn.style.marginLeft="auto",Pn.style.marginRight="auto",Pn.style.width="100%";for(let ge of[Bn,Po,Yn,ft])ge&&(ge.style.maxWidth=qd,ge.style.marginLeft="auto",ge.style.marginRight="auto",ge.style.width="100%")}else{We.style.maxWidth="",We.style.marginLeft="",We.style.marginRight="",We.style.width="",Pn.style.maxWidth="",Pn.style.marginLeft="",Pn.style.marginRight="",Pn.style.width="";for(let ge of[Bn,Po,Yn,ft])ge&&(ge.style.maxWidth="",ge.style.marginLeft="",ge.style.marginRight="",ge.style.width="")}let ns=o.statusIndicator??{},b0=ns.visible??!0;if(ft.style.display=b0?"":"none",$){let ge=$.getStatus();Wn(ft,(gt=>gt==="idle"?ns.idleText??hn.idle:gt==="connecting"?ns.connectingText??hn.connecting:gt==="connected"?ns.connectedText??hn.connected:gt==="error"?ns.errorText??hn.error:hn[gt])(ge),ns,ge)}ft.classList.remove("persona-text-left","persona-text-center","persona-text-right");let v0=ns.align==="left"?"persona-text-left":ns.align==="center"?"persona-text-center":"persona-text-right";ft.classList.add(v0),pm(),Hm(),Io(),Le()},open(){Ie()&&Bt(!0,"api")},close(){Ie()&&Bt(!1,"api")},toggle(){Ie()&&Bt(!Te,"api")},reconnect(){$.reconnectNow()},clearChat(){ur=!1,$.clearMessages(),mn.clear(),Xn();try{localStorage.removeItem(Wa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Wa)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),W?.clear&&Zc(()=>W.clear(),"[AgentWidget] Failed to clear storage adapter:"),H={},pe.syncFromMetadata(),vt?.clearAttachments(),td(),Si(void 0),Uo(void 0),Rs(),nt?.clear(),tn?.reset(),ae?.update()},setMessage(i){return!Ae||$.isStreaming()||Qr()?!1:(!Te&&Ie()&&Bt(!0,"system"),Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if($.isStreaming()||Fs())return!1;let c=i?.trim()||Ae.value.trim();return c?(!Te&&Ie()&&Bt(!0,"system"),Ae.value="",Ae.style.height="auto",qo(),Od(c,{consumeDraft:!1}),!0):!1},getComposerState(){return Fe.getState()},setQuote(i){let c=i?.text?.trim();c&&Uo({...i,text:c})},clearQuote(){Uo(void 0)},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!Te&&Ie()&&Bt(!0,"system"),dt.manuallyDeactivated=!1,Wo(),$.toggleVoice().then(()=>{dt.active=$.isVoiceActive(),hr("user"),$.isVoiceActive()&&Qi()})),!0):Jo?!0:Dv()?(!Te&&Ie()&&Bt(!0,"system"),dt.manuallyDeactivated=!1,Wo(),_d("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{dt.active=!1,dt.manuallyDeactivated=!0,Wo(),hr("user"),Mr()}),!0):!1:Jo?(dt.manuallyDeactivated=!0,Wo(),es("user"),!0):!1},injectMessage(i){return!Te&&Ie()&&Bt(!0,"system"),$.injectMessage(i)},injectAssistantMessage(i){!Te&&Ie()&&Bt(!0,"system");let c=$.injectAssistantMessage(i);return bt&&(bt=!1,Ye&&(clearTimeout(Ye),Ye=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),c},injectUserMessage(i){return!Te&&Ie()&&Bt(!0,"system"),$.injectUserMessage(i)},injectSystemMessage(i){return!Te&&Ie()&&Bt(!0,"system"),$.injectSystemMessage(i)},injectMessageBatch(i){return!Te&&Ie()&&Bt(!0,"system"),$.injectMessageBatch(i)},injectComponentDirective(i){return!Te&&Ie()&&Bt(!0,"system"),$.injectComponentDirective(i)},injectTestMessage(i){!Te&&Ie()&&Bt(!0,"system"),$.injectTestEvent(i)},async connectStream(i,c){return $.connectStream(i,c)},__pushEventStreamEvent(i){Ht&&(me(),ee(i.type,i.payload))},showEventStream(){Ht&&dm()},hideEventStream(){A&&Ai()},isEventStreamVisible(){return A},listConversations(i){return $.listConversations(i)},getActiveConversationId(){return $.getActiveConversationId()},openConversation(i,c){return gf(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return hf({focusComposer:i?.focus===!0})},deleteConversation(i){return Tv(i)},renameConversation(i,c){return yf(i,{title:c})},setConversationStarred(i,c){return yf(i,{starred:c})},clearConversationHistory(i){return Ev(i)},resetHistoryIdentity(){return kv()},getHistoryIdentityStatus(){return lo?lo.getIdentityStatus():Xm()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return gl({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Zn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return J},showArtifacts(){jn(o)&&(ur=!1,Ti=!0,Ro(),ct?.setMobileOpen(!0))},hideArtifacts(){jn(o)&&(ur=!0,Ro())},upsertArtifact(i){return jn(o)?(os(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(ur=!1,Ti=!0),$.upsertArtifact(i)):null},selectArtifact(i){jn(o)&&$.selectArtifact(i)},clearArtifacts(){jn(o)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return ue&&!Te&&!ke()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(i,c,f){let x=$.getMessages().find(P=>P.variant==="approval"&&P.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){AE(i)},clearFollowUpSuggestions(){xb()},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...H}},updatePersistentMetadata(i){Z(i)},on(i,c){return L.on(i,c)},off(i,c){L.off(i,c)},isOpen(){return Ie()&&Te},isVoiceActive(){return dt.active},toggleReadAloud(i){$.toggleReadAloud(i)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(i){return $.getReadAloudState(i)},onReadAloudChange(i){return $.onReadAloudChange(i)},getState(){return{open:Ie()&&Te,launcherEnabled:ue,voiceActive:dt.active,streaming:$.isStreaming()}},showCSATFeedback(i){!Te&&Ie()&&Bt(!0,"system");let c=We.querySelector(".persona-feedback-container");c&&c.remove();let f=$T({onSubmit:async(y,x)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});We.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Te&&Ie()&&Bt(!0,"system");let c=We.querySelector(".persona-feedback-container");c&&c.remove();let f=VT({onSubmit:async(y,x)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});We.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(){qm(),zs!=null&&(clearInterval(zs),zs=null),De.forEach(i=>i()),rt.remove(),Xt?.remove(),nn?.destroy(),Fn?.remove(),Ls&&N.removeEventListener("click",Ls)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:on,getMessages:on.getMessages,getStatus:on.getStatus,getMetadata:on.getPersistentMetadata,updateMetadata:on.updatePersistentMetadata,clearHistory:()=>on.clearChat(),setVoiceActive:f=>f?on.startVoiceRecognition():on.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=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&on.focusInput()};if(window.addEventListener("persona:focusInput",c),De.push(()=>{window.removeEventListener("persona:focusInput",c)}),Ht){let oe=Se=>{let Re=Se.detail;(!Re?.instanceId||Re.instanceId===i)&&on.showEventStream()},fe=Se=>{let Re=Se.detail;(!Re?.instanceId||Re.instanceId===i)&&on.hideEventStream()};window.addEventListener("persona:showEventStream",oe),window.addEventListener("persona:hideEventStream",fe),De.push(()=>{window.removeEventListener("persona:showEventStream",oe),window.removeEventListener("persona:hideEventStream",fe)})}let f=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&on.showHistory()},y=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&on.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=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&on.showArtifacts()},P=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&on.hideArtifacts()},Y=oe=>{let fe=oe.detail;fe?.instanceId&&fe.instanceId!==i||fe?.artifact&&on.upsertArtifact(fe.artifact)},ne=oe=>{let fe=oe.detail;fe?.instanceId&&fe.instanceId!==i||typeof fe?.id=="string"&&on.selectArtifact(fe.id)},te=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&on.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",P),window.addEventListener("persona:upsertArtifact",Y),window.addEventListener("persona:selectArtifact",ne),window.addEventListener("persona:clearArtifacts",te),De.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",P),window.removeEventListener("persona:upsertArtifact",Y),window.removeEventListener("persona:selectArtifact",ne),window.removeEventListener("persona:clearArtifacts",te)})}let xo=OB(o.persistState);if(xo&&Ie()){let i=DB(xo.storage),c=`${xo.keyPrefix}widget-open`,f=`${xo.keyPrefix}widget-voice`,y=`${xo.keyPrefix}widget-voice-mode`;if(i){let x=xo.persist?.openState&&i.getItem(c)==="true",P=xo.persist?.voiceState&&i.getItem(f)==="true",Y=xo.persist?.voiceState&&i.getItem(y)==="true";if(x&&(nn?.setPanelOpen(!0,"auto"),setTimeout(()=>{on.open(),setTimeout(()=>{if(P||Y)on.startVoiceRecognition();else if(xo.persist?.focusInput){let ne=t.querySelector("textarea");ne&&ne.focus()}},100)},0)),xo.persist?.openState&&(L.on("widget:opened",()=>{i.setItem(c,"true")}),L.on("widget:closed",()=>{i.setItem(c,"false")})),xo.persist?.voiceState&&(L.on("voice:state",ne=>{i.setItem(f,ne.active?"true":"false")}),L.on("user:message",ne=>{i.setItem(y,ne.viaVoice?"true":"false")})),xo.clearOnChatClear){let ne=()=>{i.removeItem(c),i.removeItem(f),i.removeItem(y)},te=()=>ne();window.addEventListener("persona:clear-chat",te),De.push(()=>{window.removeEventListener("persona:clear-chat",te)})}}}if(X&&Ie()&&(nn?.setPanelOpen(!0,"auto"),setTimeout(()=>{on.open()},0)),Oi(),!ME){let i=Zi(()=>{$&&(Ws++,mn.clear(),yo(We,$.getMessages(),Ue))});De.push(i)}C=()=>{$&&(Ws++,mn.clear(),yo(We,$.getMessages(),Ue))},$.getMessages().length>0&&id(),M=()=>{$&&(Ws++,mn.clear(),yo(We,$.getMessages(),Ue))};let f0=Qw(()=>{$&&(Ws++,mn.clear(),yo(We,$.getMessages(),Ue))});De.push(f0);let g0=Yh(()=>{$&&(Ws++,mn.clear(),yo(We,$.getMessages(),Ue),Wr()?.updateInlineArtifactBlocks(We,ho.artifacts,{suppressTransition:!0}),Ro())});return De.push(g0),on};us();var KT=(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},FB=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},$B=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},VB=(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.")},GT=(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"},My=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=""},YT=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",My(t)},xy=t=>{t.style.transition=""},Sy=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=""},Ay=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Zu=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},zB=(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))},qB=(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)},UB=t=>{let e=va(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:zn(e,r)??r;return{inset:o(n?.inset,eu),canvasBackground:o(n?.canvasBackground,tu)}},QT=(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},jB=(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??"";zB(t,e,n,o,p),qB(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"),Sy(e),xy(o),YT(o),Ay(n),Zu(r,o),QT(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??Rn),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"),YT(o),FB(o,d.maxHeight),QT(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",Sy(e),xy(o),Ay(n),Zu(r,o);let E=d.animate?"transform 180ms ease":"none",O=d.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":O;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=E,o.style.transform=M,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",xy(o),My(o),Zu(r,o);let E=KT(d.width,t.clientWidth),O=Math.max(0,t.clientWidth),M=d.animate?"margin-left 180ms ease":"none",D=d.side==="right"?a?-E:0:a?0:-E;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=`${O+E}px`,e.style.transition=M,e.style.marginLeft=`${D}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${O}px`,n.style.maxWidth=`${O}px`,n.style.minWidth=`${O}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="",Sy(e),My(o),Ay(n),Zu(r,o);let E=d.reveal==="emerge";E?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let O=a?d.width:"0px",M=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",D=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${O}`,o.style.width=O,o.style.maxWidth=O,o.style.minWidth=O,o.style.minHeight="0",$B(o,d.maxHeight),o.style.overflow=E||D?"hidden":"visible",o.style.transition=M,E){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let L=u?`calc(${KT(d.width,t.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=L,r.style.minWidth=L,r.style.maxWidth=L,r.style.boxSizing="border-box"}}},KB=(t,e)=>{let n=t.ownerDocument.createElement("div");return GT(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){GT(n,o)},destroy(){n.remove()}}},GB=(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?UB(e):null};C();let S=()=>{jB(a,l,d,p,u,e,m,b)},I=null,E=()=>{I?.(),I=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(I=nu(()=>{C(),S()}))},O=()=>{g(),ko(e).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{S()}),h.observe(a)))},M=!1,D=()=>{S(),O(),m&&!M&&a.dataset.personaDockMobileFullscreen!=="true"&&(M=!0,VB(a,ko(e)))},L=a.ownerDocument.defaultView,B=()=>{D()};return L?.addEventListener("resize",B),ko(e).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),D(),E(),{mode:"docked",host:u,shell:a,syncWidgetState(W){let z=W.launcherEnabled?W.open:!0;m!==z&&(m=z,D())},updateConfig(W){e=W,(e?.launcher?.enabled??!0)===!1&&(m=!0),C(),D(),E()},destroy(){L?.removeEventListener("resize",B),I?.(),I=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},XT=(t,e)=>cn(e)?GB(t,e):KB(t,e);var Hc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},JT=.15,ZT=1.5,Ty="persona-preview-shell-theme",YB={load:()=>null,save:()=>{},clear:()=>{}},QB=["How do I get started?","Pricing & plans","Talk to support"];function Ey(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function XB(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 eE(t){let e=XB(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}; }
|
|
@@ -1288,7 +1288,7 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1288
1288
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
1289
1289
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
1290
1290
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
1291
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
1291
|
+
.preview-workspace-card.short { height: 96px; }`}function tE(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Ty);o||(o=n.createElement("style"),o.id=Ty,n.head.appendChild(o)),o.textContent=eE(e)}var JB=`
|
|
1292
1292
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
1293
1293
|
<div class="preview-iframe-chrome">
|
|
1294
1294
|
<span class="preview-iframe-dot"></span>
|
|
@@ -1307,7 +1307,7 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1307
1307
|
<div class="preview-iframe-line body"></div>
|
|
1308
1308
|
<div class="preview-iframe-line body"></div>
|
|
1309
1309
|
</div>
|
|
1310
|
-
</div>`,
|
|
1310
|
+
</div>`,ZB=`
|
|
1311
1311
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
1312
1312
|
<div class="preview-iframe-line hero"></div>
|
|
1313
1313
|
<div class="preview-iframe-line body"></div>
|
|
@@ -1320,8 +1320,8 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1320
1320
|
<div class="preview-workspace-card short"></div>
|
|
1321
1321
|
<div class="preview-workspace-card short"></div>
|
|
1322
1322
|
</div>
|
|
1323
|
-
</div>`;function
|
|
1324
|
-
${
|
|
1323
|
+
</div>`;function nE(t,e,n,o){let r=`
|
|
1324
|
+
${JB}
|
|
1325
1325
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
|
|
1326
1326
|
<div class="preview-workspace-shell">
|
|
1327
1327
|
<div class="preview-workspace-topbar">
|
|
@@ -1333,7 +1333,7 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1333
1333
|
</div>
|
|
1334
1334
|
<div class="preview-workspace-body">
|
|
1335
1335
|
<div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
|
|
1336
|
-
${
|
|
1336
|
+
${ZB}
|
|
1337
1337
|
</div>
|
|
1338
1338
|
</div>
|
|
1339
1339
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -1341,16 +1341,16 @@ _Details: ${n.message}_`:o}var ag=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
1341
1341
|
<head>
|
|
1342
1342
|
<meta charset="UTF-8">
|
|
1343
1343
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1344
|
-
<link rel="stylesheet" href="${
|
|
1345
|
-
<style id="${
|
|
1344
|
+
<link rel="stylesheet" href="${Ey(o)}">
|
|
1345
|
+
<style id="${Ty}">${eE(e)}</style>
|
|
1346
1346
|
</head>
|
|
1347
1347
|
<body>
|
|
1348
1348
|
${n?s:r}
|
|
1349
1349
|
</body>
|
|
1350
|
-
</html>`}var
|
|
1351
|
-
${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${
|
|
1350
|
+
</html>`}var e1=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],t1=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function n1(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&t1(e)?[...e1(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function o1(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:QB:t.suggestionChips,initialMessages:n1(e,t,n),storageAdapter:YB};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),e==="messages"&&(r.features={...r.features,history:{presentation:"panel",...r.features?.history,enabled:!0}}),r}function r1(t,e){let n=t.theme?ba(t.theme,{validate:!1}):ba();return{...Tt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Oa(t,e){let n=t.scene??"conversation";return o1(r1(t,e),n,t.appendedMessages??[])}function oE(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Oa(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Oa(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Oa(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Oa(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Oa(t,n),shellMode:n}]}function rE(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,d=1,p=0;function u(){return n.device??"desktop"}function m(){return n.zoom??l}function h(){let E=getComputedStyle(t),O=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),M=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),D=40,L=(n.compareMode??"off")!=="off",B=(t.clientWidth-O-D)/(L?2:1),W=t.clientHeight-M-D;if(B<=0||W<=0)return 1;let z=Hc[u()]??Hc.desktop;return Math.min(B/z.w,W/z.h,1)}function g(){l=h();let E=Math.max(JT,Math.min(ZT,m()));d=E;let O=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let M of O){let D=M.dataset.device??"desktop",L=Hc[D]??Hc.desktop;M.style.width=`${L.w*E}px`,M.style.height=`${L.h*E}px`,D==="mobile"&&(M.style.borderRadius=`${32*E}px`);let B=M.querySelector("iframe");B&&(B.style.width=`${L.w}px`,B.style.height=`${L.h}px`,B.style.transformOrigin="top left",B.style.transition="none",B.style.transform=`scale(${E})`)}n.onScaleChange?.(E)}function b(){n.onBeforeDestroy?.();for(let E of o)E.destroy();for(let E of r)E();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function S(){if(a)return;b();let E=++p,O=oE(n),M=u(),D=(n.compareMode??"off")!=="off",L=(n.scene??"conversation")==="minimized",B=n.widgetCssPath??"/widget-dist/widget.css",W=n.buildSrcdoc??nE,z=M==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",H=j=>`<div class="${z}" data-mount-id="${j.mountId}" data-device="${M}" data-shell-mode="${j.shellMode}">
|
|
1351
|
+
${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${Ey(j.label)}</span></div>`:""}
|
|
1352
1352
|
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${j.mountId}"></iframe>
|
|
1353
|
-
</div>`,w=D?`<div class="preview-compare-grid">${O.map(j=>`<div class="preview-compare-cell">${H(j)}</div>`).join("")}</div>`:`<div class="preview-single">${H(O[0])}</div>`;n.morphContainer?n.morphContainer(t,w):t.innerHTML=w,g();let k=C(),R=0,_=k.length,X=()=>{if(a||E!==p)return;for(let Q of k){let Z=Q.dataset.mountId;if(!Z||!Q.contentDocument)continue;let ie=O.find(be=>be.mountId===Z);if(!ie)continue;let se=()=>{},pe=
|
|
1353
|
+
</div>`,w=D?`<div class="preview-compare-grid">${O.map(j=>`<div class="preview-compare-cell">${H(j)}</div>`).join("")}</div>`:`<div class="preview-single">${H(O[0])}</div>`;n.morphContainer?n.morphContainer(t,w):t.innerHTML=w,g();let k=C(),R=0,_=k.length,X=()=>{if(a||E!==p)return;for(let Q of k){let Z=Q.dataset.mountId;if(!Z||!Q.contentDocument)continue;let ie=O.find(be=>be.mountId===Z);if(!ie)continue;let se=()=>{},pe=cn(ie.config),ue=pe?(()=>{let be=Q.contentDocument?.getElementById(`preview-content-${Z}`);if(!be)return null;let F=XT(be,ie.config),Ce=Q.contentDocument.createElement("div");Ce.id=Z,Ce.style.height="100%",Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1",Ce.style.minHeight="0",F.host.appendChild(Ce);let Ee=()=>F.syncWidgetState(xe.getState()),Ve=se;return se=()=>{F.destroy(),Ve()},Ce.__syncDock=Ee,Ce.__hostLayout=F,Ce})():Q.contentDocument.getElementById(Z);if(!ue)continue;let xe=jT(ue,ie.config);if(o.push(xe),pe&&ue.__syncDock){let be=ue.__syncDock,F=xe.on("widget:opened",be),Ce=xe.on("widget:closed",be),Ee=se;se=()=>{F(),Ce(),Ee()},be()}r.push(se),L&&xe.close()}let j=n.scene??"conversation";if(j==="messages")for(let Q of o)Q.showHistory({focus:!1});if(j==="artifact"||n.config?.features?.artifacts?.enabled)for(let Q of o)Q.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
1354
1354
|
|
|
1355
1355
|
This is a preview of the artifact sidebar.
|
|
1356
1356
|
|
|
@@ -1358,4 +1358,4 @@ This is a preview of the artifact sidebar.
|
|
|
1358
1358
|
|
|
1359
1359
|
- Markdown rendering
|
|
1360
1360
|
- Document toolbar
|
|
1361
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:k,controllers:[...o]})};for(let j of k){let Q=j.dataset.mountId;if(!Q)continue;let Z=O.find(ie=>ie.mountId===Q);Z&&(j.addEventListener("load",()=>{R++,R>=_&&X()},{once:!0}),j.srcdoc=W(Q,Z.shellMode,
|
|
1361
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:k,controllers:[...o]})};for(let j of k){let Q=j.dataset.mountId;if(!Q)continue;let Z=O.find(ie=>ie.mountId===Q);Z&&(j.addEventListener("load",()=>{R++,R>=_&&X()},{once:!0}),j.srcdoc=W(Q,Z.shellMode,cn(Z.config),B))}_===0&&X()}function I(){if(a)return;let E=oE(n);if(o.length!==E.length){S();return}if(E.some(M=>{let D=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${M.mountId}"]`);return!D||D.dataset.shellMode!==M.shellMode})){S();return}o.forEach((M,D)=>{M.update(E[D].config),(n.scene??"conversation")==="minimized"&&M.close()});for(let M of E){let D=t.querySelector(`iframe[data-mount-id="${M.mountId}"]`);D&&tE(D,M.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||g()}),s.observe(t)),S(),{update(E){if(a)return;let O=E.device!==void 0&&E.device!==n.device||E.scene!==void 0&&E.scene!==n.scene||E.compareMode!==void 0&&E.compareMode!==n.compareMode||E.widgetCssPath!==void 0&&E.widgetCssPath!==n.widgetCssPath;n={...n,...E},O?S():I()},destroy(){a||(a=!0,b(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return d},setZoom(E){a||(n={...n,zoom:E},g())}}}0&&(module.exports={createThemePreview});
|