@runtypelabs/persona 4.10.1 → 4.11.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.
Files changed (56) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-Bx_rvjff.d.cts → types-DveIaNx6.d.cts} +2 -0
  4. package/dist/animations/{types-Bx_rvjff.d.ts → types-DveIaNx6.d.ts} +2 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/chunk-MMUPR2JW.js +1 -0
  8. package/dist/codegen.cjs +1 -1
  9. package/dist/codegen.js +1 -1
  10. package/dist/{context-mentions-7S5KVUTG.js → context-mentions-ONG7A7M6.js} +1 -1
  11. package/dist/context-mentions.d.cts +26 -0
  12. package/dist/context-mentions.d.ts +26 -0
  13. package/dist/index.cjs +67 -67
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +27 -1
  16. package/dist/index.d.ts +27 -1
  17. package/dist/index.global.js +55 -55
  18. package/dist/index.global.js.map +1 -1
  19. package/dist/index.js +78 -78
  20. package/dist/index.js.map +1 -1
  21. package/dist/smart-dom-reader.d.cts +26 -0
  22. package/dist/smart-dom-reader.d.ts +26 -0
  23. package/dist/theme-editor-preview.cjs +66 -66
  24. package/dist/theme-editor-preview.d.cts +26 -0
  25. package/dist/theme-editor-preview.d.ts +26 -0
  26. package/dist/theme-editor-preview.js +55 -55
  27. package/dist/theme-editor.cjs +5 -5
  28. package/dist/theme-editor.d.cts +26 -0
  29. package/dist/theme-editor.d.ts +26 -0
  30. package/dist/theme-editor.js +9 -9
  31. package/dist/widget.css +1 -1
  32. package/package.json +1 -1
  33. package/src/components/approval-bubble.ts +0 -1
  34. package/src/components/composer-parts.ts +19 -19
  35. package/src/components/context-mention-button.test.ts +5 -1
  36. package/src/components/context-mention-button.ts +6 -4
  37. package/src/components/header-builder.test.ts +3 -3
  38. package/src/components/header-parts.ts +14 -108
  39. package/src/components/message-bubble.test.ts +49 -0
  40. package/src/components/message-bubble.ts +8 -7
  41. package/src/components/reasoning-bubble.ts +0 -2
  42. package/src/components/tool-bubble.ts +0 -2
  43. package/src/generated/runtype-openapi-contract.ts +2 -0
  44. package/src/index-core.ts +1 -0
  45. package/src/styles/widget.css +118 -58
  46. package/src/theme-editor/sections.test.ts +33 -0
  47. package/src/theme-editor/sections.ts +10 -1
  48. package/src/types.ts +25 -0
  49. package/src/ui.attachments-drop.test.ts +2 -1
  50. package/src/ui.message-width.test.ts +407 -0
  51. package/src/ui.ts +145 -238
  52. package/src/utils/table-scroll-fade.test.ts +123 -0
  53. package/src/utils/table-scroll-fade.ts +75 -0
  54. package/src/utils/tooltip.test.ts +226 -0
  55. package/src/utils/tooltip.ts +245 -0
  56. package/dist/chunk-IPVK3KOM.js +0 -1
@@ -1,34 +1,34 @@
1
- import{a as jc}from"./chunk-5EIIHQLQ.js";import{a as m,b as Tn,c as Uc,d as De,e as Bn,f as ne,g as Kc,i as Gc,j as Qc}from"./chunk-IPVK3KOM.js";import{a as qc,b as Vc}from"./chunk-IO5VVUKP.js";var Xo=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:qy,load:Sf,provide:Vy,getSync:Li}=Xo({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),Qs=new Set,Tf=()=>{let t=[...Qs];Qs.clear();for(let e of t)try{e()}catch{}};var Mf=()=>{let t=Li();return t?Promise.resolve(t):Sf().then(e=>(Tf(),e))},Xs=t=>Li()?()=>{}:(Qs.add(t),Mf().catch(()=>{}),()=>{Qs.delete(t)});var Hn=Li;var Ef=t=>{if(t)return t},Pi=t=>{let e=null;return n=>{let o=Hn();if(!o)return Zn(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=Ef(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Js=t=>t?Pi({markedOptions:t.options,renderer:t.renderer}):Pi(),Qy=Pi();var Zn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var kf={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"]},Lf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pf=()=>{let t=null;return e=>{let n=Hn();if(!n)return Zn(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:")&&!Lf.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,kf)}},Ys=t=>t===!1?null:typeof t=="function"?t:Pf();var Xc=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Jc=t=>t.includes("|"),Yc=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())},If=t=>`| ${t.join(" | ")} |`,Rf=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Wf=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Zc=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
2
- `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Jc(r)||Xc.test(r)||!Xc.test(s))continue;let a=Yc(r).length;if(a<1)continue;let l=Rf(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let p=o+2;for(;p<e.length;p++){let d=e[p];if(d.trim()===""||!Jc(d))break;let c=If(Wf(Yc(d),a));e[p]!==c&&(e[p]=c,n=!0)}o=p-1}return n?e.join(`
3
- `):t};var Dn="webmcp:",Ii=new Map,ed=t=>{Ii.clear();for(let e of t){let n=e.title?.trim();n&&Ii.set(e.name,n)}},jr=t=>Ii.get(rd(t)),Zs={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},td=null;function od(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}:${Bf(e.join(""))}`}function nd(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 Bf(t){let e=nd(t,0).toString(36),n=nd(t,2654435761).toString(36);return`${e}.${n}`}var ea=class{constructor(e){this.config=e;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 Zs.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}ed(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=Df(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return wn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return wn(v?"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=rd(e),a;try{a=await r.getTools()}catch(v){let C=v instanceof Error?v.message:String(v);return wn(`Failed to read WebMCP registry: ${C}`)}ed(a);let l=a.find(v=>v.name===s);if(!l)return wn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return wn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return wn("Aborted by cancel()");let p=jr(s),d={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return wn("User declined the tool call.");if(o?.aborted)return wn("Aborted by cancel()");let c=new AbortController,u=!1,w=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let v=await r.executeTool(l,_f(n),{signal:c.signal});return Nf(v)}catch(v){if(u)return wn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return wn("Aborted by cancel()");let C=v instanceof Error?v.message:String(v);return wn(C)}finally{clearTimeout(w),o&&o.removeEventListener("abort",f)}}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}(td?await td():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Zs.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,Zs.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??Ff;try{return await n(e)}catch(o){return Zs.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=>Hf(e,o))}},rd=t=>t.startsWith(Dn)?t.slice(Dn.length):t,Jo=t=>t.startsWith(Dn),Hf=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Df=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Nf=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:$f(e)}]}},wn=t=>({isError:!0,content:[{type:"text",text:t}]}),Ff=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=Of(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
1
+ import{a as qc}from"./chunk-5EIIHQLQ.js";import{a as h,b as jc,c as Ne,d as Wn,e as re,f as Gc,h as Qc,i as Xc}from"./chunk-MMUPR2JW.js";import{a as Vc,b as Kc}from"./chunk-IO5VVUKP.js";var Vo=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:eb,load:Pf,provide:tb,getSync:Mi}=Vo({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),qs=new Set,If=()=>{let t=[...qs];qs.clear();for(let e of t)try{e()}catch{}};var Rf=()=>{let t=Mi();return t?Promise.resolve(t):Pf().then(e=>(If(),e))},Vs=t=>Mi()?()=>{}:(qs.add(t),Rf().catch(()=>{}),()=>{qs.delete(t)});var Hn=Mi;var Wf=t=>{if(t)return t},Ei=t=>{let e=null;return n=>{let o=Hn();if(!o)return Zn(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=Wf(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Ks=t=>t?Ei({markedOptions:t.options,renderer:t.renderer}):Ei(),rb=Ei();var Zn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Hf={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"]},Bf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Df=()=>{let t=null;return e=>{let n=Hn();if(!n)return Zn(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:")&&!Bf.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Hf)}},Gs=t=>t===!1?null:typeof t=="function"?t:Df();var Jc=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Yc=t=>t.includes("|"),Zc=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())},Ff=t=>`| ${t.join(" | ")} |`,Nf=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Of=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),ed=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
2
+ `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Yc(r)||Jc.test(r)||!Jc.test(s))continue;let a=Zc(r).length;if(a<1)continue;let l=Nf(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let p=o+2;for(;p<e.length;p++){let d=e[p];if(d.trim()===""||!Yc(d))break;let c=Ff(Of(Zc(d),a));e[p]!==c&&(e[p]=c,n=!0)}o=p-1}return n?e.join(`
3
+ `):t};var td="var(--persona-md-table-scroll-fade, 24px)",nd=new WeakSet;function rd(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 od(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":td),t.style.setProperty("--persona-fade-r",r<=1?"0px":td)}function ki(t){nd.has(t)||(nd.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&od(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(od)}var Bn="webmcp:",Li=new Map,sd=t=>{Li.clear();for(let e of t){let n=e.title?.trim();n&&Li.set(e.name,n)}},Nr=t=>Li.get(cd(t)),Qs={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},ad=null;function ld(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}:${_f(e.join(""))}`}function id(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 _f(t){let e=id(t,0).toString(36),n=id(t,2654435761).toString(36);return`${e}.${n}`}var Xs=class{constructor(e){this.config=e;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 Qs.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}sd(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=zf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return vn(v?"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=cd(e),a;try{a=await r.getTools()}catch(v){let C=v instanceof Error?v.message:String(v);return vn(`Failed to read WebMCP registry: ${C}`)}sd(a);let l=a.find(v=>v.name===s);if(!l)return vn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return vn("Aborted by cancel()");let p=Nr(s),d={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return vn("User declined the tool call.");if(o?.aborted)return vn("Aborted by cancel()");let c=new AbortController,u=!1,w=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let v=await r.executeTool(l,Vf(n),{signal:c.signal});return Uf(v)}catch(v){if(u)return vn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return vn("Aborted by cancel()");let C=v instanceof Error?v.message:String(v);return vn(C)}finally{clearTimeout(w),o&&o.removeEventListener("abort",f)}}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}(ad?await ad():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Qs.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,Qs.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??jf;try{return await n(e)}catch(o){return Qs.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=>$f(e,o))}},cd=t=>t.startsWith(Bn)?t.slice(Bn.length):t,Ko=t=>t.startsWith(Bn),$f=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},zf=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Uf=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:Kf(e)}]}},vn=t=>({isError:!0,content:[{type:"text",text:t}]}),jf=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=qf(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
4
4
 
5
5
  Arguments:
6
6
  ${e}`:"")+(t.description?`
7
7
 
8
- ${t.description}`:"");return window.confirm(n)},Of=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)}},_f=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},$f=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function ko(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function ta(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}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var zf="agent_",Uf="flow_";function sd(t){return t.startsWith(zf)?{kind:"agentId",agentId:t}:t.startsWith(Uf)?{kind:"flowId",flowId:t}:null}function ad(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 d=sd(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[a];if(!p)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:p(l).payload}}let r=sd(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.`)}import{parse as jf,ARR as qf,OBJ as Vf,STR as Kf}from"partial-json";var Ri="ask_user_question",qr=8,Yo="data-persona-ask-sheet-for",Gf="Other",Qf="Other\u2026",ld="Type your own answer here",cd="Send",Xf="Next",Jf="Back",Yf="Submit all",Zf="Skip",eg=3,Wi="data-ask-current-index",Bi="data-ask-question-count",dd="data-ask-answers",Hi="data-ask-grouped",pd="data-ask-layout",tg=t=>t.layout==="pills"?"pills":"rows",ng=t=>t.getAttribute(pd)==="pills"?"pills":"rows",id=!1,ud=t=>t.replace(/["\\]/g,"\\$&"),Lo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Ri,Di=t=>t?.features?.askUserQuestion??{},Zo=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=jf(r,Kf|Vf|qf);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Vr=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>qr&&!id&&(id=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${qr}.`)),e.slice(0,qr)},og=t=>Vr(t)[0]??null,rg=(t,e)=>Vr(t)[e]??null,sg=(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))},fd=(t,e,n)=>{if(t!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},ag=(t,e,n,o)=>{let s=m("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=m("span","persona-ask-row-content"),l=m("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let d=m("span","persona-ask-row-description");d.textContent=t.description,a.appendChild(d)}s.appendChild(a);let p=fd(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},ig=t=>{let n=m("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},lg=(t,e,n,o)=>{let s=m("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,p=(Array.isArray(t?.options)?t.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<eg;c++)s.appendChild(ig(o));return s}if(p.forEach((c,u)=>{s.appendChild(ag(c,u,o,a))}),t?.allowFreeText!==!1){let c=o==="rows"?Gf:Qf;if(o==="rows"){let u=m("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let w=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=e.freeTextPlaceholder??ld,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let v=fd(o,a,p.length);v&&u.appendChild(v),s.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??c,s.appendChild(u)}}return s},gd=(t,e)=>{let o=m("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??ld,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??cd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},cg=t=>{let e=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??cd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},dg=(t,e,n)=>{let o=m("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=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Jf,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Zf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=m("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??Yf:n.nextLabel??Xf,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Po=t=>{let e=t.getAttribute(dd);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},md=(t,e)=>{t.setAttribute(dd,JSON.stringify(e))},pn=t=>{let e=Number(t.getAttribute(Wi)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},pg=(t,e)=>{t.setAttribute(Wi,String(Math.max(0,Math.floor(e))))},er=t=>{let e=Number(t.getAttribute(Bi)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},eo=t=>t.getAttribute(Hi)==="true",ug=(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},fg=(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)))},na=(t,e)=>{let{payload:n}=Zo(e),o=Vr(n),r=Po(t),s={},a=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},hd=t=>{let e=Po(t),n=pn(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.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="")},yd=t=>{if(!eo(t))return;let e=Po(t),n=pn(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}},Ni=(t,e,n)=>{let o=Di(n),r=ng(t),{payload:s,complete:a}=Zo(e),l=eo(t),p=pn(t),d=er(t),c=l?rg(s,p):og(s),u=!!c?.multiSelect,w=t.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=t.querySelector('[data-ask-question="true"]');if(v){let E=typeof c?.question=="string"?c.question:"";v.textContent=E,v.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let E=lg(c,o,a,r);C.replaceWith(E)}if(r!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(gd(o,r))}let P=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!P?t.appendChild(cg(o)):(!u||l)&&P&&P.remove(),t.setAttribute("data-multi-select",u?"true":"false");let H=t.querySelector('[data-ask-nav-row="true"]');if(l){let E=dg(p,d,o);H?H.replaceWith(E):t.appendChild(E)}else H&&H.remove();hd(t),yd(t)},gg=(t,e,n)=>{let o=Di(e),r=tg(o),s=t.toolCall.id,a=Vr(n),l=Math.max(1,a.length),p=l>1,d=ug(t,a),c=p?fg(t,l):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Yo,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(Bi,String(l)),u.setAttribute(Wi,String(c)),u.setAttribute(Hi,p?"true":"false"),u.setAttribute(pd,r),md(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),sg(u,o);let w=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",w.appendChild(f);let v=m("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),u.appendChild(w);let P=m("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 P.setAttribute("data-ask-pill-list","true"),P.setAttribute("role","group"),u.appendChild(P),r!=="rows"&&u.appendChild(gd(o,r)),Ni(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},mg=(t,e,n)=>{let{payload:o}=Zo(e),r=Math.max(1,Vr(o).length);r>er(t)&&(t.setAttribute(Bi,String(r)),r>1&&!eo(t)&&t.setAttribute(Hi,"true")),Ni(t,e,n)};var oa=(t,e,n)=>{if(!n||!Lo(t)||Di(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Yo}]`).forEach(d=>{d.getAttribute(Yo)!==r&&d.remove()});let a=n.querySelector(`[${Yo}="${ud(r)}"]`);if(a){mg(a,t,e);return}let{payload:l}=Zo(t),p=gg(t,e,l);n.appendChild(p)},tr=(t,e)=>{if(!t)return;let n=e?`[${Yo}="${ud(e)}"]`:`[${Yo}]`;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)})},Fi=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),to=(t,e)=>{let n=Po(t),o=pn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,md(t,n),hd(t),yd(t)},ra=(t,e,n,o)=>{let r=er(t),s=Math.max(0,Math.min(r-1,o));pg(t,s),Ni(t,e,n)};var Nn="suggest_replies";var hg={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:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},bd={name:Nn,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. Each suggestion is sent verbatim as the user's next message, so phrase suggestions 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:hg,origin:"sdk",annotations:{readOnlyHint:!0}},Oi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),_i=t=>t.variant==="tool"&&t.toolCall?.name===Nn,yg=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.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);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},vd=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!_i(n))continue;let o=yg(n.toolCall?.args);return o.length>0?o:null}return null},wd=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var bg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:qr,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},vg={name:Ri,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:bg,origin:"sdk",annotations:{readOnlyHint:!0}},sa=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(vg),wd(t)&&e.push(bd),e};import{parse as wg,STR as xg,OBJ as Cg}from"partial-json";var xd=t=>t.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),no=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)}},Ag=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`},Cd=t=>t.status==="complete"?Ag(t):t.status==="pending"?"Waiting":"",Sg=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`};var Ad=t=>t.status==="complete"?Sg(t):"Using tool...",aa=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Gr=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 aa(e)},ia=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return aa(e)},$i=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Gr(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},la=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Kr(o,n.slice(s,a.index),[]),a[1]!==void 0?Kr(o,a[1],["bold"]):a[2]!==void 0?Kr(o,a[2],["italic"]):a[3]!==void 0&&Kr(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Kr(o,n.slice(s),[]),o},Kr=(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})},Tg=()=>{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
+ ${t.description}`:"");return window.confirm(n)},qf=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)}},Vf=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Kf=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function So(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function Js(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}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Gf="agent_",Qf="flow_";function dd(t){return t.startsWith(Gf)?{kind:"agentId",agentId:t}:t.startsWith(Qf)?{kind:"flowId",flowId:t}:null}function pd(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 d=dd(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[a];if(!p)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:p(l).payload}}let r=dd(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.`)}import{parse as Xf,ARR as Jf,OBJ as Yf,STR as Zf}from"partial-json";var Pi="ask_user_question",Or=8,Go="data-persona-ask-sheet-for",eg="Other",tg="Other\u2026",fd="Type your own answer here",gd="Send",ng="Next",og="Back",rg="Submit all",sg="Skip",ag=3,Ii="data-ask-current-index",Ri="data-ask-question-count",md="data-ask-answers",Wi="data-ask-grouped",hd="data-ask-layout",ig=t=>t.layout==="pills"?"pills":"rows",lg=t=>t.getAttribute(hd)==="pills"?"pills":"rows",ud=!1,yd=t=>t.replace(/["\\]/g,"\\$&"),To=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Pi,Hi=t=>t?.features?.askUserQuestion??{},Qo=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=Xf(r,Zf|Yf|Jf);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},_r=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Or&&!ud&&(ud=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Or}.`)),e.slice(0,Or)},cg=t=>_r(t)[0]??null,dg=(t,e)=>_r(t)[e]??null,pg=(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))},bd=(t,e,n)=>{if(t!=="rows")return null;let o=h("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=h("span","persona-ask-row-check");o.appendChild(r)}else{let r=h("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},ug=(t,e,n,o)=>{let s=h("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=h("span","persona-ask-row-content"),l=h("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let d=h("span","persona-ask-row-description");d.textContent=t.description,a.appendChild(d)}s.appendChild(a);let p=bd(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},fg=t=>{let n=h("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},gg=(t,e,n,o)=>{let s=h("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,p=(Array.isArray(t?.options)?t.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<ag;c++)s.appendChild(fg(o));return s}if(p.forEach((c,u)=>{s.appendChild(ug(c,u,o,a))}),t?.allowFreeText!==!1){let c=o==="rows"?eg:tg;if(o==="rows"){let u=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let w=h("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=e.freeTextPlaceholder??fd,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let v=bd(o,a,p.length);v&&u.appendChild(v),s.appendChild(u)}else{let u=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??c,s.appendChild(u)}}return s},vd=(t,e)=>{let o=h("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??fd,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=h("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??gd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},mg=t=>{let e=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??gd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},hg=(t,e,n)=>{let o=h("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=h("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??og,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??sg,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=h("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??rg:n.nextLabel??ng,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Mo=t=>{let e=t.getAttribute(md);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},wd=(t,e)=>{t.setAttribute(md,JSON.stringify(e))},dn=t=>{let e=Number(t.getAttribute(Ii)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},yg=(t,e)=>{t.setAttribute(Ii,String(Math.max(0,Math.floor(e))))},Xo=t=>{let e=Number(t.getAttribute(Ri)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},eo=t=>t.getAttribute(Wi)==="true",bg=(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},vg=(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)))},Ys=(t,e)=>{let{payload:n}=Qo(e),o=_r(n),r=Mo(t),s={},a=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},xd=t=>{let e=Mo(t),n=dn(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.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="")},Cd=t=>{if(!eo(t))return;let e=Mo(t),n=dn(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}},Bi=(t,e,n)=>{let o=Hi(n),r=lg(t),{payload:s,complete:a}=Qo(e),l=eo(t),p=dn(t),d=Xo(t),c=l?dg(s,p):cg(s),u=!!c?.multiSelect,w=t.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=t.querySelector('[data-ask-question="true"]');if(v){let k=typeof c?.question=="string"?c.question:"";v.textContent=k,v.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let k=gg(c,o,a,r);C.replaceWith(k)}if(r!=="rows"){let k=t.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(vd(o,r))}let I=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!I?t.appendChild(mg(o)):(!u||l)&&I&&I.remove(),t.setAttribute("data-multi-select",u?"true":"false");let B=t.querySelector('[data-ask-nav-row="true"]');if(l){let k=hg(p,d,o);B?B.replaceWith(k):t.appendChild(k)}else B&&B.remove();xd(t),Cd(t)},wg=(t,e,n)=>{let o=Hi(e),r=ig(o),s=t.toolCall.id,a=_r(n),l=Math.max(1,a.length),p=l>1,d=bg(t,a),c=p?vg(t,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Go,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(Ri,String(l)),u.setAttribute(Ii,String(c)),u.setAttribute(Wi,p?"true":"false"),u.setAttribute(hd,r),wd(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),pg(u,o);let w=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=h("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",w.appendChild(f);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),u.appendChild(w);let I=h("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 I.setAttribute("data-ask-pill-list","true"),I.setAttribute("role","group"),u.appendChild(I),r!=="rows"&&u.appendChild(vd(o,r)),Bi(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},xg=(t,e,n)=>{let{payload:o}=Qo(e),r=Math.max(1,_r(o).length);r>Xo(t)&&(t.setAttribute(Ri,String(r)),r>1&&!eo(t)&&t.setAttribute(Wi,"true")),Bi(t,e,n)};var Zs=(t,e,n)=>{if(!n||!To(t)||Hi(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Go}]`).forEach(d=>{d.getAttribute(Go)!==r&&d.remove()});let a=n.querySelector(`[${Go}="${yd(r)}"]`);if(a){xg(a,t,e);return}let{payload:l}=Qo(t),p=wg(t,e,l);n.appendChild(p)},Jo=(t,e)=>{if(!t)return;let n=e?`[${Go}="${yd(e)}"]`:`[${Go}]`;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)})},Di=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),to=(t,e)=>{let n=Mo(t),o=dn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,wd(t,n),xd(t),Cd(t)},ea=(t,e,n,o)=>{let r=Xo(t),s=Math.max(0,Math.min(r-1,o));yg(t,s),Bi(t,e,n)};var Dn="suggest_replies";var Cg={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:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Ad={name:Dn,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. Each suggestion is sent verbatim as the user's next message, so phrase suggestions 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:Cg,origin:"sdk",annotations:{readOnlyHint:!0}},Fi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ni=t=>t.variant==="tool"&&t.toolCall?.name===Dn,Ag=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.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);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},Sd=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Ni(n))continue;let o=Ag(n.toolCall?.args);return o.length>0?o:null}return null},Td=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var Sg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Or,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},Tg={name:Pi,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:Sg,origin:"sdk",annotations:{readOnlyHint:!0}},ta=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Tg),Td(t)&&e.push(Ad),e};import{parse as Mg,STR as Eg,OBJ as kg}from"partial-json";var Md=t=>t.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),no=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)}},Lg=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`},Ed=t=>t.status==="complete"?Lg(t):t.status==="pending"?"Waiting":"",Pg=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`};var kd=t=>t.status==="complete"?Pg(t):"Using tool...",na=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},zr=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 na(e)},oa=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return na(e)},Oi=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=zr(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ra=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&$r(o,n.slice(s,a.index),[]),a[1]!==void 0?$r(o,a[1],["bold"]):a[2]!==void 0?$r(o,a[2],["italic"]):a[3]!==void 0&&$r(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&$r(o,n.slice(s),[]),o},$r=(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})},Ig=()=>{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,`
10
10
  `).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,`
11
- `).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()=>{}}},Qr=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Sd=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Td=()=>{let t=Tg();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)}},Md=()=>{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=wg(n,xg|Cg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?xd(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=xd(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Ed=()=>{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}};var kd="4.10.1";var Xr=kd;var Eg="https://api.runtype.com/v1/dispatch",ca="https://api.runtype.com";function kg(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 zi=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 Lg(t){switch(t){case"json":return Md;case"regex-json":return Td;case"xml":return Ed;default:return Sd}}var Ld=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Pg(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=Ld(n);if(!Ld(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Qr(t);return Qr(e)!==null&&a===null?e:t}var Jr=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=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??Eg,this.headers={"Content-Type":"application/json","X-Persona-Version":Xr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??Lg(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new ea(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}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=ad(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)}getClientApiUrl(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ca}/v1/client/${e}`}getClientSession(){return this.clientSession}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}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xr},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ca}/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":Xr},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})}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){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:e.messages.filter(zi).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xr},body:JSON.stringify(c),signal:e.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);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);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 r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ca}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,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?od(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,c=!1,u;for(let w=0;;w++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&w===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ca}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,w=>{let f={...p,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:l,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}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(zi).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(e);return a&&(r.context=a),r}async buildPayload(e){let n=e.slice().filter(zi).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(e);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}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 p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);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)),p(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}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="",p=Date.now(),d=0,c=()=>p+d++,u=M=>{let F=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,y=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,A=M.tools?M.tools.map(k=>({...k,chunks:k.chunks?[...k.chunks]:void 0})):void 0;return{...M,reasoning:F,toolCall:y,tools:A}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let F=Array.isArray(M.contentParts)&&M.contentParts.length>0,y=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||F||y||!!M.stopReason},f=M=>{w(M)&&n({type:"message",message:u(M)})},v=null,C=null,P={current:null},H={current:null},E=null,T="",I=new Map,z=new Map,N=new Map,x=new Map,j=new Map,q={lastId:null,byStep:new Map},J={lastId:null,byCall:new Map},D=M=>{if(M==null)return null;try{return String(M)}catch{return null}},$=M=>D(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),fe=M=>D(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ye=o,Le=!1,Ce=()=>{if(v)return v;let M,F="",y=E;return!Le&&ye?(M=ye,Le=!0,F=r??""):ye&&y?M=`${ye}_${y}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:F,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(v),v},te=(M,F)=>{q.lastId=F,M&&q.byStep.set(M,F)},ge=(M,F)=>{let y=M.reasoningId??M.id,A=$(M);if(y){let W=String(y);return te(A,W),W}if(A){let W=q.byStep.get(A);if(W)return q.lastId=W,W}if(q.lastId&&!F)return q.lastId;if(!F)return null;let k=`reason-${c()}`;return te(A,k),k},Y=M=>{let F=x.get(M);if(F)return F;let y={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return x.set(M,y),f(y),y},ae=(M,F)=>{J.lastId=F,M&&J.byCall.set(M,F)},Z=new Set,ve=new Map,we=new Set,ue=new Map,Te=M=>{if(!M)return!1;let F=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return F==="emit_artifact_markdown"||F==="emit_artifact_component"},Ae=(M,F)=>{let y=M.toolId??M.id,A=fe(M);if(y){let W=String(y);return ae(A,W),W}if(A){let W=J.byCall.get(A);if(W)return J.lastId=W,W}if(J.lastId&&!F)return J.lastId;if(!F)return null;let k=`tool-${c()}`;return ae(A,k),k},ze=M=>{let F=j.get(M);if(F)return F;let y={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return j.set(M,y),f(y),y},Ne=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let F=Number(M);if(!Number.isNaN(F)&&Number.isFinite(F))return F;let y=Date.parse(M);if(!Number.isNaN(y))return y}return Date.now()},it=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},Je=new Map,Re=new Map,Me=new Map,Ye=(M,F,y)=>{let A=Me.get(M);A||(A=[],Me.set(M,A));let k=0,W=A.length;for(;k<W;){let B=k+W>>>1;A[B].seq<F?k=B+1:W=B}A[k]?.seq===F?A[k]={seq:F,text:y}:A.splice(k,0,{seq:F,text:y});let V="";for(let B=0;B<A.length;B++)V+=A[B].text;return V},sn=(M,F)=>{let y=it(F),A=Re.get(M.id),k=Pg(A,y);M.rawContent=k;let W=Je.get(M.id),V=Ee=>{let lt=M.content??"";Ee.trim()!==""&&(lt.trim().length===0||Ee.startsWith(lt)||Ee.trimStart().startsWith(lt.trim()))&&(M.content=Ee)},B=()=>{if(W){let Ee=W.close?.();Ee instanceof Promise&&Ee.catch(()=>{})}Je.delete(M.id),Re.delete(M.id),M.streaming=!1,f(M)};if(!W){V(y),B();return}let U=Qr(k);if(U!==null&&U.trim()!==""){V(U),B();return}let oe=Ee=>{let lt=typeof Ee=="string"?Ee:Ee?.text??null;if(lt!==null&&lt.trim()!=="")return lt;let K=W.getExtractedText();return K!==null&&K.trim()!==""?K:y},Ke;try{Ke=W.processChunk(k)}catch{V(y),B();return}if(Ke instanceof Promise){Ke.then(Ee=>{V(oe(Ee)),B()}).catch(()=>{V(y),B()});return}V(oe(Ke)),B()},Mt=null,yt=(M,F,y,A)=>{M.rawContent=F,Je.has(M.id)||Je.set(M.id,this.createStreamParser());let k=Je.get(M.id),W=F.trim().startsWith("{")||F.trim().startsWith("[");if(W&&Re.set(M.id,F),k.__isPlainTextParser===!0){M.content=A!==void 0?F:M.content+y,Re.delete(M.id),Je.delete(M.id),M.rawContent=void 0,f(M);return}let B=k.processChunk(F);if(B instanceof Promise)B.then(U=>{let oe=typeof U=="string"?U:U?.text??null;oe!==null&&oe.trim()!==""?(M.content=oe,f(M)):!W&&!F.trim().startsWith("<")&&(M.content=A!==void 0?F:M.content+y,Re.delete(M.id),Je.delete(M.id),M.rawContent=void 0,f(M))}).catch(()=>{M.content=A!==void 0?F:M.content+y,Re.delete(M.id),Je.delete(M.id),M.rawContent=void 0,f(M)});else{let U=typeof B=="string"?B:B?.text??null;U!==null&&U.trim()!==""?(M.content=U,f(M)):!W&&!F.trim().startsWith("<")&&(M.content=A!==void 0?F:M.content+y,Re.delete(M.id),Je.delete(M.id),M.rawContent=void 0,f(M))}},We=(M,F)=>{let y=F??M.content;if(y==null||y===""){M.streaming=!1,f(M);return}let k=Re.get(M.id)??it(y);M.rawContent=k;let W=Je.get(M.id),V=null,B=!1;if(W&&(V=W.getExtractedText(),V===null&&(V=Qr(k)),V===null)){let U=W.processChunk(k);U instanceof Promise?(B=!0,U.then(oe=>{let Ke=typeof oe=="string"?oe:oe?.text??null;Ke!==null&&(M.content=Ke,M.streaming=!1,Je.delete(M.id),Re.delete(M.id),f(M))}).catch(()=>{})):V=typeof U=="string"?U:U?.text??null}if(!B){V!==null&&V.trim()!==""?M.content=V:Re.has(M.id)||(M.content=it(y));let U=Je.get(M.id);if(U){let oe=U.close?.();oe instanceof Promise&&oe.catch(()=>{}),Je.delete(M.id)}Re.delete(M.id),M.streaming=!1,f(M)}},me=(M,F,y)=>{let A=z.get(M);if(A)return A;let k={id:`nested-${F}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:F}};return z.set(M,k),f(k),k},Qe=[],Pe,pe=new Map,ie=0,be="agent",bt=!1,he=null,de=null,fn=new Map,X=this.config.iterationDisplay??"separate";for(Pe=()=>{for(let M=0;M<Qe.length;M++){let F=Qe[M].payloadType,y=Qe[M].payload;if(!bt&&be!=="flow"&&typeof y.stepType=="string"&&(be="flow"),F==="reasoning_start"){let A=typeof y.id=="string"?y.id:null,k=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(A&&k){I.set(A,k),me(A,k,"reasoning");continue}let W=ge(y,!0)??`reason-${c()}`,V=Y(W);V.reasoning=V.reasoning??{id:W,status:"streaming",chunks:[]},V.reasoning.startedAt=V.reasoning.startedAt??Ne(y.startedAt??y.timestamp),V.reasoning.completedAt=void 0,V.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(V.reasoning.scope=y.scope),V.streaming=!0,V.reasoning.status="streaming",f(V)}else if(F==="reasoning_delta"){let A=typeof y.id=="string"?y.id:null;if(A&&I.has(A)&&z.has(A)){let B=z.get(A),U=y.reasoningText??y.text??y.delta??"";U&&y.hidden!==!0&&B.reasoning&&(B.reasoning.chunks.push(String(U)),f(B));continue}let k=ge(y,!1)??ge(y,!0)??`reason-${c()}`,W=Y(k);W.reasoning=W.reasoning??{id:k,status:"streaming",chunks:[]},W.reasoning.startedAt=W.reasoning.startedAt??Ne(y.startedAt??y.timestamp);let V=y.reasoningText??y.text??y.delta??"";if(V&&y.hidden!==!0){let B=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(B!==void 0){let U=Ye(k,B,String(V));W.reasoning.chunks=[U]}else W.reasoning.chunks.push(String(V))}if(W.reasoning.status=y.done?"complete":"streaming",y.done){W.reasoning.completedAt=Ne(y.completedAt??y.timestamp);let B=W.reasoning.startedAt??Date.now();W.reasoning.durationMs=Math.max(0,(W.reasoning.completedAt??Date.now())-B)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(F==="reasoning_complete"){let A=typeof y.id=="string"?y.id:null;if(A&&I.has(A)&&z.has(A)){let U=z.get(A);if(U.reasoning){let oe=typeof y.text=="string"?y.text:"";oe&&U.reasoning.chunks.length===0&&U.reasoning.chunks.push(oe),U.reasoning.status="complete",U.streaming=!1,f(U)}I.delete(A),z.delete(A);continue}let k=ge(y,!1)??ge(y,!0)??`reason-${c()}`,W=typeof y.text=="string"?y.text:"";!x.get(k)&&(W||y.scope==="loop")&&Y(k);let V=x.get(k);if(V?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(V.reasoning.scope=y.scope),W&&V.reasoning.chunks.length===0&&V.reasoning.chunks.push(W),V.reasoning.status="complete",V.reasoning.completedAt=Ne(y.completedAt??y.timestamp);let U=V.reasoning.startedAt??Date.now();V.reasoning.durationMs=Math.max(0,(V.reasoning.completedAt??Date.now())-U),V.streaming=!1,f(V)}let B=$(y);B&&q.byStep.delete(B)}else if(F==="tool_start"){v&&(v.streaming=!1,f(v),v=null),typeof y.iteration=="number"&&(ie=y.iteration);let A=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??Ae(y,!0)??`tool-${c()}`,k=y.toolName??y.name;if(Te(k)){Z.add(A);continue}ae(fe(y),A);let W=ze(A),V=W.toolCall??{id:A,status:"pending"};V.name=k??V.name,V.status="running",y.parameters!==void 0?V.args=y.parameters:y.args!==void 0&&(V.args=y.args),V.startedAt=V.startedAt??Ne(y.startedAt??y.timestamp),V.completedAt=void 0,V.durationMs=void 0,W.toolCall=V,W.streaming=!0,y.executionId&&(W.agentMetadata={executionId:y.executionId,iteration:y.iteration}),f(W)}else if(F==="tool_output_delta"){let A=Ae(y,!1)??Ae(y,!0)??`tool-${c()}`;if(Z.has(A))continue;let k=ze(A),W=k.toolCall??{id:A,status:"running"};W.startedAt=W.startedAt??Ne(y.startedAt??y.timestamp);let V=y.text??y.delta??y.message??"";V&&(W.chunks=W.chunks??[],W.chunks.push(String(V))),W.status="running",k.toolCall=W,k.streaming=!0;let B=y.agentContext;(B||y.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??y.executionId,iteration:B?.iteration??y.iteration}),f(k)}else if(F==="tool_complete"){let A=Ae(y,!1)??Ae(y,!0)??`tool-${c()}`;if(Z.has(A)){Z.delete(A);continue}let k=ze(A),W=k.toolCall??{id:A,status:"running"};W.status="complete",y.result!==void 0&&(W.result=y.result),typeof y.duration=="number"&&(W.duration=y.duration),W.completedAt=Ne(y.completedAt??y.timestamp);let V=y.duration??y.executionTime;if(typeof V=="number")W.durationMs=V;else{let oe=W.startedAt??Date.now();W.durationMs=Math.max(0,(W.completedAt??Date.now())-oe)}k.toolCall=W,k.streaming=!1;let B=y.agentContext;(B||y.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??y.executionId,iteration:B?.iteration??y.iteration}),f(k);let U=fe(y);U&&J.byCall.delete(U)}else if(F==="await"&&y.toolName){let A=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,k=A??y.toolId??`local-${c()}`,W=ze(k),V=y.toolName,B=y.origin==="webmcp"&&!Jo(V)?`webmcp:${V}`:V,U=Jo(B),oe=W.toolCall??{id:k,status:"pending"};oe.name=B,oe.args=y.parameters,oe.status=U?"running":"complete",oe.chunks=oe.chunks??[],oe.startedAt=oe.startedAt??Ne(y.startedAt??y.timestamp??y.awaitedAt),U?(oe.completedAt=void 0,oe.duration=void 0,oe.durationMs=void 0):oe.completedAt=oe.completedAt??oe.startedAt,W.toolCall=oe,W.streaming=!1,W.agentMetadata={...W.agentMetadata,executionId:y.executionId??W.agentMetadata?.executionId,awaitingLocalTool:!0,...A?{webMcpToolCallId:A}:{}},f(W)}else if(F==="text_start"){let A=typeof y.id=="string"?y.id:null,k=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(A&&k){I.set(A,k);continue}let W=v;W&&(be==="flow"?(We(W),Mt=W):(W.streaming=!1,f(W)),v=null),E=typeof y.id=="string"?y.id:E,T=""}else if(F==="text_delta"){let A=typeof y.id=="string"?y.id:null,k=A?I.get(A):void 0;if(A&&k){let V=typeof y.delta=="string"?y.delta:"",B=(N.get(A)??"")+V;if(N.set(A,B),B.trim()==="")continue;let U=me(A,k);U.agentMetadata={...U.agentMetadata,executionId:y.executionId,parentToolId:k},yt(U,B,V,void 0);continue}if(E=typeof y.id=="string"?y.id:E,be==="flow"){let V=typeof y.delta=="string"?y.delta:"";if(T+=V,T.trim()==="")continue;let B=Ce();B.agentMetadata={executionId:y.executionId,iteration:y.iteration},yt(B,T,V,void 0),C=B;continue}let W=Ce();W.content+=y.delta??"",W.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:he??void 0,agentName:de?.agentName},C=W,f(W)}else if(F==="text_complete"){let A=typeof y.id=="string"?y.id:null;if(A&&I.has(A)){let W=z.get(A);W&&We(W),I.delete(A),N.delete(A),z.delete(A);continue}let k=v;k&&(be==="flow"?(We(k),Mt=k):((k.content??"")===""&&typeof y.text=="string"&&(k.content=y.text),k.streaming=!1,f(k)),v=null),E=null,T=""}else if(F==="step_complete"){let A=y.stepType,k=y.executionType;if(A==="tool"||k==="context")continue;if(y.success===!1){let W=y.error,V=typeof W=="string"&&W!==""?W:W!=null&&typeof W=="object"&&Reflect.has(W,"message")?String(W.message??"Step failed"):"Step failed";n({type:"error",error:new Error(V)});let B=v;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"});continue}{let W=Mt;Mt=null;let V=y.stopReason,B=y.result?.response;if(W)V&&(W.stopReason=V),B!=null?sn(W,B):W.streaming!==!1&&(Je.delete(W.id),Re.delete(W.id),W.streaming=!1,f(W));else{let U=B!=null&&B!=="";if(U||V){let oe=Ce();V&&(oe.stopReason=V),U?We(oe,B):(oe.streaming=!1,f(oe))}}continue}}else if(F==="execution_start")be=y.kind==="flow"?"flow":"agent",bt=!0,be==="agent"&&(de={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Ne(y.startedAt)});else if(F==="turn_start"){let A=typeof y.iteration=="number"?y.iteration:ie;if(A!==ie){if(de&&(de.currentIteration=A),X==="separate"&&A>1){let k=v;k&&(k.streaming=!1,f(k),fn.set(A-1,k),v=null)}ie=A}he=typeof y.id=="string"?y.id:null,C=null}else if(F==="tool_input_delta"){let A=y.toolCallId??J.lastId;if(A){let k=j.get(A);k?.toolCall&&(k.toolCall.chunks=k.toolCall.chunks??[],k.toolCall.chunks.push(y.delta??""),f(k))}}else{if(F==="tool_input_complete")continue;if(F==="turn_complete"){let A=y.stopReason,k=v??C;if(A&&k!==null){let W=y.id;(!W||k.agentMetadata?.turnId===W)&&(k.stopReason=A,f(k))}he===y.id&&(he=null)}else if(F==="media_start"){let A=String(y.id);pe.set(A,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(F==="media_delta"){let A=pe.get(String(y.id));A&&typeof y.delta=="string"&&A.parts.push(y.delta)}else if(F==="media_complete"){let A=String(y.id),k=pe.get(A);pe.delete(A);let W=(typeof y.mediaType=="string"?y.mediaType:void 0)??k?.mediaType??"application/octet-stream",V=typeof y.data=="string"?y.data:void 0,B=typeof y.url=="string"?y.url:k&&k.parts.length>0?k.parts.join(""):void 0,U=null;if(V)U={type:"media",data:V,mediaType:W};else if(B){let lt=W.toLowerCase();U={type:lt==="image"||lt.startsWith("image/")?"image-url":"file-url",url:B,mediaType:W}}let oe=y.toolCallId??k?.toolCallId,Ke=U?[U]:[],Ee=[];for(let lt of Ke){if(!lt||typeof lt!="object")continue;let K=lt,_e=typeof K.type=="string"?K.type:void 0,ke=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",Be=null,Ie="";if(_e==="media"){let Ze=typeof K.data=="string"?K.data:void 0;if(!Ze)continue;Ie=ke.length>0?ke:"application/octet-stream",Be=`data:${Ie};base64,${Ze}`}else if(_e==="image-url"){let Ze=typeof K.url=="string"?K.url:void 0;if(!Ze)continue;Ie=ke,Be=Ze}else if(_e==="file-url"){let Ze=typeof K.url=="string"?K.url:void 0;if(!Ze)continue;Ie=ke,Be=Ze}else continue;if(Be)if(_e==="image-url"||Ie.startsWith("image/"))Ee.push({type:"image",image:Be,...Ie.includes("/")?{mimeType:Ie}:{}});else if(Ie.startsWith("audio/"))Ee.push({type:"audio",audio:Be,mimeType:Ie});else if(Ie.startsWith("video/"))Ee.push({type:"video",video:Be,mimeType:Ie});else{let Ze=Ie||"application/octet-stream";Ee.push({type:"file",data:Be,mimeType:Ze,filename:kg(Ze)})}}if(Ee.length>0){let lt=c(),K=oe,ke={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${lt}`:String(lt)}`,role:"assistant",content:"",contentParts:Ee,createdAt:new Date().toISOString(),streaming:!1,sequence:lt,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:ie}};f(ke);let Be=v;Be&&(Be.streaming=!1,f(Be)),v=null,P.current=null}}else if(F==="execution_complete"){let A=y.kind??be;A==="agent"&&de&&(de.status=y.success?"complete":"error",de.completedAt=Ne(y.completedAt),de.stopReason=y.stopReason);let k=v;k&&(A==="flow"&&k.streaming!==!1?We(k):(k.streaming=!1,f(k)),v=null),E=null,T="",Mt=null,n({type:"status",status:"idle",terminal:!0})}else if(F==="execution_error"){let A=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(A)})}else if(F!=="ping"){if(F==="approval_start"){let A=y.approvalId??`approval-${c()}`,k={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:"pending",agentId:de?.agentId??"virtual",executionId:y.executionId??de?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(k)}else if(F==="step_await"&&y.awaitReason==="approval_required"){let A=y.approvalId??`approval-${c()}`,k={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:"pending",agentId:de?.agentId??"virtual",executionId:y.executionId??de?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(k)}else if(F==="approval_complete"){let A=y.approvalId;if(A){let W={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:y.decision??"approved",agentId:de?.agentId??"virtual",executionId:y.executionId??de?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};f(W)}}else if(F==="artifact_start"||F==="artifact_delta"||F==="artifact_update"||F==="artifact_complete"){if(F==="artifact_start"){let A=y.artifactType,k=String(y.id),W=typeof y.title=="string"?y.title:void 0,V=y.file,B;V&&typeof V=="object"&&!Array.isArray(V)&&typeof V.path=="string"&&typeof V.mimeType=="string"&&(B={path:V.path,mimeType:V.mimeType,...typeof V.language=="string"?{language:V.language}:{}}),n({type:"artifact_start",id:k,artifactType:A,title:W,component:typeof y.component=="string"?y.component:void 0,...B?{file:B}:{}});let U=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(ue.set(k,{markdown:"",title:W,file:B,...U?{props:U}:{}}),!we.has(k)){we.add(k);let oe=ko(this.config.features?.artifacts,A),Ke=typeof y.component=="string"?y.component:void 0,Ee={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ta(oe,{artifactId:k,title:W,artifactType:A,status:"streaming",...B?{file:B}:{},...Ke?{component:Ke}:{}})};ve.set(k,Ee),f(Ee)}}else if(F==="artifact_delta"){let A=String(y.id),k=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:A,artDelta:k});let W=ue.get(A);W&&(W.markdown+=k)}else if(F==="artifact_update"){let A=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:A,component:typeof y.component=="string"?y.component:void 0});let k=ue.get(String(y.id));k&&(k.props={...k.props??{},...A})}else if(F==="artifact_complete"){let A=String(y.id);n({type:"artifact_complete",id:A});let k=ve.get(A);if(k){k.streaming=!1;try{let W=JSON.parse(k.rawContent??"{}");if(W.props){W.props.status="complete";let V=ue.get(A);V?.markdown&&(W.props.markdown=V.markdown),V?.file&&(W.props.file=V.file),W.component==="PersonaArtifactInline"&&V?.props&&Object.keys(V.props).length>0&&(W.props.componentProps=V.props)}k.rawContent=JSON.stringify(W)}catch{}ue.delete(A),f(k),ve.delete(A)}}}else if(F==="transcript_insert"){let A=y.message;if(!A||typeof A!="object")continue;let k=String(A.id??`msg-${c()}`),W=A.role,B={id:k,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof A.content=="string"?A.content:"",rawContent:typeof A.rawContent=="string"?A.rawContent:void 0,createdAt:typeof A.createdAt=="string"?A.createdAt:new Date().toISOString(),streaming:A.streaming===!0,...typeof A.variant=="string"?{variant:A.variant}:{},sequence:c()};if(f(B),B.rawContent)try{let oe=JSON.parse(B.rawContent)?.props?.artifactId;typeof oe=="string"&&we.add(oe)}catch{}v=null,P.current=null,Je.delete(k),Re.delete(k)}else if(F==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let A=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(A)});let k=v;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}else if(F==="step_error"||F==="dispatch_error"||F==="flow_error"){let A=null;if(y.error instanceof Error)A=y.error;else if(F==="dispatch_error"){let k=y.message??y.error;k!=null&&k!==""&&(A=new Error(String(k)))}else{let k=y.error;typeof k=="string"&&k!==""?A=new Error(k):k!=null&&typeof k=="object"&&Reflect.has(k,"message")&&(A=new Error(String(k.message??k)))}if(A){n({type:"error",error:A});let k=v;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}Qe.length=0};;){let{done:M,value:F}=await s.read();if(M)break;l+=a.decode(F,{stream:!0});let y=l.split(`
11
+ `).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()=>{}}},Ur=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Ld=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Pd=()=>{let t=Ig();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)}},Id=()=>{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=Mg(n,Eg|kg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?Md(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=Md(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Rd=()=>{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}};var Wd="4.11.0";var jr=Wd;var Wg="https://api.runtype.com/v1/dispatch",sa="https://api.runtype.com";function Hg(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 _i=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 Bg(t){switch(t){case"json":return Id;case"regex-json":return Pd;case"xml":return Rd;default:return Ld}}var Hd=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Dg(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=Hd(n);if(!Hd(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Ur(t);return Ur(e)!==null&&a===null?e:t}var qr=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=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??Wg,this.headers={"Content-Type":"application/json","X-Persona-Version":jr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??Bg(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new Xs(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}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=pd(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)}getClientApiUrl(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||sa}/v1/client/${e}`}getClientSession(){return this.clientSession}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}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":jr},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||sa}/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":jr},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})}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){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:e.messages.filter(_i).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":jr},body:JSON.stringify(c),signal:e.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);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);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 r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||sa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,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?ld(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,c=!1,u;for(let w=0;;w++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&w===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||sa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ta(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,w=>{let f={...p,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:l,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}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(_i).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ta(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(e);return a&&(r.context=a),r}async buildPayload(e){let n=e.slice().filter(_i).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...ta(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(e);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}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 p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);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)),p(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}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="",p=Date.now(),d=0,c=()=>p+d++,u=T=>{let O=T.reasoning?{...T.reasoning,chunks:[...T.reasoning.chunks]}:void 0,y=T.toolCall?{...T.toolCall,chunks:T.toolCall.chunks?[...T.toolCall.chunks]:void 0}:void 0,S=T.tools?T.tools.map(E=>({...E,chunks:E.chunks?[...E.chunks]:void 0})):void 0;return{...T,reasoning:O,toolCall:y,tools:S}},w=T=>{if(T.role!=="assistant"||T.variant)return!0;let O=Array.isArray(T.contentParts)&&T.contentParts.length>0,y=typeof T.rawContent=="string"&&T.rawContent.trim()!=="";return typeof T.content=="string"&&T.content.trim()!==""||O||y||!!T.stopReason},f=T=>{w(T)&&n({type:"message",message:u(T)})},v=null,C=null,I={current:null},B={current:null},k=null,M="",P=new Map,z=new Map,K=new Map,x=new Map,U=new Map,j={lastId:null,byStep:new Map},J={lastId:null,byCall:new Map},D=T=>{if(T==null)return null;try{return String(T)}catch{return null}},F=T=>D(T.stepId??T.step_id??T.step??T.parentId??T.flowStepId??T.flow_step_id),ie=T=>D(T.callId??T.call_id??T.requestId??T.request_id??T.toolCallId??T.tool_call_id??T.stepId??T.step_id),ge=o,Ce=!1,we=()=>{if(v)return v;let T,O="",y=k;return!Ce&&ge?(T=ge,Ce=!0,O=r??""):ge&&y?T=`${ge}_${y}`:T=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:T,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(v),v},ee=(T,O)=>{j.lastId=O,T&&j.byStep.set(T,O)},ce=(T,O)=>{let y=T.reasoningId??T.id,S=F(T);if(y){let W=String(y);return ee(S,W),W}if(S){let W=j.byStep.get(S);if(W)return j.lastId=W,W}if(j.lastId&&!O)return j.lastId;if(!O)return null;let E=`reason-${c()}`;return ee(S,E),E},Y=T=>{let O=x.get(T);if(O)return O;let y={id:`reason-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"streaming",chunks:[]}};return x.set(T,y),f(y),y},ae=(T,O)=>{J.lastId=O,T&&J.byCall.set(T,O)},Z=new Set,he=new Map,ye=new Set,pe=new Map,Te=T=>{if(!T)return!1;let O=T.replace(/_+/g,"_").replace(/^_|_$/g,"");return O==="emit_artifact_markdown"||O==="emit_artifact_component"},Ae=(T,O)=>{let y=T.toolId??T.id,S=ie(T);if(y){let W=String(y);return ae(S,W),W}if(S){let W=J.byCall.get(S);if(W)return J.lastId=W,W}if(J.lastId&&!O)return J.lastId;if(!O)return null;let E=`tool-${c()}`;return ae(S,E),E},Oe=T=>{let O=U.get(T);if(O)return O;let y={id:`tool-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:T,status:"pending"}};return U.set(T,y),f(y),y},Fe=T=>{if(typeof T=="number"&&Number.isFinite(T))return T;if(typeof T=="string"){let O=Number(T);if(!Number.isNaN(O)&&Number.isFinite(O))return O;let y=Date.parse(T);if(!Number.isNaN(y))return y}return Date.now()},ot=T=>{if(typeof T=="string")return T;if(T==null)return"";try{return JSON.stringify(T)}catch{return String(T)}},Ge=new Map,Ie=new Map,Me=new Map,Qe=(T,O,y)=>{let S=Me.get(T);S||(S=[],Me.set(T,S));let E=0,W=S.length;for(;E<W;){let H=E+W>>>1;S[H].seq<O?E=H+1:W=H}S[E]?.seq===O?S[E]={seq:O,text:y}:S.splice(E,0,{seq:O,text:y});let q="";for(let H=0;H<S.length;H++)q+=S[H].text;return q},on=(T,O)=>{let y=ot(O),S=Ie.get(T.id),E=Dg(S,y);T.rawContent=E;let W=Ge.get(T.id),q=Ee=>{let rt=T.content??"";Ee.trim()!==""&&(rt.trim().length===0||Ee.startsWith(rt)||Ee.trimStart().startsWith(rt.trim()))&&(T.content=Ee)},H=()=>{if(W){let Ee=W.close?.();Ee instanceof Promise&&Ee.catch(()=>{})}Ge.delete(T.id),Ie.delete(T.id),T.streaming=!1,f(T)};if(!W){q(y),H();return}let $=Ur(E);if($!==null&&$.trim()!==""){q($),H();return}let se=Ee=>{let rt=typeof Ee=="string"?Ee:Ee?.text??null;if(rt!==null&&rt.trim()!=="")return rt;let V=W.getExtractedText();return V!==null&&V.trim()!==""?V:y},je;try{je=W.processChunk(E)}catch{q(y),H();return}if(je instanceof Promise){je.then(Ee=>{q(se(Ee)),H()}).catch(()=>{q(y),H()});return}q(se(je)),H()},Tt=null,yt=(T,O,y,S)=>{T.rawContent=O,Ge.has(T.id)||Ge.set(T.id,this.createStreamParser());let E=Ge.get(T.id),W=O.trim().startsWith("{")||O.trim().startsWith("[");if(W&&Ie.set(T.id,O),E.__isPlainTextParser===!0){T.content=S!==void 0?O:T.content+y,Ie.delete(T.id),Ge.delete(T.id),T.rawContent=void 0,f(T);return}let H=E.processChunk(O);if(H instanceof Promise)H.then($=>{let se=typeof $=="string"?$:$?.text??null;se!==null&&se.trim()!==""?(T.content=se,f(T)):!W&&!O.trim().startsWith("<")&&(T.content=S!==void 0?O:T.content+y,Ie.delete(T.id),Ge.delete(T.id),T.rawContent=void 0,f(T))}).catch(()=>{T.content=S!==void 0?O:T.content+y,Ie.delete(T.id),Ge.delete(T.id),T.rawContent=void 0,f(T)});else{let $=typeof H=="string"?H:H?.text??null;$!==null&&$.trim()!==""?(T.content=$,f(T)):!W&&!O.trim().startsWith("<")&&(T.content=S!==void 0?O:T.content+y,Ie.delete(T.id),Ge.delete(T.id),T.rawContent=void 0,f(T))}},Re=(T,O)=>{let y=O??T.content;if(y==null||y===""){T.streaming=!1,f(T);return}let E=Ie.get(T.id)??ot(y);T.rawContent=E;let W=Ge.get(T.id),q=null,H=!1;if(W&&(q=W.getExtractedText(),q===null&&(q=Ur(E)),q===null)){let $=W.processChunk(E);$ instanceof Promise?(H=!0,$.then(se=>{let je=typeof se=="string"?se:se?.text??null;je!==null&&(T.content=je,T.streaming=!1,Ge.delete(T.id),Ie.delete(T.id),f(T))}).catch(()=>{})):q=typeof $=="string"?$:$?.text??null}if(!H){q!==null&&q.trim()!==""?T.content=q:Ie.has(T.id)||(T.content=ot(y));let $=Ge.get(T.id);if($){let se=$.close?.();se instanceof Promise&&se.catch(()=>{}),Ge.delete(T.id)}Ie.delete(T.id),T.streaming=!1,f(T)}},me=(T,O,y)=>{let S=z.get(T);if(S)return S;let E={id:`nested-${O}-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:T,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:O}};return z.set(T,E),f(E),E},Ve=[],ke,ue=new Map,le=0,be="agent",bt=!1,ve=null,de=null,un=new Map,X=this.config.iterationDisplay??"separate";for(ke=()=>{for(let T=0;T<Ve.length;T++){let O=Ve[T].payloadType,y=Ve[T].payload;if(!bt&&be!=="flow"&&typeof y.stepType=="string"&&(be="flow"),O==="reasoning_start"){let S=typeof y.id=="string"?y.id:null,E=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(S&&E){P.set(S,E),me(S,E,"reasoning");continue}let W=ce(y,!0)??`reason-${c()}`,q=Y(W);q.reasoning=q.reasoning??{id:W,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??Fe(y.startedAt??y.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(q.reasoning.scope=y.scope),q.streaming=!0,q.reasoning.status="streaming",f(q)}else if(O==="reasoning_delta"){let S=typeof y.id=="string"?y.id:null;if(S&&P.has(S)&&z.has(S)){let H=z.get(S),$=y.reasoningText??y.text??y.delta??"";$&&y.hidden!==!0&&H.reasoning&&(H.reasoning.chunks.push(String($)),f(H));continue}let E=ce(y,!1)??ce(y,!0)??`reason-${c()}`,W=Y(E);W.reasoning=W.reasoning??{id:E,status:"streaming",chunks:[]},W.reasoning.startedAt=W.reasoning.startedAt??Fe(y.startedAt??y.timestamp);let q=y.reasoningText??y.text??y.delta??"";if(q&&y.hidden!==!0){let H=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(H!==void 0){let $=Qe(E,H,String(q));W.reasoning.chunks=[$]}else W.reasoning.chunks.push(String(q))}if(W.reasoning.status=y.done?"complete":"streaming",y.done){W.reasoning.completedAt=Fe(y.completedAt??y.timestamp);let H=W.reasoning.startedAt??Date.now();W.reasoning.durationMs=Math.max(0,(W.reasoning.completedAt??Date.now())-H)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(O==="reasoning_complete"){let S=typeof y.id=="string"?y.id:null;if(S&&P.has(S)&&z.has(S)){let $=z.get(S);if($.reasoning){let se=typeof y.text=="string"?y.text:"";se&&$.reasoning.chunks.length===0&&$.reasoning.chunks.push(se),$.reasoning.status="complete",$.streaming=!1,f($)}P.delete(S),z.delete(S);continue}let E=ce(y,!1)??ce(y,!0)??`reason-${c()}`,W=typeof y.text=="string"?y.text:"";!x.get(E)&&(W||y.scope==="loop")&&Y(E);let q=x.get(E);if(q?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(q.reasoning.scope=y.scope),W&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(W),q.reasoning.status="complete",q.reasoning.completedAt=Fe(y.completedAt??y.timestamp);let $=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-$),q.streaming=!1,f(q)}let H=F(y);H&&j.byStep.delete(H)}else if(O==="tool_start"){v&&(v.streaming=!1,f(v),v=null),typeof y.iteration=="number"&&(le=y.iteration);let S=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??Ae(y,!0)??`tool-${c()}`,E=y.toolName??y.name;if(Te(E)){Z.add(S);continue}ae(ie(y),S);let W=Oe(S),q=W.toolCall??{id:S,status:"pending"};q.name=E??q.name,q.status="running",y.parameters!==void 0?q.args=y.parameters:y.args!==void 0&&(q.args=y.args),q.startedAt=q.startedAt??Fe(y.startedAt??y.timestamp),q.completedAt=void 0,q.durationMs=void 0,W.toolCall=q,W.streaming=!0,y.executionId&&(W.agentMetadata={executionId:y.executionId,iteration:y.iteration}),f(W)}else if(O==="tool_output_delta"){let S=Ae(y,!1)??Ae(y,!0)??`tool-${c()}`;if(Z.has(S))continue;let E=Oe(S),W=E.toolCall??{id:S,status:"running"};W.startedAt=W.startedAt??Fe(y.startedAt??y.timestamp);let q=y.text??y.delta??y.message??"";q&&(W.chunks=W.chunks??[],W.chunks.push(String(q))),W.status="running",E.toolCall=W,E.streaming=!0;let H=y.agentContext;(H||y.executionId)&&(E.agentMetadata=E.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(E)}else if(O==="tool_complete"){let S=Ae(y,!1)??Ae(y,!0)??`tool-${c()}`;if(Z.has(S)){Z.delete(S);continue}let E=Oe(S),W=E.toolCall??{id:S,status:"running"};W.status="complete",y.result!==void 0&&(W.result=y.result),typeof y.duration=="number"&&(W.duration=y.duration),W.completedAt=Fe(y.completedAt??y.timestamp);let q=y.duration??y.executionTime;if(typeof q=="number")W.durationMs=q;else{let se=W.startedAt??Date.now();W.durationMs=Math.max(0,(W.completedAt??Date.now())-se)}E.toolCall=W,E.streaming=!1;let H=y.agentContext;(H||y.executionId)&&(E.agentMetadata=E.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(E);let $=ie(y);$&&J.byCall.delete($)}else if(O==="await"&&y.toolName){let S=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,E=S??y.toolId??`local-${c()}`,W=Oe(E),q=y.toolName,H=y.origin==="webmcp"&&!Ko(q)?`webmcp:${q}`:q,$=Ko(H),se=W.toolCall??{id:E,status:"pending"};se.name=H,se.args=y.parameters,se.status=$?"running":"complete",se.chunks=se.chunks??[],se.startedAt=se.startedAt??Fe(y.startedAt??y.timestamp??y.awaitedAt),$?(se.completedAt=void 0,se.duration=void 0,se.durationMs=void 0):se.completedAt=se.completedAt??se.startedAt,W.toolCall=se,W.streaming=!1,W.agentMetadata={...W.agentMetadata,executionId:y.executionId??W.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},f(W)}else if(O==="text_start"){let S=typeof y.id=="string"?y.id:null,E=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(S&&E){P.set(S,E);continue}let W=v;W&&(be==="flow"?(Re(W),Tt=W):(W.streaming=!1,f(W)),v=null),k=typeof y.id=="string"?y.id:k,M=""}else if(O==="text_delta"){let S=typeof y.id=="string"?y.id:null,E=S?P.get(S):void 0;if(S&&E){let q=typeof y.delta=="string"?y.delta:"",H=(K.get(S)??"")+q;if(K.set(S,H),H.trim()==="")continue;let $=me(S,E);$.agentMetadata={...$.agentMetadata,executionId:y.executionId,parentToolId:E},yt($,H,q,void 0);continue}if(k=typeof y.id=="string"?y.id:k,be==="flow"){let q=typeof y.delta=="string"?y.delta:"";if(M+=q,M.trim()==="")continue;let H=we();H.agentMetadata={executionId:y.executionId,iteration:y.iteration},yt(H,M,q,void 0),C=H;continue}let W=we();W.content+=y.delta??"",W.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:ve??void 0,agentName:de?.agentName},C=W,f(W)}else if(O==="text_complete"){let S=typeof y.id=="string"?y.id:null;if(S&&P.has(S)){let W=z.get(S);W&&Re(W),P.delete(S),K.delete(S),z.delete(S);continue}let E=v;E&&(be==="flow"?(Re(E),Tt=E):((E.content??"")===""&&typeof y.text=="string"&&(E.content=y.text),E.streaming=!1,f(E)),v=null),k=null,M=""}else if(O==="step_complete"){let S=y.stepType,E=y.executionType;if(S==="tool"||E==="context")continue;if(y.success===!1){let W=y.error,q=typeof W=="string"&&W!==""?W:W!=null&&typeof W=="object"&&Reflect.has(W,"message")?String(W.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let H=v;H&&H.streaming&&(H.streaming=!1,f(H)),n({type:"status",status:"idle"});continue}{let W=Tt;Tt=null;let q=y.stopReason,H=y.result?.response;if(W)q&&(W.stopReason=q),H!=null?on(W,H):W.streaming!==!1&&(Ge.delete(W.id),Ie.delete(W.id),W.streaming=!1,f(W));else{let $=H!=null&&H!=="";if($||q){let se=we();q&&(se.stopReason=q),$?Re(se,H):(se.streaming=!1,f(se))}}continue}}else if(O==="execution_start")be=y.kind==="flow"?"flow":"agent",bt=!0,be==="agent"&&(de={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Fe(y.startedAt)});else if(O==="turn_start"){let S=typeof y.iteration=="number"?y.iteration:le;if(S!==le){if(de&&(de.currentIteration=S),X==="separate"&&S>1){let E=v;E&&(E.streaming=!1,f(E),un.set(S-1,E),v=null)}le=S}ve=typeof y.id=="string"?y.id:null,C=null}else if(O==="tool_input_delta"){let S=y.toolCallId??J.lastId;if(S){let E=U.get(S);E?.toolCall&&(E.toolCall.chunks=E.toolCall.chunks??[],E.toolCall.chunks.push(y.delta??""),f(E))}}else{if(O==="tool_input_complete")continue;if(O==="turn_complete"){let S=y.stopReason,E=v??C;if(S&&E!==null){let W=y.id;(!W||E.agentMetadata?.turnId===W)&&(E.stopReason=S,f(E))}ve===y.id&&(ve=null)}else if(O==="media_start"){let S=String(y.id);ue.set(S,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(O==="media_delta"){let S=ue.get(String(y.id));S&&typeof y.delta=="string"&&S.parts.push(y.delta)}else if(O==="media_complete"){let S=String(y.id),E=ue.get(S);ue.delete(S);let W=(typeof y.mediaType=="string"?y.mediaType:void 0)??E?.mediaType??"application/octet-stream",q=typeof y.data=="string"?y.data:void 0,H=typeof y.url=="string"?y.url:E&&E.parts.length>0?E.parts.join(""):void 0,$=null;if(q)$={type:"media",data:q,mediaType:W};else if(H){let rt=W.toLowerCase();$={type:rt==="image"||rt.startsWith("image/")?"image-url":"file-url",url:H,mediaType:W}}let se=y.toolCallId??E?.toolCallId,je=$?[$]:[],Ee=[];for(let rt of je){if(!rt||typeof rt!="object")continue;let V=rt,$e=typeof V.type=="string"?V.type:void 0,Se=typeof V.mediaType=="string"?V.mediaType.toLowerCase():"",Pe=null,Le="";if($e==="media"){let Xe=typeof V.data=="string"?V.data:void 0;if(!Xe)continue;Le=Se.length>0?Se:"application/octet-stream",Pe=`data:${Le};base64,${Xe}`}else if($e==="image-url"){let Xe=typeof V.url=="string"?V.url:void 0;if(!Xe)continue;Le=Se,Pe=Xe}else if($e==="file-url"){let Xe=typeof V.url=="string"?V.url:void 0;if(!Xe)continue;Le=Se,Pe=Xe}else continue;if(Pe)if($e==="image-url"||Le.startsWith("image/"))Ee.push({type:"image",image:Pe,...Le.includes("/")?{mimeType:Le}:{}});else if(Le.startsWith("audio/"))Ee.push({type:"audio",audio:Pe,mimeType:Le});else if(Le.startsWith("video/"))Ee.push({type:"video",video:Pe,mimeType:Le});else{let Xe=Le||"application/octet-stream";Ee.push({type:"file",data:Pe,mimeType:Xe,filename:Hg(Xe)})}}if(Ee.length>0){let rt=c(),V=se,Se={id:`agent-media-${typeof V=="string"&&V.length>0?`${V}-${rt}`:String(rt)}`,role:"assistant",content:"",contentParts:Ee,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:le}};f(Se);let Pe=v;Pe&&(Pe.streaming=!1,f(Pe)),v=null,I.current=null}}else if(O==="execution_complete"){let S=y.kind??be;S==="agent"&&de&&(de.status=y.success?"complete":"error",de.completedAt=Fe(y.completedAt),de.stopReason=y.stopReason);let E=v;E&&(S==="flow"&&E.streaming!==!1?Re(E):(E.streaming=!1,f(E)),v=null),k=null,M="",Tt=null,n({type:"status",status:"idle",terminal:!0})}else if(O==="execution_error"){let S=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(O!=="ping"){if(O==="approval_start"){let S=y.approvalId??`approval-${c()}`,E={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:de?.agentId??"virtual",executionId:y.executionId??de?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(E)}else if(O==="step_await"&&y.awaitReason==="approval_required"){let S=y.approvalId??`approval-${c()}`,E={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:de?.agentId??"virtual",executionId:y.executionId??de?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(E)}else if(O==="approval_complete"){let S=y.approvalId;if(S){let W={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:y.decision??"approved",agentId:de?.agentId??"virtual",executionId:y.executionId??de?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};f(W)}}else if(O==="artifact_start"||O==="artifact_delta"||O==="artifact_update"||O==="artifact_complete"){if(O==="artifact_start"){let S=y.artifactType,E=String(y.id),W=typeof y.title=="string"?y.title:void 0,q=y.file,H;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&(H={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:E,artifactType:S,title:W,component:typeof y.component=="string"?y.component:void 0,...H?{file:H}:{}});let $=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(pe.set(E,{markdown:"",title:W,file:H,...$?{props:$}:{}}),!ye.has(E)){ye.add(E);let se=So(this.config.features?.artifacts,S),je=typeof y.component=="string"?y.component:void 0,Ee={id:`artifact-ref-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Js(se,{artifactId:E,title:W,artifactType:S,status:"streaming",...H?{file:H}:{},...je?{component:je}:{}})};he.set(E,Ee),f(Ee)}}else if(O==="artifact_delta"){let S=String(y.id),E=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:S,artDelta:E});let W=pe.get(S);W&&(W.markdown+=E)}else if(O==="artifact_update"){let S=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:S,component:typeof y.component=="string"?y.component:void 0});let E=pe.get(String(y.id));E&&(E.props={...E.props??{},...S})}else if(O==="artifact_complete"){let S=String(y.id);n({type:"artifact_complete",id:S});let E=he.get(S);if(E){E.streaming=!1;try{let W=JSON.parse(E.rawContent??"{}");if(W.props){W.props.status="complete";let q=pe.get(S);q?.markdown&&(W.props.markdown=q.markdown),q?.file&&(W.props.file=q.file),W.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(W.props.componentProps=q.props)}E.rawContent=JSON.stringify(W)}catch{}pe.delete(S),f(E),he.delete(S)}}}else if(O==="transcript_insert"){let S=y.message;if(!S||typeof S!="object")continue;let E=String(S.id??`msg-${c()}`),W=S.role,H={id:E,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:c()};if(f(H),H.rawContent)try{let se=JSON.parse(H.rawContent)?.props?.artifactId;typeof se=="string"&&ye.add(se)}catch{}v=null,I.current=null,Ge.delete(E),Ie.delete(E)}else if(O==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let S=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(S)});let E=v;E&&E.streaming&&(E.streaming=!1,f(E)),n({type:"status",status:"idle"})}}else if(O==="step_error"||O==="dispatch_error"||O==="flow_error"){let S=null;if(y.error instanceof Error)S=y.error;else if(O==="dispatch_error"){let E=y.message??y.error;E!=null&&E!==""&&(S=new Error(String(E)))}else{let E=y.error;typeof E=="string"&&E!==""?S=new Error(E):E!=null&&typeof E=="object"&&Reflect.has(E,"message")&&(S=new Error(String(E.message??E)))}if(S){n({type:"error",error:S});let E=v;E&&E.streaming&&(E.streaming=!1,f(E)),n({type:"status",status:"idle"})}}}}}Ve.length=0};;){let{done:T,value:O}=await s.read();if(T)break;l+=a.decode(O,{stream:!0});let y=l.split(`
12
12
 
13
- `);l=y.pop()??"";for(let A of y){let k=A.split(`
14
- `),W="message",V="",B=null;for(let Ee of k)Ee.startsWith("event:")?W=Ee.replace("event:","").trim():Ee.startsWith("data:")?V+=Ee.replace("data:","").trim():Ee.startsWith("id:")&&(B=Ee.slice(3).trim());let U=()=>{B!==null&&B!==""&&n({type:"cursor",id:B})};if(!V){U();continue}let oe;try{oe=JSON.parse(V)}catch(Ee){n({type:"error",error:Ee instanceof Error?Ee:new Error("Failed to parse chat stream payload")});continue}let Ke=W!=="message"?W:oe.type??"message";if(this.onSSEEvent?.(Ke,oe),this.parseSSEEvent){P.current=v;let Ee=await this.handleCustomSSEEvent(oe,n,P,f,c,H);if(P.current&&P.current!==v&&(v=P.current),Ee){U();continue}}Qe.push({payloadType:Ke,payload:oe}),Pe(),U()}}Pe()}};function da(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function nr(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var pa="[Image]";function Pd(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function or(t){return{type:"text",text:t}}var Id=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ig=["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"],Fn=[...Id,...Ig];function Rg(t){return Id.includes(t)||t.startsWith("image/")}function ua(t){return Rg(t.type)}async function Rd(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ua(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 Wd(t,e=Fn,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 Wg(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Bd(t,e){let n=Wg(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 Hd=16e3,Bg=24e3,Hg=4096,Dg=1380533830;function Ng(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Dg?new Uint8Array(t,44):new Uint8Array(t)}function Fg(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 Yr=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;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:Hd,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Hd});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new jc(Bg);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Fg(o)}/ws/agents/${encodeURIComponent(e)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let w=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),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}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(Hg,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},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=Ng(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 Io=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 rr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Yr(t.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(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 Dd(t){if(t?.type==="custom"&&t.custom)return rr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return rr({type:"runtype",runtype:t.runtype});if(Io.isSupported())return rr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ui(t){try{return Dd(t),!0}catch{return!1}}function fa(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 sr=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):fa(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 Zr=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)}};function ji(t){if(!t)return"";let e=Og(t);return Nd(e!==null?e:t)}function Og(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 Nd(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
13
+ `);l=y.pop()??"";for(let S of y){let E=S.split(`
14
+ `),W="message",q="",H=null;for(let Ee of E)Ee.startsWith("event:")?W=Ee.replace("event:","").trim():Ee.startsWith("data:")?q+=Ee.replace("data:","").trim():Ee.startsWith("id:")&&(H=Ee.slice(3).trim());let $=()=>{H!==null&&H!==""&&n({type:"cursor",id:H})};if(!q){$();continue}let se;try{se=JSON.parse(q)}catch(Ee){n({type:"error",error:Ee instanceof Error?Ee:new Error("Failed to parse chat stream payload")});continue}let je=W!=="message"?W:se.type??"message";if(this.onSSEEvent?.(je,se),this.parseSSEEvent){I.current=v;let Ee=await this.handleCustomSSEEvent(se,n,I,f,c,B);if(I.current&&I.current!==v&&(v=I.current),Ee){$();continue}}Ve.push({payloadType:je,payload:se}),ke(),$()}}ke()}};function aa(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Yo(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var ia="[Image]";function Bd(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Zo(t){return{type:"text",text:t}}var Dd=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Fg=["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"],Fn=[...Dd,...Fg];function Ng(t){return Dd.includes(t)||t.startsWith("image/")}function la(t){return Ng(t.type)}async function Fd(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;la(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 Nd(t,e=Fn,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 Og(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Od(t,e){let n=Og(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 _d=16e3,_g=24e3,$g=4096,zg=1380533830;function Ug(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===zg?new Uint8Array(t,44):new Uint8Array(t)}function jg(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 Vr=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;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:_d,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:_d});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new qc(_g);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${jg(o)}/ws/agents/${encodeURIComponent(e)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let w=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),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}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor($g,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},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=Ug(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 Eo=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 er(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Vr(t.runtype);case"browser":if(!Eo.isSupported())throw new Error("Browser speech recognition not supported");return new Eo(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 $d(t){if(t?.type==="custom"&&t.custom)return er({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return er({type:"runtype",runtype:t.runtype});if(Eo.isSupported())return er({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function $i(t){try{return $d(t),!0}catch{return!1}}function ca(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 tr=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):ca(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 Kr=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)}};function zi(t){if(!t)return"";let e=qg(t);return zd(e!==null?e:t)}function qg(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 zd(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),e=e.replace(/\n{2,}/g,`
16
- `),e.trim()}var Fd=null;var qi=()=>Fd?Fd():import("./runtype-tts-entry-UJAEF7NZ.js");var _g=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function $g(t,e){return _g.some(n=>t[n]!==e[n])}function Vi(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}
16
+ `),e.trim()}var Ud=null;var Ui=()=>Ud?Ud():import("./runtype-tts-entry-UJAEF7NZ.js");var Vg=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Kg(t,e){return Vg.some(n=>t[n]!==e[n])}function ji(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}
17
17
 
18
- _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]}),Od=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,_d=t=>Jo(t)||t===Nn,ga=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Zr(()=>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&&(Jo(n.name)||n.name===Nn&&this.config.features?.suggestReplies?.enabled!==!1);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.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);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.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Jr(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,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()}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||qi().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 Ui(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}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=sr.isSupported()?new sr({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 qi().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=rr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!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.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;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){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){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)}updateConfig(e){let n={...this.config,...e};if(!$g(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Jr(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}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:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=e,f={id:a??(n==="user"?da():n==="assistant"?nr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}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:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:f}=o,C={id:p??(r==="user"?da():r==="assistant"?nr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...f!==void 0&&{rawContent:f}};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:p}=e,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
18
+ _Details: ${n.message}_`:o}var Gr=t=>({isError:!0,content:[{type:"text",text:t}]}),jd=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,qd=t=>Ko(t)||t===Dn,da=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Kr(()=>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&&(Ko(n.name)||n.name===Dn&&this.config.features?.suggestReplies?.enabled!==!1);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.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);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.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new qr(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,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()}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||Ui().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 $i(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}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=tr.isSupported()?new tr({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 Ui().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=er(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!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.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;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){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){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)}updateConfig(e){let n={...this.config,...e};if(!Kg(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new qr(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}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:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=e,f={id:a??(n==="user"?aa():n==="assistant"?Yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}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:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:f}=o,C={id:p??(r==="user"?aa():r==="assistant"?Yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...f!==void 0&&{rawContent:f}};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:p}=e,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
19
19
 
20
20
  `),a=[s,n].filter(Boolean).join(`
21
21
 
22
- `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];s&&d.push(or(s)),d.push(...r.contentParts),d.push(...e.contentParts),e.contentParts=d}else if(p){let d=[];a&&d.push(or(a)),d.push(...r.contentParts),e.contentParts=d}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=da(),s=nr();this.activeAssistantMessageId=null;let a=n?.contentParts&&Pd(n.contentParts)?pa:"",l={id:r,role:"user",content:o||a,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}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let w=Vi(c,this.config.errorMessage);if(w){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let e=nr();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=Vi(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(c=>c.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 p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):c=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{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(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}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(c=>c.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 c=e.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let w=typeof u[0]?.question=="string"?u[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,w])=>`${u}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,w)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let v=c[f],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}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!==Nn?!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=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${e}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let w=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Nn)return{dedupeKey:u,resumeKey:f,output:Oi(),toolMessage:p,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,v.signal),P;if(!C)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await C}catch(H){let E=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));return E||this.callbacks.onError?.(H instanceof Error?H:new Error(String(H))),this.markWebMcpToolComplete(p,es(E?"Aborted by cancel()":Od(H)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,es("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:P,toolMessage:p,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(e,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Nn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,es("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),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 v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);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(v)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===Nn,c=e.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",f=a;try{let v;if(d?v=Oi():u?v=await u:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,es("Aborted by cancel()"),a);return}let C=e.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,v,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(v){let C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,es(C||p.aborted?"Aborted by cancel()":Od(v)),a),C||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});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}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{}};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=ko(this.config.features?.artifacts,e.artifactType),r=ta(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...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})}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=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),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=>Vi(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=nr(),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=ji(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return fa(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=ji(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 c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&_d(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&_d(f)&&r.toolCall?.status==="complete";(u||w||v)&&(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)})}};var ma={allowedTypes:Fn,maxFileSize:10*1024*1024,maxFiles:4};function zg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ug(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var ts=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??ma.allowedTypes,maxFileSize:e.maxFileSize??ma.maxFileSize,maxFiles:e.maxFiles??ma.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:ma.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)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}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){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Wd(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Rd(n),s=ua(n)?URL.createObjectURL(n):null,a={id:zg(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=ua(e.file),o=m("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 a=m("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=Ug(e.file.type),p=ne(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=Bd(e.file.type,e.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ne("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}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})}};function $d(t){let{config:e,onOpen:n}=t,o=t.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=e.buttonIconName??"plus",l=e.buttonTooltipText??"Add context",p=m("div","persona-send-button-wrapper"),d=De("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ne(a,s,"currentColor",1.5);c?d.appendChild(c):d.textContent="+",d.addEventListener("click",w=>{w.preventDefault(),w.stopPropagation(),n()}),p.appendChild(d);let u=m("div","persona-send-button-tooltip");return u.textContent=l,p.appendChild(u),{button:d,wrapper:p}}var{setLoader:sv,load:jg}=Xo({fallbackImport:()=>import("./context-mentions-7S5KVUTG.js")});var Ki=jg;var{setLoader:lv,load:qg}=Xo({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var zd=qg;function ns(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=De("span",{className:Bn("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=ne(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=m("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(De("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Ud(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Kc(e).filter(T=>T.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(T=>T.sources.some(I=>typeof I.matchCommand=="function")),r=T=>o.some(I=>I.trigger?I.position==="line-start"?T.split(`
23
- `).some(N=>N.startsWith(I.trigger)):(I.position==="anywhere"?T:T.split(`
24
- `)[0]).startsWith(I.trigger):!1),s=(T,I)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:I}))}catch{}},a=De("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=t.textarea,c=null,u=null,w=null,f=null,v=()=>{if(l)return Promise.resolve(l);if(p)return p;let T=Ki().then(I=>(l=I.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:c??void 0,anchor:t.anchor,contextRow:a,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:E,emit:s}),l)).catch(I=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",I),p===T&&(p=null),null));return p=T,T},C=()=>{zd().then(T=>{let I=T.mountInlineComposer({textarea:t.textarea,renderToken:N=>ns(N,{render:e.renderMentionToken}),onMentionRemoved:N=>l?.untrackMention(N)});c=I.input,u=I.destroy;let z=d;z.replaceWith(I.element),d=I.element,f={next:I.element,prev:z},w?.(I.element,z),l?l.rebindComposer(I.input):p&&p.then(N=>N?.rebindComposer(I.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};e.display==="inline"&&C();let P=[],H=new Map;for(let T of n){if(!T.showButton)continue;let I=$d({config:{...e,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{v().then(z=>z?.openMenu(T.trigger))}});P.push(I),H.set(T.trigger,I.button)}let E=(T,I,z)=>{let N=H.get(I);N&&(N.setAttribute("aria-expanded",T?"true":"false"),T?N.setAttribute("aria-controls",z):N.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(T=>T.wrapper),contextRow:a,handleInput:T=>{if(l){l.handleInput();return}if(!Vc(T))return;let I=d,z=I.selectionStart??0;qc(I.value,z,n)&&v().then(N=>N?.handleInput())},handleKeydown:T=>{if(l?.isMenuOpen())return l.handleKeydown(T);if(T.key==="Backspace"&&l?.hasMentions()&&!f){let I=d,z=I.selectionStart===0&&I.selectionEnd===0;if((I.value.length===0||z)&&l.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(l??await v())?.dispatchInlineCommand(T)??null:null,clear:()=>l?.clear(),prefetch:()=>{Ki().catch(()=>{})},onComposerSwap:T=>{w=T,f&&T(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let T of P)T.wrapper.remove();a.remove()}}}var jd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function os(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];jd(s)&&jd(r)?n[o]=os(s,r):n[o]=r}return n}var On="min(440px, calc(100vw - 24px))",Vd="440px",Vg={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:On,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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",size:"32px",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)"},ct={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",launcher:Vg,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",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",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",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"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],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 qd(t,e){if(!(!t&&!e))return t?e?os(t,e):t:e}function ha(t){return t?{...ct,...t,theme:qd(ct.theme,t.theme),darkTheme:qd(ct.darkTheme,t.darkTheme),launcher:{...ct.launcher,...t.launcher,dock:{...ct.launcher?.dock,...t.launcher?.dock},clearChat:{...ct.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...ct.copy,...t.copy},sendButton:{...ct.sendButton,...t.sendButton},statusIndicator:{...ct.statusIndicator,...t.statusIndicator},voiceRecognition:{...ct.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=ct.features?.artifacts,n=t.features?.artifacts,o=ct.features?.scrollToBottom,r=t.features?.scrollToBottom,s=ct.features?.scrollBehavior,a=t.features?.scrollBehavior,l=ct.features?.streamAnimation,p=t.features?.streamAnimation,d=ct.features?.askUserQuestion,c=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&p===void 0?void 0:{...l,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...ct.features,...t.features,...w!==void 0?{scrollToBottom:w}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...v!==void 0?{streamAnimation:v}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??ct.suggestionChips,suggestionChipsConfig:{...ct.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...ct.layout,...t.layout,header:{...ct.layout?.header,...t.layout?.header},messages:{...ct.layout?.messages,...t.layout?.messages,avatar:{...ct.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...ct.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...ct.layout?.slots,...t.layout?.slots}},markdown:{...ct.markdown,...t.markdown,options:{...ct.markdown?.options,...t.markdown?.options}},messageActions:{...ct.messageActions,...t.messageActions}}:ct}var ya="16px",ba="transparent",Kg={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:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},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"}},Gg={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"}},Qg={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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:On,maxWidth:Vd,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ya,canvasBackground:ba},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},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"},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 Vt(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."))?Vt(t,o):o}function Kd(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Vt(t,a);p!==void 0&&(e[l]={path:l,value:p,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 Xg(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 Gd(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]=Gd(s,r):n[o]=r}return n}function Jg(t,e){return e?Gd(t,e):t}function ar(t,e={}){let n={palette:Kg,semantic:Gg,components:Qg},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:Jg(n.components,t?.components)};if(e.validate!==!1){let r=Xg(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}function Qd(t){let e=Kd(t),n={};for(let[x,j]of Object.entries(e)){let q=x.replace(/\./g,"-");n[`--persona-${q}`]=j.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ya,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ba,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=t.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-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"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=t.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let w=d?.toggleGroup;w&&(w.gap&&(n["--persona-toggle-group-gap"]=w.gap),w.borderRadius&&(n["--persona-toggle-group-radius"]=w.borderRadius));let f=d?.artifact;if(f?.toolbar){let x=f.toolbar;x.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=x.iconHoverColor),x.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=x.iconHoverBackground),x.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=x.iconPadding),x.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=x.iconBorderRadius),x.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=x.iconBorder),x.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=x.toggleGroupGap),x.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=x.toggleBorderRadius),x.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=x.toggleGroupPadding),x.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=x.toggleGroupBorder),x.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=x.toggleGroupBorderRadius),x.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Vt(t,x.toggleGroupBackground)??x.toggleGroupBackground),x.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=x.copyBackground),x.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=x.copyBorder),x.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=x.copyColor),x.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=x.copyBorderRadius),x.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=x.copyPadding),x.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=x.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??x.copyMenuBackground),x.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=x.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??x.copyMenuBorder),x.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=x.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??x.copyMenuShadow),x.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=x.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??x.copyMenuBorderRadius),x.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=x.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??x.copyMenuItemHoverBackground),x.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=x.iconBackground),x.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=x.toolbarBorder)}if(f?.tab){let x=f.tab;x.background&&(n["--persona-artifact-tab-bg"]=x.background),x.activeBackground&&(n["--persona-artifact-tab-active-bg"]=x.activeBackground),x.activeBorder&&(n["--persona-artifact-tab-active-border"]=x.activeBorder),x.borderRadius&&(n["--persona-artifact-tab-radius"]=x.borderRadius),x.textColor&&(n["--persona-artifact-tab-color"]=x.textColor),x.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=x.hoverBackground),x.listBackground&&(n["--persona-artifact-tab-list-bg"]=x.listBackground),x.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=x.listBorderColor),x.listPadding&&(n["--persona-artifact-tab-list-padding"]=x.listPadding)}if(f?.pane){let x=f.pane;if(x.toolbarBackground){let j=Vt(t,x.toolbarBackground)??x.toolbarBackground;n["--persona-artifact-toolbar-bg"]=j}}if(f?.card){let x=f.card;x.background&&(n["--persona-artifact-card-bg"]=x.background),x.border&&(n["--persona-artifact-card-border"]=x.border),x.borderRadius&&(n["--persona-artifact-card-radius"]=x.borderRadius),x.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=x.hoverBackground),x.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=x.hoverBorderColor)}if(f?.inline){let x=f.inline;x.background&&(n["--persona-artifact-inline-bg"]=Vt(t,x.background)??x.background),x.border&&(n["--persona-artifact-inline-border"]=x.border),x.borderRadius&&(n["--persona-artifact-inline-radius"]=x.borderRadius),x.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Vt(t,x.chromeBackground)??x.chromeBackground),x.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Vt(t,x.chromeBorder)??x.chromeBorder),x.titleColor&&(n["--persona-artifact-inline-title-color"]=Vt(t,x.titleColor)??x.titleColor),x.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Vt(t,x.mutedColor)??x.mutedColor),x.frameHeight&&(n["--persona-artifact-inline-frame-height"]=x.frameHeight)}let v=d?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Vt(t,v.background)??v.background));let C=n["--persona-surface"],P=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",E=n["--persona-palette-colors-gray-200"]??"#e5e7eb",T=n["--persona-palette-colors-gray-300"]??"#d1d5db",I=!P||P===C,z=I?H:P,N=I?E:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??z,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??N,I&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??T),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??z,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??z,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??z,n}var Yg={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"}}},Xd=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Gi=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Zg=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Gi()},Jd=t=>Zg(t),em=t=>ar(t),tm=t=>ar({...t,palette:{...t?.palette,colors:{...Yg.colors,...t?.palette?.colors}}},{validate:!1}),ir=t=>{let e=Jd(t),n=Xd(t?.theme),o=Xd(t?.darkTheme);return e==="dark"?tm(os(n??{},o??{})):em(n)},nm=t=>Qd(t),rs=(t,e)=>{let n=ir(e),o=nm(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",Jd(e))},va=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Gi())});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(Gi());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())}};function Mn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function Yd(t){let e=Mn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function wa(t){if(typeof t!="string")return"";let e=t.indexOf(`
22
+ `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];s&&d.push(Zo(s)),d.push(...r.contentParts),d.push(...e.contentParts),e.contentParts=d}else if(p){let d=[];a&&d.push(Zo(a)),d.push(...r.contentParts),e.contentParts=d}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=aa(),s=Yo();this.activeAssistantMessageId=null;let a=n?.contentParts&&Bd(n.contentParts)?ia:"",l={id:r,role:"user",content:o||a,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}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let w=ji(c,this.config.errorMessage);if(w){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let e=Yo();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=ji(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(c=>c.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 p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):c=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{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(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}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(c=>c.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 c=e.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let w=typeof u[0]?.question=="string"?u[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,w])=>`${u}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,w)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let v=c[f],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}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!==Dn?!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=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${e}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let w=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Dn)return{dedupeKey:u,resumeKey:f,output:Fi(),toolMessage:p,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,v.signal),I;if(!C)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await C}catch(B){let k=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return k||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(p,Gr(k?"Aborted by cancel()":jd(B)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,Gr("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:I,toolMessage:p,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(e,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Dn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,Gr("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),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 v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);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(v)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===Dn,c=e.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",f=a;try{let v;if(d?v=Fi():u?v=await u:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,Gr("Aborted by cancel()"),a);return}let C=e.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,v,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(v){let C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,Gr(C||p.aborted?"Aborted by cancel()":jd(v)),a),C||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});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}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{}};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=So(this.config.features?.artifacts,e.artifactType),r=Js(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...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})}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=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),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=>ji(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=Yo(),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=zi(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ca(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=zi(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 c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&qd(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&qd(f)&&r.toolCall?.status==="complete";(u||w||v)&&(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)})}};var pa={allowedTypes:Fn,maxFileSize:10*1024*1024,maxFiles:4};function Gg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Qg(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var Qr=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??pa.allowedTypes,maxFileSize:e.maxFileSize??pa.maxFileSize,maxFiles:e.maxFiles??pa.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:pa.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)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}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){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Nd(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Fd(n),s=la(n)?URL.createObjectURL(n):null,a={id:Gg(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=la(e.file),o=h("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 a=h("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=Qg(e.file.type),p=re(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=h("span");d.textContent=Od(e.file.type,e.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=re("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}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})}};var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},$t=1e5,ua=$t+1;var Xg=8,Jg=8,qi=10,Vi=new WeakMap,Vd=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,Yg=t=>{let e=t.getRootNode?.();return Vd(e)?e:t.ownerDocument.body},Ki=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n));function Ft(t){Vi.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,enabled:r=!0,gap:s=Xg,viewportPadding:a=Jg}=t,l=()=>e.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,u=null,w=!1,f=!1,v=!1,C=()=>(typeof o=="function"?o():o).trim(),I=()=>{u?.(),u=null,d?.remove(),d=null,c=null},B=()=>{if(!d)return;let J=l(),D=p(),F=e.getBoundingClientRect(),ie=d.getBoundingClientRect(),ge=J.documentElement.clientWidth||D.innerWidth,Ce=J.documentElement.clientHeight||D.innerHeight,we=ge-a-ie.width,ee=F.left+F.width/2-ie.width/2,ce=Ki(ee,a,we),Y=F.top-a,ae=Ce-a-F.bottom,Z=ie.height+s,he=Y>=Z||Y>=ae?"top":"bottom",ye=he==="top"?F.top-s-ie.height:F.bottom+s,pe=Ce-a-ie.height,Te=Ki(ye,a,pe),Ae=F.left+F.width/2,Oe=Math.max(qi,ie.width-qi),Fe=Ki(Ae-ce,qi,Oe);d.dataset.placement=he,d.style.left=`${ce}px`,d.style.top=`${Te}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Fe}px`)},k=()=>{if(v||!r||d||!e.isConnected)return;let J=C(),D=Yg(e);if(!J||!D)return;let F=l(),ie=p();d=F.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(ua),c=F.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=J,d.appendChild(c);let ge=F.createElement("span");ge.className="persona-control-tooltip__arrow",d.appendChild(ge),D.appendChild(d),B(),d.dataset.state="open";let Ce=()=>{if(!e.isConnected){I();return}c&&(c.textContent=C()),B()};ie.addEventListener("scroll",Ce,!0),ie.addEventListener("resize",Ce);let we=e.getRootNode(),ee=Vd(we)?we:F.documentElement,ce=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||I()});ce?.observe(ee,{childList:!0,subtree:!0}),u=()=>{ie.removeEventListener("scroll",Ce,!0),ie.removeEventListener("resize",Ce),ce?.disconnect()}},M=()=>{w||f?k():I()},P=()=>{let J=p();(!J.matchMedia||!J.matchMedia("(hover: none)").matches)&&(w=!0,M())},z=()=>{w=!1,M()},K=()=>{f=!0,M()},x=()=>{f=!1,M()},U=J=>{J.key==="Escape"&&(w=!1,f=!1,I())};n.addEventListener("mouseenter",P),n.addEventListener("mouseleave",z),e.addEventListener("focus",K),e.addEventListener("blur",x),e.addEventListener("keydown",U);let j={get isOpen(){return d!==null},show:k,hide:I,reposition:B,destroy:()=>{v||(v=!0,I(),n.removeEventListener("mouseenter",P),n.removeEventListener("mouseleave",z),e.removeEventListener("focus",K),e.removeEventListener("blur",x),e.removeEventListener("keydown",U),Vi.delete(e))}};return Vi.set(e,j),j}function Kd(t){let{config:e,onOpen:n}=t,o=t.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=e.buttonIconName??"plus",l=e.buttonTooltipText??"Add context",p=h("div","persona-send-button-wrapper"),d=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=re(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Ft({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:vv,load:Zg}=Vo({fallbackImport:()=>import("./context-mentions-ONG7A7M6.js")});var Gi=Zg;var{setLoader:Cv,load:em}=Vo({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var Gd=em;function Xr(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=Ne("span",{className:Wn("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=re(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=h("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ne("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Qd(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Gc(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(P=>typeof P.matchCommand=="function")),r=M=>o.some(P=>P.trigger?P.position==="line-start"?M.split(`
23
+ `).some(K=>K.startsWith(P.trigger)):(P.position==="anywhere"?M:M.split(`
24
+ `)[0]).startsWith(P.trigger):!1),s=(M,P)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${M}`,{detail:P}))}catch{}},a=Ne("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=t.textarea,c=null,u=null,w=null,f=null,v=()=>{if(l)return Promise.resolve(l);if(p)return p;let M=Gi().then(P=>(l=P.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:c??void 0,anchor:t.anchor,contextRow:a,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:k,emit:s}),l)).catch(P=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",P),p===M&&(p=null),null));return p=M,M},C=()=>{Gd().then(M=>{let P=M.mountInlineComposer({textarea:t.textarea,renderToken:K=>Xr(K,{render:e.renderMentionToken}),onMentionRemoved:K=>l?.untrackMention(K)});c=P.input,u=P.destroy;let z=d;z.replaceWith(P.element),d=P.element,f={next:P.element,prev:z},w?.(P.element,z),l?l.rebindComposer(P.input):p&&p.then(K=>K?.rebindComposer(P.input))}).catch(M=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",M)})};e.display==="inline"&&C();let I=[],B=new Map;for(let M of n){if(!M.showButton)continue;let P=Kd({config:{...e,buttonIconName:M.buttonIconName,buttonTooltipText:M.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{v().then(z=>z?.openMenu(M.trigger))}});I.push(P),B.set(M.trigger,P.button)}let k=(M,P,z)=>{let K=B.get(P);K&&(K.setAttribute("aria-expanded",M?"true":"false"),M?K.setAttribute("aria-controls",z):K.removeAttribute("aria-controls"))};return{affordanceButtons:I.map(M=>M.wrapper),contextRow:a,handleInput:M=>{if(l){l.handleInput();return}if(!Kc(M))return;let P=d,z=P.selectionStart??0;Vc(P.value,z,n)&&v().then(K=>K?.handleInput())},handleKeydown:M=>{if(l?.isMenuOpen())return l.handleKeydown(M);if(M.key==="Backspace"&&l?.hasMentions()&&!f){let P=d,z=P.selectionStart===0&&P.selectionEnd===0;if((P.value.length===0||z)&&l.removeLastChip())return M.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async M=>r(M)?(l??await v())?.dispatchInlineCommand(M)??null:null,clear:()=>l?.clear(),prefetch:()=>{Gi().catch(()=>{})},onComposerSwap:M=>{w=M,f&&M(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let M of I)M.wrapper.remove();a.remove()}}}var Xd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Jr(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];Xd(s)&&Xd(r)?n[o]=Jr(s,r):n[o]=r}return n}var Nn="min(440px, calc(100vw - 24px))",Yd="440px",tm={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:Nn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:tm,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",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",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",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"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],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 Jd(t,e){if(!(!t&&!e))return t?e?Jr(t,e):t:e}function fa(t){return t?{...it,...t,theme:Jd(it.theme,t.theme),darkTheme:Jd(it.darkTheme,t.darkTheme),launcher:{...it.launcher,...t.launcher,dock:{...it.launcher?.dock,...t.launcher?.dock},clearChat:{...it.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...it.copy,...t.copy},sendButton:{...it.sendButton,...t.sendButton},statusIndicator:{...it.statusIndicator,...t.statusIndicator},voiceRecognition:{...it.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=it.features?.artifacts,n=t.features?.artifacts,o=it.features?.scrollToBottom,r=t.features?.scrollToBottom,s=it.features?.scrollBehavior,a=t.features?.scrollBehavior,l=it.features?.streamAnimation,p=t.features?.streamAnimation,d=it.features?.askUserQuestion,c=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&p===void 0?void 0:{...l,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...it.features,...t.features,...w!==void 0?{scrollToBottom:w}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...v!==void 0?{streamAnimation:v}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...it.layout,...t.layout,header:{...it.layout?.header,...t.layout?.header},messages:{...it.layout?.messages,...t.layout?.messages,avatar:{...it.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...t.layout?.slots}},markdown:{...it.markdown,...t.markdown,options:{...it.markdown?.options,...t.markdown?.options}},messageActions:{...it.messageActions,...t.messageActions}}:it}var ga="16px",ma="transparent",nm={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:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},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"}},om={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"}},rm={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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Nn,maxWidth:Yd,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ga,canvasBackground:ma},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},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"},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 qt(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."))?qt(t,o):o}function Zd(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=qt(t,a);p!==void 0&&(e[l]={path:l,value:p,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 sm(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 ep(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]=ep(s,r):n[o]=r}return n}function am(t,e){return e?ep(t,e):t}function nr(t,e={}){let n={palette:nm,semantic:om,components:rm},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:am(n.components,t?.components)};if(e.validate!==!1){let r=sm(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}function tp(t){let e=Zd(t),n={};for(let[x,U]of Object.entries(e)){let j=x.replace(/\./g,"-");n[`--persona-${j}`]=U.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ga,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ma,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=t.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-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"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=t.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let w=d?.toggleGroup;w&&(w.gap&&(n["--persona-toggle-group-gap"]=w.gap),w.borderRadius&&(n["--persona-toggle-group-radius"]=w.borderRadius));let f=d?.artifact;if(f?.toolbar){let x=f.toolbar;x.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=x.iconHoverColor),x.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=x.iconHoverBackground),x.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=x.iconPadding),x.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=x.iconBorderRadius),x.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=x.iconBorder),x.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=x.toggleGroupGap),x.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=x.toggleBorderRadius),x.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=x.toggleGroupPadding),x.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=x.toggleGroupBorder),x.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=x.toggleGroupBorderRadius),x.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=qt(t,x.toggleGroupBackground)??x.toggleGroupBackground),x.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=x.copyBackground),x.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=x.copyBorder),x.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=x.copyColor),x.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=x.copyBorderRadius),x.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=x.copyPadding),x.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=x.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??x.copyMenuBackground),x.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=x.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??x.copyMenuBorder),x.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=x.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??x.copyMenuShadow),x.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=x.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??x.copyMenuBorderRadius),x.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=x.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??x.copyMenuItemHoverBackground),x.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=x.iconBackground),x.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=x.toolbarBorder)}if(f?.tab){let x=f.tab;x.background&&(n["--persona-artifact-tab-bg"]=x.background),x.activeBackground&&(n["--persona-artifact-tab-active-bg"]=x.activeBackground),x.activeBorder&&(n["--persona-artifact-tab-active-border"]=x.activeBorder),x.borderRadius&&(n["--persona-artifact-tab-radius"]=x.borderRadius),x.textColor&&(n["--persona-artifact-tab-color"]=x.textColor),x.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=x.hoverBackground),x.listBackground&&(n["--persona-artifact-tab-list-bg"]=x.listBackground),x.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=x.listBorderColor),x.listPadding&&(n["--persona-artifact-tab-list-padding"]=x.listPadding)}if(f?.pane){let x=f.pane;if(x.toolbarBackground){let U=qt(t,x.toolbarBackground)??x.toolbarBackground;n["--persona-artifact-toolbar-bg"]=U}}if(f?.card){let x=f.card;x.background&&(n["--persona-artifact-card-bg"]=x.background),x.border&&(n["--persona-artifact-card-border"]=x.border),x.borderRadius&&(n["--persona-artifact-card-radius"]=x.borderRadius),x.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=x.hoverBackground),x.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=x.hoverBorderColor)}if(f?.inline){let x=f.inline;x.background&&(n["--persona-artifact-inline-bg"]=qt(t,x.background)??x.background),x.border&&(n["--persona-artifact-inline-border"]=x.border),x.borderRadius&&(n["--persona-artifact-inline-radius"]=x.borderRadius),x.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=qt(t,x.chromeBackground)??x.chromeBackground),x.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=qt(t,x.chromeBorder)??x.chromeBorder),x.titleColor&&(n["--persona-artifact-inline-title-color"]=qt(t,x.titleColor)??x.titleColor),x.mutedColor&&(n["--persona-artifact-inline-muted-color"]=qt(t,x.mutedColor)??x.mutedColor),x.frameHeight&&(n["--persona-artifact-inline-frame-height"]=x.frameHeight)}let v=d?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=qt(t,v.background)??v.background));let C=n["--persona-surface"],I=n["--persona-container"],B=n["--persona-palette-colors-gray-100"]??"#f3f4f6",k=n["--persona-palette-colors-gray-200"]??"#e5e7eb",M=n["--persona-palette-colors-gray-300"]??"#d1d5db",P=!I||I===C,z=P?B:I,K=P?k:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??z,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??K,P&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??M),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??z,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??z,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??z,n}var im={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"}}},np=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Qi=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",lm=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Qi()},op=t=>lm(t),cm=t=>nr(t),dm=t=>nr({...t,palette:{...t?.palette,colors:{...im.colors,...t?.palette?.colors}}},{validate:!1}),or=t=>{let e=op(t),n=np(t?.theme),o=np(t?.darkTheme);return e==="dark"?dm(Jr(n??{},o??{})):cm(n)},pm=t=>tp(t),Yr=(t,e)=>{let n=or(e),o=pm(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",op(e))},ha=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Qi())});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(Qi());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())}};function Sn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function rp(t){let e=Sn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function ya(t){if(typeof t!="string")return"";let e=t.indexOf(`
25
25
  `);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
26
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function ss(t){let e=Yd(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 oo(t){switch(ss(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=Yd(t.path);return e?e.toUpperCase():"File"}}}function Zd(t){let e=t.markdown??"";return t.file?{filename:Mn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:wa(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}var Qi="http://www.w3.org/2000/svg";function ep(t){let e=document.createElementNS(Qi,"svg");e.setAttribute("class",Bn("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Qi,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Qi,"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 ro=(t,e,n)=>{let o=n;for(let r of e){let s=m("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function tp(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)),ro(t,e,0)}var Xi="persona-artifact-status-label",np="persona-artifact-status-detail",op="data-artifact-status-label",Ji=new Map,rp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function lr(t){t&&Ji.delete(t)}function om(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?oo(e):t.artifactType==="component"?"Component":"Document"}function cr(t,e,n){let o=om(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=Ji.get(a);t.status!=="complete"&&l===void 0&&(l=rp(),Ji.set(a,l));let p=l===void 0?0:Math.max(0,rp()-l),d=t.artifactType==="component",c=!d&&typeof t.markdown=="string"?t.markdown:"",u=d?0:c.length,w=d||c===""?0:c.split(`
27
- `).length,f=t.artifactType==="markdown"?t.file:void 0,v={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,chars:u,lines:w,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(v);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 rm(t){t.className=Xi,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 Ro(t,e,n){let o=t.querySelector(`:scope > .${Xi}`);o||(o=m("span",Xi),t.appendChild(o)),o.getAttribute(op)!==e.label&&(rm(o),tp(o,e.label,n),o.setAttribute(op,e.label));let r=t.querySelector(`:scope > .${np}`),s=e.detail;s?(r||(r=m("span",np),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var sm={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"},am=15e4,xa={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"};function im(t,e){let n=(t||"").trim().toLowerCase();if(n&&xa[n])return xa[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(xa[r])return xa[r]}}return null}function Ca(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 p=l.re.exec(t);if(p&&p.index===o&&p[0].length>0){s(o);let d=l.map?l.map(p[0]):l.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}var lm=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"]),cm=[{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=>lm.has(t)?"keyword":"plain"}];function sp(t){return Ca(t,cm)}var dm=[{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"}];function pm(t){let e=Ca(t,dm);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}var um=[{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}];function ap(t){let e=Ca(t,um),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}var fm=[{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}];function gm(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,p=t.slice(r,l);for(let c of Ca(p,fm))e.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),w=new RegExp("</\\s*"+c+"\\s*>","i").exec(t.slice(r)),f=w?r+w.index:o,v=t.slice(r,f),C=c==="script"?sp(v):ap(v);for(let P of C)e.push(P);r=f}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 mm(t,e){switch(e){case"html":return gm(t);case"css":return ap(t);case"js":return sp(t);case"json":return pm(t)}}function hm(t){let e=Uc(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=sm[r];if(a){let l=m("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
26
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Zr(t){let e=rp(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 oo(t){switch(Zr(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=rp(t.path);return e?e.toUpperCase():"File"}}}function sp(t){let e=t.markdown??"";return t.file?{filename:Sn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:ya(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}var Xi="http://www.w3.org/2000/svg";function ap(t){let e=document.createElementNS(Xi,"svg");e.setAttribute("class",Wn("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Xi,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Xi,"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 ro=(t,e,n)=>{let o=n;for(let r of e){let s=h("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function ip(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)),ro(t,e,0)}var Ji="persona-artifact-status-label",lp="persona-artifact-status-detail",cp="data-artifact-status-label",Yi=new Map,dp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function rr(t){t&&Yi.delete(t)}function um(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?oo(e):t.artifactType==="component"?"Component":"Document"}function sr(t,e,n){let o=um(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=Yi.get(a);t.status!=="complete"&&l===void 0&&(l=dp(),Yi.set(a,l));let p=l===void 0?0:Math.max(0,dp()-l),d=t.artifactType==="component",c=!d&&typeof t.markdown=="string"?t.markdown:"",u=d?0:c.length,w=d||c===""?0:c.split(`
27
+ `).length,f=t.artifactType==="markdown"?t.file:void 0,v={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,chars:u,lines:w,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(v);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 fm(t){t.className=Ji,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 ko(t,e,n){let o=t.querySelector(`:scope > .${Ji}`);o||(o=h("span",Ji),t.appendChild(o)),o.getAttribute(cp)!==e.label&&(fm(o),ip(o,e.label,n),o.setAttribute(cp,e.label));let r=t.querySelector(`:scope > .${lp}`),s=e.detail;s?(r||(r=h("span",lp),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var gm={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"},mm=15e4,ba={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"};function hm(t,e){let n=(t||"").trim().toLowerCase();if(n&&ba[n])return ba[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(ba[r])return ba[r]}}return null}function va(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 p=l.re.exec(t);if(p&&p.index===o&&p[0].length>0){s(o);let d=l.map?l.map(p[0]):l.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}var ym=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"]),bm=[{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=>ym.has(t)?"keyword":"plain"}];function pp(t){return va(t,bm)}var vm=[{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"}];function wm(t){let e=va(t,vm);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}var xm=[{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}];function up(t){let e=va(t,xm),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}var Cm=[{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}];function Am(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,p=t.slice(r,l);for(let c of va(p,Cm))e.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),w=new RegExp("</\\s*"+c+"\\s*>","i").exec(t.slice(r)),f=w?r+w.index:o,v=t.slice(r,f),C=c==="script"?pp(v):up(v);for(let I of C)e.push(I);r=f}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 Sm(t,e){switch(e){case"html":return Am(t);case"css":return up(t);case"js":return pp(t);case"json":return wm(t)}}function Tm(t){let e=jc(),n=h("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=gm[r];if(a){let l=h("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
28
28
  `);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
29
- `)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function ip(t,e,n){let o=t.length<=am?im(e,n):null,r=o?mm(t,o):[{type:"plain",value:t}];return hm(r)}var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,so=zt+1;function dr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(so)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let P=document.createElement("hr");a.appendChild(P)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let P=ne(f.icon,16,"currentColor",1.5);P&&v.appendChild(P)}let C=document.createElement("span");C.textContent=f.label,v.appendChild(C),v.addEventListener("click",P=>{P.stopPropagation(),c(),n(f.id)}),a.appendChild(v)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function u(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:w}}function Rt(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=t,p=m("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ne(e,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Wo(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=t,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),e){let w=ne(e,s??14,"currentColor",2);w&&c.appendChild(w)}let u=m("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[w,f]of Object.entries(p))c.setAttribute(w,f);return c}function Aa(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=m("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of e){let u;c.icon?u=Rt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function lp(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=t,d=m("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",e);let c=m("span","persona-combo-btn-label");c.textContent=e,d.appendChild(c);let u=ne(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=dr({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",f=>{f.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let f=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var Sa="persona-artifact-custom-action-btn";function pr(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 "+Sa+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+Sa+(n?" persona-artifact-doc-icon-btn":"");o=m("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=m("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Wo({icon:t.icon,label:t.label,className:Sa+(n?" persona-artifact-doc-copy-btn":"")}):o=Rt({icon:t.icon,label:t.label,className:Sa+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function as(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}function cp(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?Mn(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=n?oo(n):l==="component"?"Component":"Document",d=document.createElement("div");d.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",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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 u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let w=document.createElement("div");w.className="persona-truncate persona-text-sm persona-font-medium",w.style.color="var(--persona-text, #1f2937)",w.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let v=e?.config?.features?.artifacts,C={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{}},P=cr(C,v,"card");Ro(f,P,v)}else s&&lr(s),f.textContent=p;if(u.append(w,f),d.append(c,u),a==="complete"){let v=e?.config?.features?.artifacts?.cardActions;if(v&&v.length>0){let P={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let H of v)try{if(H.visible===void 0||H.visible(P)){let E=pr(H);E.setAttribute("data-artifact-custom-action",H.id),E.className=`${E.className} persona-flex-shrink-0`,d.append(E)}}catch{}}let C=Wo({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var Ta=(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:()=>cp(t,e)});if(l)return l}return cp(t,e)};var ao=new WeakMap;function Yi(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=ao.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function gp(t){return ao.has(t)}function ym(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";if(t.artifactType==="component"){let s=t.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:a}}let r=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:"",...r?{file:r}:{}}}function dp(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Mn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?oo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function bm(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}var pp=180,vm=240,wm=.8,xm=300,Cm=500,Am="cubic-bezier(0.2, 0, 0, 1)",up=240,Sm=.35;function Tm(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:pp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let H of a)H.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let p=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!p||Math.abs(p-e)<1){l(),r();return}let d=Math.abs(e-p),c=Math.round(Math.min(Cm,Math.max(xm,vm+d*wm))),u=Math.round(c*Sm),w=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:up,delay:u,easing:"ease-out",fill:"backwards"}):null,v=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:c,easing:Am});t.style.height=`${p}px`;let C=!1,P=()=>{C||(C=!0,l(),r())};Promise.allSettled([v.finished,f?.finished].filter(Boolean)).then(P),window.setTimeout(P,Math.max(c,u+up)+120)},pp)}function Mm(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}}var is="--persona-artifact-inline-body-height";function Em(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",p=l==="clip"?!1:e?.followOutput!==!1,d,c,u=e?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=e?.transition==="none"?"none":"auto",f=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:f}}function fp(t,e){let n=ym(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Mm(o),p=o?.inlineActions??[],d=Em(o),c=d.completeDisplay==="card",u=null,w=n,f=m("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let v=Y=>Ta(bm(Y),e),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(is),f.replaceChildren(v(Y)),ao.set(f,ae=>{f.replaceChildren(v(ae))})};if(c&&n.status==="complete")return C(n),f;let P=Ma(n,{config:e.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),H=m("div","persona-artifact-inline-body");H.appendChild(P.el);let E=Y=>{let ae=Y.status!=="complete",Z=ae?d.streamingHeight:d.completeHeight,ve=typeof Z=="number";ve?f.style.setProperty(is,`${Z}px`):f.style.removeProperty(is);let we=!!P.el.querySelector(".persona-code-pre"),ue=!!P.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");H.classList.toggle("persona-artifact-content-flush",we),H.classList.toggle("persona-artifact-inline-body--sized",ve&&ue),H.classList.toggle("persona-artifact-inline-body--cap",!ae&&!ue&&typeof d.completeHeight=="number")},T=n.status,I=(Y,ae)=>{T!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(is,`${d.completeHeight}px`):f.style.removeProperty(is),hp(H,ae?.suppressTransition?"none":d.transition,Y.id,()=>{P.update(Y),E(Y)})):P.update(Y),E(Y),T=Y.status};E(n);let z=d.overflow==="clip"&&a&&!!n.id;if(z&&(H.setAttribute("data-expand-artifact-inline",n.id),H.setAttribute("role","button"),H.setAttribute("tabindex","0"),H.classList.add("persona-cursor-pointer"),H.setAttribute("aria-label",`Open ${dp(n).title} in panel`)),!r)return f.appendChild(H),ao.set(f,I),f;let N=m("div","persona-artifact-inline-chrome");N.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let x=m("div","persona-artifact-inline-chrome-lead"),j=m("span","persona-flex persona-items-center persona-flex-shrink-0"),q=ne("file-text",16,"currentColor",2);q&&j.appendChild(q);let J=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=m("span","persona-artifact-inline-type");x.append(j,J,D);let $=m("div","persona-artifact-inline-chrome-actions"),fe=m("span","persona-flex persona-items-center persona-gap-1"),ye=()=>u??d.viewMode,Le=l?Aa({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:ye(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let ae=Y==="source"?"source":"rendered";ae!==ye()&&(u=ae,P.update(w),E(w))}}):null,Ce=s?Rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Ce&&n.id&&Ce.setAttribute("data-copy-artifact",n.id);let te=a?Rt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;te&&n.id&&te.setAttribute("data-expand-artifact-inline",n.id),$.appendChild(fe),Le&&$.appendChild(Le.element),Ce&&$.appendChild(Ce),te&&$.appendChild(te),N.append(x,$),f.append(N,H);let ge=Y=>{let{title:ae,typeLabel:Z}=dp(Y);J.textContent=ae,J.title=ae,z&&H.setAttribute("aria-label",`Open ${ae} in panel`);let ve=Y.status!=="complete";if(ve){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let we=cr(Y,o,"inline-chrome");Ro(D,we,o)}else lr(Y.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Z;if(Ce&&Ce.classList.toggle("persona-hidden",ve),Le){let we=Y.artifactType==="markdown"?Y.file:void 0,ue=!1;if(!ve&&we&&d.viewMode!=="source"){let Te=ss(we);Te==="markdown"?ue=!0:(Te==="html"||Te==="svg")&&(ue=o?.filePreview?.enabled!==!1)}Le.element.classList.toggle("persona-hidden",!ue),Le.setSelected(ye())}if(fe.replaceChildren(),!ve&&p.length>0){let we=as(Y);if(we)for(let ue of p)try{if(ue.visible===void 0||ue.visible(we)){let Te=pr(ue,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",ue.id),Te.classList.add("persona-flex-shrink-0"),fe.appendChild(Te)}}catch{}}};return ge(n),ao.set(f,(Y,ae)=>{if(c&&T!=="complete"&&Y.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;T="complete";let ve=Y,we=!1,ue=Te=>{ve=Te,we=!0};ao.set(f,ue),Tm(f,Z,{swap:()=>{C(ve),we=!1,ao.set(f,ue)},onSettled:()=>{we?C(ve):ao.set(f,Te=>{f.replaceChildren(v(Te))})}});return}(Y.status!=="complete"||Y.id!==w.id)&&(u=null),w=Y,I(Y,ae),ge(Y)}),f}var mp=(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:()=>fp(t,e)});if(l)return l}return fp(t,e)};var Zi=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)})}},_n=new Zi;_n.register("PersonaArtifactCard",Ta,{bubbleChrome:!1});_n.register("PersonaArtifactInline",mp,{bubbleChrome:!1});function ls(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?wa(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var el=!1;function km(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function hp(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"||el||s){o();return}el=!0;let a=km(n);t.style.setProperty("view-transition-name",a);let l=()=>{el=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Lm="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Pm="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Im(t){let e=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=m("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 Rm(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}}var Wm=220;function Bm(){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 Hm(t){return`
30
- <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 Dm(t,e,n){let o=m("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=m("div","persona-artifact-frame-loading-indicator");r.appendChild(ep());let s=null;return n.label!==!1&&(s=m("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 Nm(t,e,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(T=>clearTimeout(T)),d.clear()},u=(T,I)=>{let z=setTimeout(()=>{d.delete(z),T()},I);d.add(z)},w=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let T=Dm(r,s,o);a=T.el,t.appendChild(a),l=Date.now(),o.label!==!1&&u(T.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,Wm))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",H):e.removeEventListener("load",E)},P=()=>{if(p||(p=!0,C(),c(),!a))return;let T=Math.max(0,o.minVisibleMs-(Date.now()-l));T>0?u(v,T):v()};function H(T){if(n===null)return;let I=T.data;!I||I.persona!=="artifact-preview-ready"||I.token!==n||T.source===e.contentWindow&&P()}function E(){let T=I=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>I()):setTimeout(I,0)};T(()=>T(()=>P()))}return u(f,o.delayMs),u(P,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",H):e.addEventListener("load",E),()=>{p=!0,c(),C(),w()}}function Ma(t,e){let{config:n}=e,o=e.registry??_n,r=e.bodyLayout,s=n.markdown?Js(n.markdown):null,a=Ys(n.sanitize),l=t,p=!1,d=te=>{let ge=Hn()!==null;s&&!ge&&!p&&(p=!0,Xs(()=>Ce(l)));let Y=s?s(te):Zn(te);return s&&ge&&a?a(Y):Y},c=m("div","persona-artifact-preview-body"),u=null,w=null,f=null,v=()=>{f&&(f(),f=null),u=null,w=null},C=null,P=null,H=null,E=!1,T=()=>{C=null,P=null,H=null,E=!1},I=null,z=null,N=()=>{I=null,z=null},x=40,j=0,q=te=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>te()):setTimeout(te,0),J=te=>te.scrollHeight-te.clientHeight-te.scrollTop<=x,D=te=>{if(!r)return;let ge=te.scrollHeight-te.clientHeight>1,Y=te.scrollHeight-te.clientHeight-te.scrollTop;te.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&te.scrollTop>1),te.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&Y>1)},$=te=>{j||(j=q(()=>{j=0,te.scrollTop=te.scrollHeight,D(te)}))},fe=(te,ge,Y,ae)=>{let Z=!!r,ve=Y.id+"|"+(Z?"w":"p");if(!C||H!==ve||C.parentElement!==c){v(),N(),c.replaceChildren();let Te=m("pre",Lm+" persona-code-pre"),Ae=m("code","persona-code");if(Te.appendChild(Ae),Z){let ze=m("div","persona-artifact-source-window");if(ze.appendChild(Te),c.appendChild(ze),!(r?.overflow==="clip")&&typeof ze.addEventListener=="function"){let it=()=>ze.scrollHeight-ze.clientHeight>1;ze.addEventListener("scroll",()=>{J(ze)&&(E=!1),D(ze)},{passive:!0}),ze.addEventListener("wheel",Je=>{it()&&Je.deltaY<0&&(E=!0)},{passive:!0}),ze.addEventListener("touchmove",()=>{it()&&(E=!0)},{passive:!0})}C=ze}else c.appendChild(Te),C=Te;P=Ae,H=ve}let we=Z?C:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",ae),we.classList.toggle("persona-artifact-source-window--clip",ae&&r?.overflow==="clip"));let ue=we?J(we):!0;if(P.replaceChildren(ip(te,ge?.language,ge?.path)),we){let Te=Y.status!=="complete";ae&&Te&&r?.followOutput&&!E&&ue?$(we):Te||(E=!1),D(we)}},ye=te=>{v(),T(),N(),c.replaceChildren();let ge=m("div",Pm);ge.innerHTML=d(te),c.appendChild(ge)},Le=te=>{let ge=te.id,Y=n.features?.artifacts,ae=cr(te,Y,"status-body");if(I&&z===ge&&I.parentElement===c){let we=I.querySelector(".persona-artifact-status-view-text");we&&Ro(we,ae,Y);return}v(),T(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),ve=m("div","persona-artifact-status-view-text");Ro(ve,ae,Y),Z.appendChild(ve),c.appendChild(Z),I=Z,z=ge},Ce=te=>{l=te;let ge=e.resolveViewMode?.(te)??r?.viewMode??"rendered",Y=te.artifactType==="markdown"?te.file:void 0,ae=te.status!=="complete";ae||lr(te.id);let Z=ae?r?.streamingHeight:r?.completeHeight,ve=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&ae){Le(te);return}if(Y){let ue=wa(te.markdown??""),Te=ss(Y),Ae=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ae&&ge==="rendered"&&Ae&&(Te==="html"||Te==="svg")){let Ne=te.id+"\0"+ue;if(u&&w===Ne&&u.parentElement===c)return;T(),N(),v(),c.replaceChildren();let it=n.features?.artifacts?.filePreview,Je=it?.iframeSandbox??"allow-scripts";!it?.dangerouslyAllowSameOrigin&&Je.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."),Je=Je.split(/\s+/).filter(Mt=>Mt&&Mt!=="allow-same-origin").join(" "));let Re=Rm(it?.loading),Me=m("div","persona-artifact-frame"),Ye=m("iframe","persona-artifact-iframe");Ye.setAttribute("sandbox",Je),Ye.setAttribute("data-artifact-id",te.id);let sn=null;Re.enabled&&Re.injectReadySignal?(sn=Bm(),Ye.srcdoc=ue+Hm(sn)):Ye.srcdoc=ue,Me.appendChild(Ye),c.appendChild(Me),Re.enabled&&(f=Nm(Me,Ye,sn,Re,te.id,n)),u=Me,w=Ne;return}if(v(),!ae&&Te==="markdown"&&ge==="rendered"){ye(ue);return}fe(ue,{language:Y.language,path:Y.path},te,ve);return}if(te.artifactType==="markdown"){if(ge==="source"){v(),fe(te.markdown??"",void 0,te,ve);return}ye(te.markdown??"");return}v(),T(),N(),c.replaceChildren();let we=te.component?o.get(te.component):void 0;if(we){let Te={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ae=we(te.props??{},Te);if(Ae){c.appendChild(Ae);return}}catch{}}c.appendChild(Im(te))};return Ce(t),{el:c,update(te){Ce(te)}}}import{Idiomorph as Fm}from"idiomorph";var Ea=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Fm.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 yp=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var tl={index:-1,draft:""};function bp(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 vp(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 wp(){return new Map}function xp(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function Cp(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function Ap(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function ka(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function En(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function io(t,e){return En(t)-t.scrollTop<=e}function La(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=t,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!e&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:e&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:e&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Pa(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 Sp(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Tp(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function Mp(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var cs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Om=["pre","code","a","script","style"],Ia=t=>({type:t?.type??cs.type,placeholder:t?.placeholder??cs.placeholder,speed:t?.speed??cs.speed,duration:t?.duration??cs.duration,buffer:t?.buffer??cs.buffer}),_m=[{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"}],kp=new Map;for(let t of _m)kp.set(t.name,t);var ur=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:kp.get(t)??null,Ra=(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(`
31
- `);return s<0?"":t.slice(0,s)}return t},$m=(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},zm=(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},nl=/\s/,Um=(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},jm=(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(nl.test(s[l])){let p=l;for(;p<s.length&&nl.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<s.length&&!nl.test(s[d]);)p.appendChild($m(o,s[d],e,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,t)},qm=(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 p of l)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(zm(o,p,e,n.value)),n.value+=1));r.replaceChild(a,t)},ds=(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??Om).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)Um(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=e==="char"?jm:qm;for(let u of l)c(u,n,d);return r.innerHTML},Wa=(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},ps=(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},Ep=new WeakMap,Vm=(t,e)=>{if(!t.styles)return;let n=Ep.get(e);if(n||(n=new Set,Ep.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)},ol=new WeakMap,Km=(t,e)=>{if(!t.onAttach)return;let n=ol.get(e);if(n||(n=new Map,ol.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},Lp=t=>{let e=ol.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Ba=(t,e)=>{Vm(t,e),Km(t,e)};function rl(t,e=zt){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 us=0,lo=null;function sl(t=document){if(us++,us===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;lo={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,us=Math.max(0,us-1),us===0&&lo)){let n=t.body,o=t.defaultView??window;n.style.overflow=lo.originalOverflow,n.style.position=lo.originalPosition,n.style.top=lo.originalTop,n.style.width=lo.originalWidth,o.scrollTo(0,lo.scrollY),lo=null}}}var fs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Nt=t=>(t?.launcher?.mountMode??"floating")==="docked",gs=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",un=t=>{let e=t?.launcher?.dock;return{side:e?.side??fs.side,width:e?.width??fs.width,animate:e?.animate??fs.animate,reveal:e?.reveal??fs.reveal,maxHeight:e?.maxHeight??fs.maxHeight}};var xn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Gm="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ha=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=Gm,buttonSize:r,iconSize:s="28px"}=e,a=t?.launcher??{},l=r??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=De("button",{className:Bn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Kt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=ne(u,s,"currentColor",1);if(C?(C.style.display="block",v.appendChild(C)):v.textContent=w,p.appendChild(v),c&&d){let P=null,H=()=>{if(P)return;let T=v.ownerDocument,I=T.body;if(!I)return;P=Tn(T,"div","persona-clear-chat-tooltip"),P.textContent=d;let z=Tn(T,"div");z.className="persona-clear-chat-tooltip-arrow",P.appendChild(z);let N=v.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(so),P.style.left=`${N.left+N.width/2}px`,P.style.top=`${N.top-8}px`,P.style.transform="translate(-50%, -100%)",I.appendChild(P)},E=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};p.addEventListener("mouseenter",H),p.addEventListener("mouseleave",E),v.addEventListener("focus",H),v.addEventListener("blur",E),p._cleanupTooltip=()=>{E(),p.removeEventListener("mouseenter",H),p.removeEventListener("mouseleave",E),v.removeEventListener("focus",H),v.removeEventListener("blur",E)}}return{button:v,wrapper:p}},Qm="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Da=(t,e={})=>{let{wrapperClassName:n=Qm,buttonSize:o,iconSize:r="20px"}=e,a=(t?.launcher??{}).clearChat??{},l=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",w=a.borderColor??"",f=a.borderRadius??"",v=a.paddingX??"",C=a.paddingY??"",P=a.tooltipText??"Clear chat",H=a.showTooltip??!0,E=m("div",n),T=!!(u||w),I=De("button",{className:Bn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":P},style:{height:l,width:l,color:d||Kt.actionIconColor,backgroundColor:c||void 0,border:T?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=ne(p,r,"currentColor",1);if(z&&(z.style.display="block",I.appendChild(z)),E.appendChild(I),H&&P){let N=null,x=()=>{if(N)return;let q=I.ownerDocument,J=q.body;if(!J)return;N=Tn(q,"div","persona-clear-chat-tooltip"),N.textContent=P;let D=Tn(q,"div");D.className="persona-clear-chat-tooltip-arrow",N.appendChild(D);let $=I.getBoundingClientRect();N.style.position="fixed",N.style.zIndex=String(so),N.style.left=`${$.left+$.width/2}px`,N.style.top=`${$.top-8}px`,N.style.transform="translate(-50%, -100%)",J.appendChild(N)},j=()=>{N&&N.parentNode&&(N.parentNode.removeChild(N),N=null)};E.addEventListener("mouseenter",x),E.addEventListener("mouseleave",j),I.addEventListener("focus",x),I.addEventListener("blur",j),E._cleanupTooltip=()=>{j(),E.removeEventListener("mouseenter",x),E.removeEventListener("mouseleave",j),I.removeEventListener("focus",x),I.removeEventListener("blur",j)}}return{button:I,wrapper:E}};var Kt={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))"},Bo=t=>{let{config:e,showClose:n=!0}=t,o=De("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:{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,p=r.headerIconName,d=De("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(p){let z=parseFloat(s)||24,N=ne(p,z*.6,"currentColor",1);N?d.replaceChildren(N):d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let z=m("img");z.src=e.launcher.iconUrl,z.alt="",z.className="persona-rounded-xl persona-object-cover",z.style.height=s,z.style.width=s,d.replaceChildren(z)}else d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=De("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Kt.titleColor}}),w=De("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Kt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let f=r.clearChat??{},v=f.enabled??!0,C=f.placement??"inline",P=null,H=null;if(v){let N=Da(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});P=N.button,H=N.wrapper,C==="top-right"&&(H.style.right="48px"),C==="inline"&&o.appendChild(H)}let E=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&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:T,wrapper:I}=Ha(e,{showClose:n,wrapperClassName:E});return a!=="top-right"&&o.appendChild(I),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:T,closeButtonWrapper:I,clearChatButton:P,clearChatButtonWrapper:H}},ms=(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))};var Xm=t=>{let e=Bo({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 Jm(t,e,n){if(e?.length)for(let o of e){let r=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ne(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=m("div","persona-relative");s.appendChild(r);let a=dr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),t.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),t.appendChild(r)}}var Ym=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),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 p=r?.titleMenu,d,c;if(p)d=lp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Kt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Kt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Jm(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let T=r.onTitleClick;d.addEventListener("click",I=>{I.target.closest("button")||T()}),d.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),T())})}let E=r?.titleRowHover;E&&(d.style.borderRadius=E.borderRadius??"10px",d.style.padding=E.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=E.background??"",d.style.borderColor=E.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=m("div",""),f=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Kt.actionIconColor;let v=a.closeButtonIconName??"x",C=ne(v,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),w.appendChild(f),l.appendChild(w);let P=m("div");P.style.display="none";let H=m("span");return H.style.display="none",{header:l,iconHolder:P,headerTitle:c,headerSubtitle:H,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},Pp={default:Xm,minimal:Ym},Zm=t=>Pp[t]??Pp.default,Na=(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=m("div");l.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=Zm(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};var Fa=t=>{let e=m("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;e.style.maxHeight=`${n*o}px`,e.style.overflowY="auto";let r=()=>{let a=parseFloat(e.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,r());e.style.height=`${a}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Oa=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",p=t?.copy?.sendButtonLabel??"Send",d=t?.copy?.stopButtonLabel??"Stop",c=e.showTooltip??!1,u=e.size??"40px",w=e.backgroundColor,f=e.textColor,v=m("div","persona-send-button-wrapper"),C=De("button",{className:Bn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&w||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}}),P=null,H=null;if(n){let z=parseFloat(u)||24,N=f?.trim()||"currentColor";r?(P=ne(r,z,N,2),P?C.appendChild(P):C.textContent=o):C.textContent=o,H=ne(s,z,N,2)}else C.textContent=p;let E=null;c&&a&&(E=m("div","persona-send-button-tooltip"),E.textContent=a,v.appendChild(E)),C.setAttribute("aria-label",a),v.appendChild(C);let T="send";return{button:C,wrapper:v,setMode:z=>{if(z===T)return;T=z;let N=z==="stop"?l:a;if(C.setAttribute("aria-label",N),E&&(E.textContent=N),n){if(P&&H){let x=z==="stop"?H:P;C.replaceChildren(x)}}else C.textContent=z==="stop"?d:p}}},_a=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";if(!(o||r))return null;let a=t?.sendButton?.size??"40px",l=e.iconName??"mic",p=e.iconSize??a,d=parseFloat(p)||24,c=e.backgroundColor??t?.sendButton?.backgroundColor,u=e.iconColor??t?.sendButton?.textColor,w=m("div","persona-send-button-wrapper"),f=De("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||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=ne(l,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",w.appendChild(f);let P=e.tooltipText??"Start voice recognition";if((e.showTooltip??!1)&&P){let E=m("div","persona-send-button-tooltip");E.textContent=P,w.appendChild(E)}return{button:f,wrapper:w}},$a=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??Fn).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=m("div","persona-send-button-wrapper"),c=De("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ne(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",v=>{v.preventDefault(),r.click()}),d.appendChild(c);let w=e.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=w,d.appendChild(f),{button:c,wrapper:d,input:r,previewsContainer:o}},za=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=m("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=m("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},Ua=()=>De("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ja=t=>{let{config:e}=t,n=De("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=Ua(),r=De("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Fa(e);a();let l=Oa(e),p=_a(e),d=$a(e),c=za(e);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=De("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(w,f),r.append(u),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:w,rightActions:f,setSendButtonMode:l.setMode}};var Ip=()=>{let t=De("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=m("span","persona-pill-peek__icon"),n=ne("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=ne("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},Rp=t=>{let{config:e}=t,n=De("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ua(),r=za(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Fa(e);s.style.maxHeight="100px",a();let l=Oa(e),p=_a(e),d=$a(e);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=De("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&w.append(p.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:w,setSendButtonMode:l.setMode}};var Wp=t=>{let e=t?.launcher?.enabled??!0,n=Nt(t);if(gs(t)){let c=t?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??zt);let w=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",u.appendChild(w);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??zt),{wrapper:u,panel:w,pillRoot:f}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!e){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=t?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=t?.launcher??{},s=r.position&&xn[r.position]?xn[r.position]:xn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??zt);let l=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=t?.launcher?.width??t?.launcherWidth??On;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},eh=(t,e)=>{let n=m("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}=Ha(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});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 I=Da(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=I.button,l=I.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=De("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=De("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"}});d.style.setProperty("scrollbar-gutter","stable");let c=De("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=De("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),w=De("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),f=m("div","persona-flex persona-flex-col persona-gap-3"),v=t?.layout?.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(w.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(w,f);let P=De("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),H=Rp({config:t}),{root:E,textNode:T}=Ip();return n.append(p,r,d,P),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:P,suggestions:H.suggestions,textarea:H.textarea,sendButton:H.sendButton,sendButtonWrapper:H.sendButtonWrapper,micButton:H.micButton,micButtonWrapper:H.micButtonWrapper,composerForm:H.composerForm,statusText:H.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:H.footer,attachmentButton:H.attachmentButton,attachmentButtonWrapper:H.attachmentButtonWrapper,attachmentInput:H.attachmentInput,attachmentPreviewsContainer:H.attachmentPreviewsContainer,actionsRow:H.actionsRow,leftActions:H.leftActions,rightActions:H.rightActions,setSendButtonMode:H.setSendButtonMode,peekBanner:E,peekTextNode:T}},Bp=(t,e=!0)=>{if(gs(t))return eh(t,e);let n=De("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?Na(t,o,{showClose:e}):Bo({config:t,showClose:e}),a=De("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 l=De("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=De("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=De("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Nt(t)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=t?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=ja({config:t}),v=t?.layout?.showFooter!==!1;r?ms(n,s,t):(s.header.style.display="none",ms(n,s,t)),n.append(a);let C=De("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var al=(t,e)=>{let n=m("button");n.type="button",n.innerHTML=`
29
+ `)),n=h("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function fp(t,e,n){let o=t.length<=mm?hm(e,n):null,r=o?Sm(t,o):[{type:"plain",value:t}];return Tm(r)}function ar(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(ua)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let I=document.createElement("hr");a.appendChild(I)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let I=re(f.icon,16,"currentColor",1.5);I&&v.appendChild(I)}let C=document.createElement("span");C.textContent=f.label,v.appendChild(C),v.addEventListener("click",I=>{I.stopPropagation(),c(),n(f.id)}),a.appendChild(v)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function u(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:w}}function Rt(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=t,p=h("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=re(e,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Lo(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=t,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=h("button",d);if(c.type="button",c.setAttribute("aria-label",n),e){let w=re(e,s??14,"currentColor",2);w&&c.appendChild(w)}let u=h("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[w,f]of Object.entries(p))c.setAttribute(w,f);return c}function wa(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=h("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of e){let u;c.icon?u=Rt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=h("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function gp(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=t,d=h("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",e);let c=h("span","persona-combo-btn-label");c.textContent=e,d.appendChild(c);let u=re(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=ar({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",f=>{f.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let f=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var xa="persona-artifact-custom-action-btn";function ir(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 "+xa+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+xa+(n?" persona-artifact-doc-icon-btn":"");o=h("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=h("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Lo({icon:t.icon,label:t.label,className:xa+(n?" persona-artifact-doc-copy-btn":"")}):o=Rt({icon:t.icon,label:t.label,className:xa+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function es(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}function mp(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?Sn(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=n?oo(n):l==="component"?"Component":"Document",d=document.createElement("div");d.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",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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 u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let w=document.createElement("div");w.className="persona-truncate persona-text-sm persona-font-medium",w.style.color="var(--persona-text, #1f2937)",w.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let v=e?.config?.features?.artifacts,C={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{}},I=sr(C,v,"card");ko(f,I,v)}else s&&rr(s),f.textContent=p;if(u.append(w,f),d.append(c,u),a==="complete"){let v=e?.config?.features?.artifacts?.cardActions;if(v&&v.length>0){let I={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let B of v)try{if(B.visible===void 0||B.visible(I)){let k=ir(B);k.setAttribute("data-artifact-custom-action",B.id),k.className=`${k.className} persona-flex-shrink-0`,d.append(k)}}catch{}}let C=Lo({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var Ca=(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:()=>mp(t,e)});if(l)return l}return mp(t,e)};var so=new WeakMap;function Zi(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=so.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function wp(t){return so.has(t)}function Mm(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";if(t.artifactType==="component"){let s=t.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:a}}let r=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:"",...r?{file:r}:{}}}function hp(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Sn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?oo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Em(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}var yp=180,km=240,Lm=.8,Pm=300,Im=500,Rm="cubic-bezier(0.2, 0, 0, 1)",bp=240,Wm=.35;function Hm(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:yp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of a)B.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let p=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!p||Math.abs(p-e)<1){l(),r();return}let d=Math.abs(e-p),c=Math.round(Math.min(Im,Math.max(Pm,km+d*Lm))),u=Math.round(c*Wm),w=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:bp,delay:u,easing:"ease-out",fill:"backwards"}):null,v=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:c,easing:Rm});t.style.height=`${p}px`;let C=!1,I=()=>{C||(C=!0,l(),r())};Promise.allSettled([v.finished,f?.finished].filter(Boolean)).then(I),window.setTimeout(I,Math.max(c,u+bp)+120)},yp)}function Bm(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}}var ts="--persona-artifact-inline-body-height";function Dm(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",p=l==="clip"?!1:e?.followOutput!==!1,d,c,u=e?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=e?.transition==="none"?"none":"auto",f=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:f}}function vp(t,e){let n=Mm(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Bm(o),p=o?.inlineActions??[],d=Dm(o),c=d.completeDisplay==="card",u=null,w=n,f=h("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let v=Y=>Ca(Em(Y),e),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(ts),f.replaceChildren(v(Y)),so.set(f,ae=>{f.replaceChildren(v(ae))})};if(c&&n.status==="complete")return C(n),f;let I=Aa(n,{config:e.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),B=h("div","persona-artifact-inline-body");B.appendChild(I.el);let k=Y=>{let ae=Y.status!=="complete",Z=ae?d.streamingHeight:d.completeHeight,he=typeof Z=="number";he?f.style.setProperty(ts,`${Z}px`):f.style.removeProperty(ts);let ye=!!I.el.querySelector(".persona-code-pre"),pe=!!I.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",ye),B.classList.toggle("persona-artifact-inline-body--sized",he&&pe),B.classList.toggle("persona-artifact-inline-body--cap",!ae&&!pe&&typeof d.completeHeight=="number")},M=n.status,P=(Y,ae)=>{M!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(ts,`${d.completeHeight}px`):f.style.removeProperty(ts),Cp(B,ae?.suppressTransition?"none":d.transition,Y.id,()=>{I.update(Y),k(Y)})):I.update(Y),k(Y),M=Y.status};k(n);let z=d.overflow==="clip"&&a&&!!n.id;if(z&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${hp(n).title} in panel`)),!r)return f.appendChild(B),so.set(f,P),f;let K=h("div","persona-artifact-inline-chrome");K.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let x=h("div","persona-artifact-inline-chrome-lead"),U=h("span","persona-flex persona-items-center persona-flex-shrink-0"),j=re("file-text",16,"currentColor",2);j&&U.appendChild(j);let J=h("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=h("span","persona-artifact-inline-type");x.append(U,J,D);let F=h("div","persona-artifact-inline-chrome-actions"),ie=h("span","persona-flex persona-items-center persona-gap-1"),ge=()=>u??d.viewMode,Ce=l?wa({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:ge(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let ae=Y==="source"?"source":"rendered";ae!==ge()&&(u=ae,I.update(w),k(w))}}):null,we=s?Rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;we&&n.id&&we.setAttribute("data-copy-artifact",n.id);let ee=a?Rt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ee&&n.id&&ee.setAttribute("data-expand-artifact-inline",n.id),F.appendChild(ie),Ce&&F.appendChild(Ce.element),we&&F.appendChild(we),ee&&F.appendChild(ee),K.append(x,F),f.append(K,B);let ce=Y=>{let{title:ae,typeLabel:Z}=hp(Y);J.textContent=ae,J.title=ae,z&&B.setAttribute("aria-label",`Open ${ae} in panel`);let he=Y.status!=="complete";if(he){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let ye=sr(Y,o,"inline-chrome");ko(D,ye,o)}else rr(Y.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Z;if(we&&we.classList.toggle("persona-hidden",he),Ce){let ye=Y.artifactType==="markdown"?Y.file:void 0,pe=!1;if(!he&&ye&&d.viewMode!=="source"){let Te=Zr(ye);Te==="markdown"?pe=!0:(Te==="html"||Te==="svg")&&(pe=o?.filePreview?.enabled!==!1)}Ce.element.classList.toggle("persona-hidden",!pe),Ce.setSelected(ge())}if(ie.replaceChildren(),!he&&p.length>0){let ye=es(Y);if(ye)for(let pe of p)try{if(pe.visible===void 0||pe.visible(ye)){let Te=ir(pe,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",pe.id),Te.classList.add("persona-flex-shrink-0"),ie.appendChild(Te)}}catch{}}};return ce(n),so.set(f,(Y,ae)=>{if(c&&M!=="complete"&&Y.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;M="complete";let he=Y,ye=!1,pe=Te=>{he=Te,ye=!0};so.set(f,pe),Hm(f,Z,{swap:()=>{C(he),ye=!1,so.set(f,pe)},onSettled:()=>{ye?C(he):so.set(f,Te=>{f.replaceChildren(v(Te))})}});return}(Y.status!=="complete"||Y.id!==w.id)&&(u=null),w=Y,P(Y,ae),ce(Y)}),f}var xp=(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:()=>vp(t,e)});if(l)return l}return vp(t,e)};var el=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)})}},On=new el;On.register("PersonaArtifactCard",Ca,{bubbleChrome:!1});On.register("PersonaArtifactInline",xp,{bubbleChrome:!1});function ns(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?ya(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var tl=!1;function Fm(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Cp(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"||tl||s){o();return}tl=!0;let a=Fm(n);t.style.setProperty("view-transition-name",a);let l=()=>{tl=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Nm="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Om="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function _m(t){let e=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=h("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 $m(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}}var zm=220;function Um(){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 jm(t){return`
30
+ <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 qm(t,e,n){let o=h("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=h("div","persona-artifact-frame-loading-indicator");r.appendChild(ap());let s=null;return n.label!==!1&&(s=h("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 Vm(t,e,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(M=>clearTimeout(M)),d.clear()},u=(M,P)=>{let z=setTimeout(()=>{d.delete(z),M()},P);d.add(z)},w=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let M=qm(r,s,o);a=M.el,t.appendChild(a),l=Date.now(),o.label!==!1&&u(M.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,zm))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):e.removeEventListener("load",k)},I=()=>{if(p||(p=!0,C(),c(),!a))return;let M=Math.max(0,o.minVisibleMs-(Date.now()-l));M>0?u(v,M):v()};function B(M){if(n===null)return;let P=M.data;!P||P.persona!=="artifact-preview-ready"||P.token!==n||M.source===e.contentWindow&&I()}function k(){let M=P=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>P()):setTimeout(P,0)};M(()=>M(()=>I()))}return u(f,o.delayMs),u(I,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):e.addEventListener("load",k),()=>{p=!0,c(),C(),w()}}function Aa(t,e){let{config:n}=e,o=e.registry??On,r=e.bodyLayout,s=n.markdown?Ks(n.markdown):null,a=Gs(n.sanitize),l=t,p=!1,d=ee=>{let ce=Hn()!==null;s&&!ce&&!p&&(p=!0,Vs(()=>we(l)));let Y=s?s(ee):Zn(ee);return s&&ce&&a?a(Y):Y},c=h("div","persona-artifact-preview-body"),u=null,w=null,f=null,v=()=>{f&&(f(),f=null),u=null,w=null},C=null,I=null,B=null,k=!1,M=()=>{C=null,I=null,B=null,k=!1},P=null,z=null,K=()=>{P=null,z=null},x=40,U=0,j=ee=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ee()):setTimeout(ee,0),J=ee=>ee.scrollHeight-ee.clientHeight-ee.scrollTop<=x,D=ee=>{if(!r)return;let ce=ee.scrollHeight-ee.clientHeight>1,Y=ee.scrollHeight-ee.clientHeight-ee.scrollTop;ee.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ce&&ee.scrollTop>1),ee.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ce&&Y>1)},F=ee=>{U||(U=j(()=>{U=0,ee.scrollTop=ee.scrollHeight,D(ee)}))},ie=(ee,ce,Y,ae)=>{let Z=!!r,he=Y.id+"|"+(Z?"w":"p");if(!C||B!==he||C.parentElement!==c){v(),K(),c.replaceChildren();let Te=h("pre",Nm+" persona-code-pre"),Ae=h("code","persona-code");if(Te.appendChild(Ae),Z){let Oe=h("div","persona-artifact-source-window");if(Oe.appendChild(Te),c.appendChild(Oe),!(r?.overflow==="clip")&&typeof Oe.addEventListener=="function"){let ot=()=>Oe.scrollHeight-Oe.clientHeight>1;Oe.addEventListener("scroll",()=>{J(Oe)&&(k=!1),D(Oe)},{passive:!0}),Oe.addEventListener("wheel",Ge=>{ot()&&Ge.deltaY<0&&(k=!0)},{passive:!0}),Oe.addEventListener("touchmove",()=>{ot()&&(k=!0)},{passive:!0})}C=Oe}else c.appendChild(Te),C=Te;I=Ae,B=he}let ye=Z?C:null;ye&&(ye.classList.toggle("persona-artifact-source-window--fixed",ae),ye.classList.toggle("persona-artifact-source-window--clip",ae&&r?.overflow==="clip"));let pe=ye?J(ye):!0;if(I.replaceChildren(fp(ee,ce?.language,ce?.path)),ye){let Te=Y.status!=="complete";ae&&Te&&r?.followOutput&&!k&&pe?F(ye):Te||(k=!1),D(ye)}},ge=ee=>{v(),M(),K(),c.replaceChildren();let ce=h("div",Om);ce.innerHTML=d(ee),c.appendChild(ce)},Ce=ee=>{let ce=ee.id,Y=n.features?.artifacts,ae=sr(ee,Y,"status-body");if(P&&z===ce&&P.parentElement===c){let ye=P.querySelector(".persona-artifact-status-view-text");ye&&ko(ye,ae,Y);return}v(),M(),c.replaceChildren();let Z=h("div","persona-artifact-status-view"),he=h("div","persona-artifact-status-view-text");ko(he,ae,Y),Z.appendChild(he),c.appendChild(Z),P=Z,z=ce},we=ee=>{l=ee;let ce=e.resolveViewMode?.(ee)??r?.viewMode??"rendered",Y=ee.artifactType==="markdown"?ee.file:void 0,ae=ee.status!=="complete";ae||rr(ee.id);let Z=ae?r?.streamingHeight:r?.completeHeight,he=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&ae){Ce(ee);return}if(Y){let pe=ya(ee.markdown??""),Te=Zr(Y),Ae=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ae&&ce==="rendered"&&Ae&&(Te==="html"||Te==="svg")){let Fe=ee.id+"\0"+pe;if(u&&w===Fe&&u.parentElement===c)return;M(),K(),v(),c.replaceChildren();let ot=n.features?.artifacts?.filePreview,Ge=ot?.iframeSandbox??"allow-scripts";!ot?.dangerouslyAllowSameOrigin&&Ge.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."),Ge=Ge.split(/\s+/).filter(Tt=>Tt&&Tt!=="allow-same-origin").join(" "));let Ie=$m(ot?.loading),Me=h("div","persona-artifact-frame"),Qe=h("iframe","persona-artifact-iframe");Qe.setAttribute("sandbox",Ge),Qe.setAttribute("data-artifact-id",ee.id);let on=null;Ie.enabled&&Ie.injectReadySignal?(on=Um(),Qe.srcdoc=pe+jm(on)):Qe.srcdoc=pe,Me.appendChild(Qe),c.appendChild(Me),Ie.enabled&&(f=Vm(Me,Qe,on,Ie,ee.id,n)),u=Me,w=Fe;return}if(v(),!ae&&Te==="markdown"&&ce==="rendered"){ge(pe);return}ie(pe,{language:Y.language,path:Y.path},ee,he);return}if(ee.artifactType==="markdown"){if(ce==="source"){v(),ie(ee.markdown??"",void 0,ee,he);return}ge(ee.markdown??"");return}v(),M(),K(),c.replaceChildren();let ye=ee.component?o.get(ee.component):void 0;if(ye){let Te={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ae=ye(ee.props??{},Te);if(Ae){c.appendChild(Ae);return}}catch{}}c.appendChild(_m(ee))};return we(t),{el:c,update(ee){we(ee)}}}import{Idiomorph as Km}from"idiomorph";var Sa=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Km.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 Ap=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var nl={index:-1,draft:""};function Sp(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 Tp(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 Mp(){return new Map}function Ep(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function kp(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function Lp(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Ta(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Tn(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function ao(t,e){return Tn(t)-t.scrollTop<=e}function Ma(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=t,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!e&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:e&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:e&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Ea(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 Pp(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Ip(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function Rp(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var os={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Gm=["pre","code","a","script","style"],ka=t=>({type:t?.type??os.type,placeholder:t?.placeholder??os.placeholder,speed:t?.speed??os.speed,duration:t?.duration??os.duration,buffer:t?.buffer??os.buffer}),Qm=[{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"}],Hp=new Map;for(let t of Qm)Hp.set(t.name,t);var lr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Hp.get(t)??null,La=(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(`
31
+ `);return s<0?"":t.slice(0,s)}return t},Xm=(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},Jm=(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},ol=/\s/,Ym=(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},Zm=(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(ol.test(s[l])){let p=l;for(;p<s.length&&ol.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<s.length&&!ol.test(s[d]);)p.appendChild(Xm(o,s[d],e,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,t)},eh=(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 p of l)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(Jm(o,p,e,n.value)),n.value+=1));r.replaceChild(a,t)},rs=(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??Gm).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)Ym(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=e==="char"?Zm:eh;for(let u of l)c(u,n,d);return r.innerHTML},Pa=(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},ss=(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},Wp=new WeakMap,th=(t,e)=>{if(!t.styles)return;let n=Wp.get(e);if(n||(n=new Set,Wp.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)},rl=new WeakMap,nh=(t,e)=>{if(!t.onAttach)return;let n=rl.get(e);if(n||(n=new Map,rl.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},Bp=t=>{let e=rl.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Ia=(t,e)=>{th(t,e),nh(t,e)};function sl(t,e=$t){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 as=0,io=null;function al(t=document){if(as++,as===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;io={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,as=Math.max(0,as-1),as===0&&io)){let n=t.body,o=t.defaultView??window;n.style.overflow=io.originalOverflow,n.style.position=io.originalPosition,n.style.top=io.originalTop,n.style.width=io.originalWidth,o.scrollTo(0,io.scrollY),io=null}}}var is={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ht=t=>(t?.launcher?.mountMode??"floating")==="docked",ls=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",pn=t=>{let e=t?.launcher?.dock;return{side:e?.side??is.side,width:e?.width??is.width,animate:e?.animate??is.animate,reveal:e?.reveal??is.reveal,maxHeight:e?.maxHeight??is.maxHeight}};var wn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var oh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ra=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=oh,buttonSize:r,iconSize:s="28px"}=e,a=t?.launcher??{},l=r??a.closeButtonSize??"32px",p=h("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Ne("button",{className:Wn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Vt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=re(u,s,"currentColor",1);return C?(C.style.display="block",v.appendChild(C)):v.textContent=w,p.appendChild(v),Ft({anchor:v,trigger:p,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:p}},rh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wa=(t,e={})=>{let{wrapperClassName:n=rh,buttonSize:o,iconSize:r="20px"}=e,a=(t?.launcher??{}).clearChat??{},l=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",w=a.borderColor??"",f=a.borderRadius??"",v=a.paddingX??"",C=a.paddingY??"",I=a.tooltipText??"Clear chat",B=a.showTooltip??!0,k=h("div",n),M=!!(u||w),P=Ne("button",{className:Wn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!M&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":I},style:{height:l,width:l,color:d||Vt.actionIconColor,backgroundColor:c||void 0,border:M?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=re(p,r,"currentColor",1);return z&&(z.style.display="block",P.appendChild(z)),k.appendChild(P),Ft({anchor:P,trigger:k,text:()=>P.getAttribute("aria-label")??I,enabled:B}),{button:P,wrapper:k}};var Vt={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))"},Po=t=>{let{config:e,showClose:n=!0}=t,o=Ne("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:{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,p=r.headerIconName,d=Ne("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(p){let z=parseFloat(s)||24,K=re(p,z*.6,"currentColor",1);K?d.replaceChildren(K):d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let z=h("img");z.src=e.launcher.iconUrl,z.alt="",z.className="persona-rounded-xl persona-object-cover",z.style.height=s,z.style.width=s,d.replaceChildren(z)}else d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let c=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Ne("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Vt.titleColor}}),w=Ne("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Vt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let f=r.clearChat??{},v=f.enabled??!0,C=f.placement??"inline",I=null,B=null;if(v){let K=Wa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=K.button,B=K.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&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:M,wrapper:P}=Ra(e,{showClose:n,wrapperClassName:k});return a!=="top-right"&&o.appendChild(P),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:M,closeButtonWrapper:P,clearChatButton:I,clearChatButtonWrapper:B}},cs=(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))};var sh=t=>{let e=Po({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 ah(t,e,n){if(e?.length)for(let o of e){let r=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=re(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=h("div","persona-relative");s.appendChild(r);let a=ar({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),t.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),t.appendChild(r)}}var ih=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),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 p=r?.titleMenu,d,c;if(p)d=gp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Vt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=h("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Vt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),ah(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let M=r.onTitleClick;d.addEventListener("click",P=>{P.target.closest("button")||M()}),d.addEventListener("keydown",P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),M())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=h("div",""),f=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Vt.actionIconColor;let v=a.closeButtonIconName??"x",C=re(v,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),w.appendChild(f),l.appendChild(w);let I=h("div");I.style.display="none";let B=h("span");return B.style.display="none",{header:l,iconHolder:I,headerTitle:c,headerSubtitle:B,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},Dp={default:sh,minimal:ih},lh=t=>Dp[t]??Dp.default,Ha=(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=h("div");l.style.display="none";let p=h("span"),d=h("span"),c=h("button");c.style.display="none";let u=h("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=lh(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};var Ba=t=>{let e=h("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;e.style.maxHeight=`${n*o}px`,e.style.overflowY="auto";let r=()=>{let a=parseFloat(e.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,r());e.style.height=`${a}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Da=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",p=t?.copy?.sendButtonLabel??"Send",d=t?.copy?.stopButtonLabel??"Stop",c=e.showTooltip??!1,u=e.size??"40px",w=e.backgroundColor,f=e.textColor,v=h("div","persona-send-button-wrapper"),C=Ne("button",{className:Wn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&w||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}}),I=null,B=null;if(n){let P=parseFloat(u)||24,z=f?.trim()||"currentColor";r?(I=re(r,P,z,2),I?C.appendChild(I):C.textContent=o):C.textContent=o,B=re(s,P,z,2)}else C.textContent=p;C.setAttribute("aria-label",a),v.appendChild(C),Ft({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:c});let k="send";return{button:C,wrapper:v,setMode:P=>{if(P===k)return;k=P;let z=P==="stop"?l:a;if(C.setAttribute("aria-label",z),n){if(I&&B){let K=P==="stop"?B:I;C.replaceChildren(K)}}else C.textContent=P==="stop"?d:p}}},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";if(!(o||r))return null;let a=t?.sendButton?.size??"40px",l=e.iconName??"mic",p=e.iconSize??a,d=parseFloat(p)||24,c=e.backgroundColor??t?.sendButton?.backgroundColor,u=e.iconColor??t?.sendButton?.textColor,w=h("div","persona-send-button-wrapper"),f=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":e.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||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=re(l,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",w.appendChild(f);let I=e.tooltipText??"Start voice recognition",B=e.showTooltip??!1;return Ft({anchor:f,trigger:w,text:()=>f.getAttribute("aria-label")??I,enabled:B}),{button:f,wrapper:w}},Na=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=h("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??Fn).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=h("div","persona-send-button-wrapper"),c=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=re(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",f=>{f.preventDefault(),r.click()}),d.appendChild(c);let w=e.buttonTooltipText??"Attach file";return Ft({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},Oa=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=h("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=h("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},_a=()=>Ne("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var $a=t=>{let{config:e}=t,n=Ne("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=_a(),r=Ne("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ba(e);a();let l=Da(e),p=Fa(e),d=Na(e),c=Oa(e);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=Ne("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(w,f),r.append(u),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:w,rightActions:f,setSendButtonMode:l.setMode}};var Fp=()=>{let t=Ne("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=h("span","persona-pill-peek__icon"),n=re("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=h("span","persona-pill-peek__text"),r=h("span","persona-pill-peek__caret"),s=re("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},Np=t=>{let{config:e}=t,n=Ne("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=_a(),r=Oa(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Ba(e);s.style.maxHeight="100px",a();let l=Da(e),p=Fa(e),d=Na(e);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ne("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=h("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&w.append(p.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:w,setSendButtonMode:l.setMode}};var Op=t=>{let e=t?.launcher?.enabled??!0,n=Ht(t);if(ls(t)){let c=t?.launcher?.composerBar??{},u=h("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??$t);let w=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",u.appendChild(w);let f=h("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??$t),{wrapper:u,panel:w,pillRoot:f}}if(n){let c=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!e){let c=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=t?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=t?.launcher??{},s=r.position&&wn[r.position]?wn[r.position]:wn["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??$t);let l=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=t?.launcher?.width??t?.launcherWidth??Nn;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},ch=(t,e)=>{let n=h("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}=Ra(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});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 P=Wa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=P.button,l=P.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Ne("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Ne("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"}});d.style.setProperty("scrollbar-gutter","stable");let c=Ne("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ne("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),w=Ne("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),f=h("div","persona-flex persona-flex-col persona-gap-3"),v=t?.layout?.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(w.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(w,f);let I=Ne("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),B=Np({config:t}),{root:k,textNode:M}=Fp();return n.append(p,r,d,I),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:I,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:p,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:k,peekTextNode:M}},_p=(t,e=!0)=>{if(ls(t))return ch(t,e);let n=Ne("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?Ha(t,o,{showClose:e}):Po({config:t,showClose:e}),a=Ne("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 l=Ne("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Ne("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Ne("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Ht(t)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),c=h("div","persona-flex persona-flex-col persona-gap-3"),u=t?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=$a({config:t}),v=t?.layout?.showFooter!==!1;r?cs(n,s,t):(s.header.style.display="none",cs(n,s,t)),n.append(a);let C=Ne("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var il=(t,e)=>{let n=h("button");n.type="button",n.innerHTML=`
32
32
  <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>
33
33
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
34
34
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -36,14 +36,14 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
36
36
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
37
37
  </span>
38
38
  <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>
39
- `,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=Nt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let T=a.title??"Chat Assistant";p.textContent=T,p.setAttribute("title",T)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let T=a.subtitle??"Here to help you get answers fast";d.textContent=T,d.setAttribute("title",T)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let T=a.agentIconSize??"40px";if(u.style.height=T,u.style.width=T,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let I=parseFloat(T)||24,z=ne(a.agentIconName,I*.6,"var(--persona-text-inverse, #ffffff)",2);z?(u.appendChild(z),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let T=a.agentIconSize??"40px";w.style.height=T,w.style.width=T,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let T=a.callToActionIconSize??"32px";f.style.height=T,f.style.width=T,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let I=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,I=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",a.callToActionIconName){let z=parseFloat(T)||24,N=Math.max(z-I,8),x=ne(a.callToActionIconName,N,"currentColor",2);x?f.appendChild(x):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&xn[a.position]?xn[a.position]:xn["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",P="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-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?P:`${C} ${v}`,l||(n.style.zIndex=String(a.zIndex??zt));let H="1px solid 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??H,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}};var Hp=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=Wp(t),s=Bp(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={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:p,composer:d,replaceHeader:w=>(p.element.replaceWith(w.header),p.element=w.header,p.iconHolder=w.iconHolder,p.headerTitle=w.headerTitle,p.headerSubtitle=w.headerSubtitle,p.closeButton=w.closeButton,p.closeButtonWrapper=w.closeButtonWrapper,p.clearChatButton=w.clearChatButton,p.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},il=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>al(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=al(t,n);return{instance:r,element:r.element}};var th=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},nh=(t,e)=>{if(!t)return null;let n=th(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},oh=(t,e)=>{let n=m("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},rh=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ll=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(":"))},cl=320,Op=320,sh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ah=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),ih=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),lh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),ch=t=>{if(!t||t.length===0)return null;let e=De("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=De("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=m("span","persona-mention-chip-icon"),s=ne(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(De("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},dh=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ns(o.ref,{readonly:!0,render:e}))}return n},Dp="\uE000",Np="\uE001",ph=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${Dp}${r}:${w}${Np}`,a=e.map((w,f)=>w.kind==="text"?w.text:s(f)).join(""),l=n(a);if(!e.every((w,f)=>w.kind==="text"||l.includes(s(f)))){t.replaceChildren(dh(e,o));return}t.innerHTML=l;let d=new RegExp(`${Dp}${r}:(\\d+)${Np}`),c=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),u=[];for(let w=c.nextNode();w;w=c.nextNode())u.push(w);for(let w of u){let f=w;for(let v=d.exec(f.data);v;v=d.exec(f.data)){let C=e[Number(v[1])],P=f.splitText(v.index);P.data=P.data.slice(v[0].length),C?.kind==="mention"&&P.parentNode?.insertBefore(ns(C.ref,{readonly:!0,render:o}),P),f=P}}},uh=(t,e,n)=>{if(t.length===0)return null;try{let o=m("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,p)=>{let d=m("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${cl}px`,d.style.maxHeight=`${Op}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),rh(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},fh=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!ll(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${cl}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},gh=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!ll(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${cl}px`,r.style.maxHeight=`${Op}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}},mh=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!ll(o.data))return;let r=m("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}},hs=()=>{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},hh=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:hs};if(e){let r=e(o);if(r!==null)return r}return hs()},yh=(t,e)=>{let n=m("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=m("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},Fp=(t,e,n="div")=>{let o=m(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},bh=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];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-primary","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-surface","persona-text-persona-primary","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-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},vh=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,a=e.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=m("div");return v.style.display="none",v.id=`actions-${t.id}`,v.setAttribute("data-actions-for",t.id),v}let l=e.visibility??"hover",p=e.align??"right",d=e.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${t.id}`,w.setAttribute("data-actions-for",t.id);let f=(v,C,P)=>{let H=Rt({icon:v,label:C,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",P),H};return o&&w.appendChild(f("copy","Copy message","copy")),a&&w.appendChild(f("volume-2","Read aloud","read-aloud")),r&&w.appendChild(f("thumbs-up","Upvote","upvote")),s&&w.appendChild(f("thumbs-down","Downvote","downvote")),w},dl=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,w=p?.position??"left",f=d?.position??"below",v=bh(t.role,l),C=m("div",v.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"),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-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=sh(t),H=t.content?.trim()??"",T=P.length>0&&H===pa,I=Ia(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,N=t.role==="assistant"&&I.type!=="none"?ur(I.type,z):null,x=t.role==="assistant"&&N?.isAnimating?.(t)===!0,j=t.role==="assistant"&&N!==null&&(!!t.streaming||x);j&&N?.bubbleClass&&C.classList.add(N.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),t.streaming&&q.classList.add("persona-content-streaming"),j&&N&&(N.containerClass&&q.classList.add(N.containerClass),q.style.setProperty("--persona-stream-step",`${I.speed}ms`),q.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let J=j?Ra(t.content??"",I.buffer,N,t,!!t.streaming):t.content??"",D=()=>{let Z=e({text:J,message:t,streaming:!!t.streaming,raw:t.rawContent});return j&&N?.wrap==="char"?ds(Z,"char",t.id,{skipTags:N.skipTags}):j&&N?.wrap==="word"?ds(Z,"word",t.id,{skipTags:N.skipTags}):Z},$=null;if(T?($=document.createElement("div"),$.innerHTML=D(),$.style.display="none",q.appendChild($)):t.contentSegments?.length?ph(q,t.contentSegments,Z=>e({text:Z,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=D(),j&&N?.useCaret&&!T&&H){let Z=Wa(),ve=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=ve[ve.length-1];if(we?.parentNode)we.parentNode.insertBefore(Z,we.nextSibling);else{let ue=q.lastElementChild;ue?ue.appendChild(Z):q.appendChild(Z)}}if(u&&f==="inline"&&t.createdAt){let Z=Fp(t,d,"span");Z.classList.add("persona-timestamp-inline");let ve=q.lastElementChild;ve?ve.appendChild(Z):q.appendChild(Z)}if(P.length>0){let Z=uh(P,!T&&!!H,()=>{T&&$&&($.style.display="")});Z?C.appendChild(Z):T&&$&&($.style.display="")}let fe=ah(t);if(fe.length>0){let Z=fh(fe);Z&&C.appendChild(Z)}let ye=ih(t);if(ye.length>0){let Z=gh(ye);Z&&C.appendChild(Z)}let Le=lh(t);if(Le.length>0){let Z=mh(Le);Z&&C.appendChild(Z)}let Ce=t.contentSegments?.length?null:ch(t.contextMentions);if(Ce&&C.appendChild(Ce),C.appendChild(q),u&&f==="below"&&t.createdAt){let Z=Fp(t,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let te=t.role==="assistant"?nh(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Z=!!(J&&J.trim()),ve=I.placeholder==="skeleton",we=ve&&I.buffer==="line"&&Z;if(Z)we&&C.appendChild(ps());else if(ve)C.appendChild(ps());else{let ue=hh("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ue&&C.appendChild(ue)}}if(te&&t.stopReason&&!t.streaming&&(H||(q.style.display="none"),C.appendChild(oh(t.stopReason,te))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let Z=vh(t,o,r);C.appendChild(Z)}if(!c||t.role==="system")return C;let Y=m("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ae=yh(p,t.role);return w==="right"||w==="left"&&t.role==="user"?Y.append(C,ae):Y.append(ae,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y};var fr=new Set,wh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),xh=(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(`
40
- `):""},_p=(t,e)=>{let n=fr.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=ne(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},pl=(t,e)=>{let n=t.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","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"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&fr.has(t.id),l=n.status!=="complete",p=xh(t,r.previewMaxLines??3),d=m("button",s?"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":"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");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),w="Thinking...",f=e?.reasoning??{},v=String(n.startedAt??Date.now()),C=()=>{let ye=m("span","");return ye.setAttribute("data-tool-elapsed",v),ye.textContent=ia(n),ye},P=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:w,previewText:p,isActive:l,config:e??{},elapsed:ia(n),createElapsedElement:C});typeof P=="string"&&P.trim()?(u.textContent=P,c.appendChild(u)):P instanceof HTMLElement?c.appendChild(P):(u.textContent=w,c.appendChild(u));let H=m("span","persona-text-xs persona-text-persona-primary");H.textContent=Cd(n),c.appendChild(H);let E=r.loadingAnimation??"none",T=f.activeTextTemplate,I=f.completeTextTemplate,z=l?T:I,N=P instanceof HTMLElement,x=(ye,Le)=>{u.textContent="";let Ce=la(ye,""),te=0;for(let ge of Ce){let Y=ge.styles.length>0?(()=>{let ae=m("span",ge.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(ae),ae})():u;if(ge.isDuration&&l)Y.appendChild(C());else{let ae=ge.isDuration?ia(n):ge.text;Le?te=ro(Y,ae,te):Y.appendChild(document.createTextNode(ae))}}};if(!N&&z)if(H.style.display="none",u.style.display="",l&&E!=="none"){let ye=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),E==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),x(z,!1)):(u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),E==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),x(z,!0))}else x(z,!1);else if(!N&&l&&E!=="none"){u.style.display="";let ye=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),E==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`);else{u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),E==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Le=u.textContent||w;u.textContent="",ro(u,Le,0)}n.status==="complete"&&(u.style.display="none")}else N||(n.status==="complete"?u.style.display="none":u.style.display="");let j=null;if(s){j=m("div","persona-flex persona-items-center");let Le=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Le?j.appendChild(Le):j.textContent=a?"Hide":"Show";let Ce=m("div","persona-flex persona-items-center persona-ml-auto");Ce.append(j),d.append(c,Ce)}else d.append(c);let q=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","reasoning"),q.style.display="none",q.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&p){let ye=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});wh(q,ye)||(q.textContent=p),q.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,q),o;let J=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");J.style.display=a?"":"none";let D=n.chunks.join(""),$=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return $.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),J.appendChild($),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let Le=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Le?j.appendChild(Le):j.textContent=a?"Hide":"Show"}J.style.display=a?"":"none",q.style.display=a?"none":q.textContent||q.childNodes.length?"":"none"})(),o.append(d,q,J),o};var gr=new Set,Ch=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Ah=(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(`
39
+ `,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=Ht(s),p=n.querySelector("[data-role='launcher-title']");if(p){let M=a.title??"Chat Assistant";p.textContent=M,p.setAttribute("title",M)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let M=a.subtitle??"Here to help you get answers fast";d.textContent=M,d.setAttribute("title",M)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let M=a.agentIconSize??"40px";if(u.style.height=M,u.style.width=M,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let P=parseFloat(M)||24,z=re(a.agentIconName,P*.6,"var(--persona-text-inverse, #ffffff)",2);z?(u.appendChild(z),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let M=a.agentIconSize??"40px";w.style.height=M,w.style.width=M,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let M=a.callToActionIconSize??"32px";f.style.height=M,f.style.width=M,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let P=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,P=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",a.callToActionIconName){let z=parseFloat(M)||24,K=Math.max(z-P,8),x=re(a.callToActionIconName,K,"currentColor",2);x?f.appendChild(x):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&wn[a.position]?wn[a.position]:wn["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",I="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-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?I:`${C} ${v}`,l||(n.style.zIndex=String(a.zIndex??$t));let B="1px solid var(--persona-border, #e5e7eb)",k="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??B,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:k,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}};var $p=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=Op(t),s=_p(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={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:p,composer:d,replaceHeader:w=>(p.element.replaceWith(w.header),p.element=w.header,p.iconHolder=w.iconHolder,p.headerTitle=w.headerTitle,p.headerSubtitle=w.headerSubtitle,p.closeButton=w.closeButton,p.closeButtonWrapper=w.closeButtonWrapper,p.clearChatButton=w.clearChatButton,p.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},ll=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>il(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=il(t,n);return{instance:r,element:r.element}};var dh=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}},ph=(t,e)=>{if(!t)return null;let n=dh(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},uh=(t,e)=>{let n=h("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},fh=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},cl=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(":"))},dl=320,qp=320,gh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),mh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),hh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),yh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),bh=t=>{if(!t||t.length===0)return null;let e=Ne("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Ne("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=h("span","persona-mention-chip-icon"),s=re(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ne("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},vh=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Xr(o.ref,{readonly:!0,render:e}))}return n},zp="\uE000",Up="\uE001",wh=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${zp}${r}:${w}${Up}`,a=e.map((w,f)=>w.kind==="text"?w.text:s(f)).join(""),l=n(a);if(!e.every((w,f)=>w.kind==="text"||l.includes(s(f)))){t.replaceChildren(vh(e,o));return}t.innerHTML=l;let d=new RegExp(`${zp}${r}:(\\d+)${Up}`),c=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),u=[];for(let w=c.nextNode();w;w=c.nextNode())u.push(w);for(let w of u){let f=w;for(let v=d.exec(f.data);v;v=d.exec(f.data)){let C=e[Number(v[1])],I=f.splitText(v.index);I.data=I.data.slice(v[0].length),C?.kind==="mention"&&I.parentNode?.insertBefore(Xr(C.ref,{readonly:!0,render:o}),I),f=I}}},xh=(t,e,n)=>{if(t.length===0)return null;try{let o=h("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,p)=>{let d=h("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${dl}px`,d.style.maxHeight=`${qp}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),fh(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},Ch=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!cl(o.audio))return;let r=h("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${dl}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Ah=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!cl(o.video))return;let r=h("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${dl}px`,r.style.maxHeight=`${qp}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}},Sh=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!cl(o.data))return;let r=h("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}},ds=()=>{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},Th=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:ds};if(e){let r=e(o);if(r!==null)return r}return ds()},Mh=(t,e)=>{let n=h("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=h("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},jp=(t,e,n="div")=>{let o=h(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},Eh=(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-primary","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-surface","persona-text-persona-primary","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-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},kh=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,a=e.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=h("div");return v.style.display="none",v.id=`actions-${t.id}`,v.setAttribute("data-actions-for",t.id),v}let l=e.visibility??"hover",p=e.align??"right",d=e.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${t.id}`,w.setAttribute("data-actions-for",t.id);let f=(v,C,I)=>{let B=Rt({icon:v,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",I),B};return o&&w.appendChild(f("copy","Copy message","copy")),a&&w.appendChild(f("volume-2","Read aloud","read-aloud")),r&&w.appendChild(f("thumbs-up","Upvote","upvote")),s&&w.appendChild(f("thumbs-down","Downvote","downvote")),w},pl=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,w=p?.position??"left",f=d?.position??"below",v=Eh(t.role,l),C=h("div",v.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"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color="var(--persona-primary, 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-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let I=gh(t),B=t.content?.trim()??"",M=I.length>0&&B===ia,P=ka(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,K=t.role==="assistant"&&P.type!=="none"?lr(P.type,z):null,x=t.role==="assistant"&&K?.isAnimating?.(t)===!0,U=t.role==="assistant"&&K!==null&&(!!t.streaming||x);U&&K?.bubbleClass&&C.classList.add(K.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),t.streaming&&j.classList.add("persona-content-streaming"),U&&K&&(K.containerClass&&j.classList.add(K.containerClass),j.style.setProperty("--persona-stream-step",`${P.speed}ms`),j.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let J=U?La(t.content??"",P.buffer,K,t,!!t.streaming):t.content??"",D=()=>{let Z=e({text:J,message:t,streaming:!!t.streaming,raw:t.rawContent});return U&&K?.wrap==="char"?rs(Z,"char",t.id,{skipTags:K.skipTags}):U&&K?.wrap==="word"?rs(Z,"word",t.id,{skipTags:K.skipTags}):Z},F=null;if(M?(F=document.createElement("div"),F.innerHTML=D(),F.style.display="none",j.appendChild(F)):t.contentSegments?.length?wh(j,t.contentSegments,Z=>e({text:Z,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):j.innerHTML=D(),U&&K?.useCaret&&!M&&B){let Z=Pa(),he=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),ye=he[he.length-1];if(ye?.parentNode)ye.parentNode.insertBefore(Z,ye.nextSibling);else{let pe=j.lastElementChild;pe?pe.appendChild(Z):j.appendChild(Z)}}if(u&&f==="inline"&&t.createdAt){let Z=jp(t,d,"span");Z.classList.add("persona-timestamp-inline");let he=j.lastElementChild;he?he.appendChild(Z):j.appendChild(Z)}if(I.length>0){let Z=xh(I,!M&&!!B,()=>{M&&F&&(F.style.display="")});Z?C.appendChild(Z):M&&F&&(F.style.display="")}let ie=mh(t);if(ie.length>0){let Z=Ch(ie);Z&&C.appendChild(Z)}let ge=hh(t);if(ge.length>0){let Z=Ah(ge);Z&&C.appendChild(Z)}let Ce=yh(t);if(Ce.length>0){let Z=Sh(Ce);Z&&C.appendChild(Z)}let we=t.contentSegments?.length?null:bh(t.contextMentions);if(we&&C.appendChild(we),C.appendChild(j),u&&f==="below"&&t.createdAt){let Z=jp(t,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let ee=t.role==="assistant"?ph(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Z=!!(J&&J.trim()),he=P.placeholder==="skeleton",ye=he&&P.buffer==="line"&&Z;if(Z)ye&&C.appendChild(ss());else if(he)C.appendChild(ss());else{let pe=Th("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);pe&&C.appendChild(pe)}}if(ee&&t.stopReason&&!t.streaming&&(B||(j.style.display="none"),C.appendChild(uh(t.stopReason,ee))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let Z=kh(t,o,r);C.appendChild(Z)}if(!c||t.role==="system")return C;let Y=h("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ae=Mh(p,t.role);return w==="right"||w==="left"&&t.role==="user"?Y.append(C,ae):Y.append(ae,C),Y};var cr=new Set,Lh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Ph=(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(`
40
+ `):""},Vp=(t,e)=>{let n=cr.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=re(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},ul=(t,e)=>{let n=t.reasoning,o=h("div",["persona-message-bubble","persona-reasoning-bubble","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"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&cr.has(t.id),l=n.status!=="complete",p=Ph(t,r.previewMaxLines??3),d=h("button",s?"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":"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");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary"),w="Thinking...",f=e?.reasoning??{},v=String(n.startedAt??Date.now()),C=()=>{let ge=h("span","");return ge.setAttribute("data-tool-elapsed",v),ge.textContent=oa(n),ge},I=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:w,previewText:p,isActive:l,config:e??{},elapsed:oa(n),createElapsedElement:C});typeof I=="string"&&I.trim()?(u.textContent=I,c.appendChild(u)):I instanceof HTMLElement?c.appendChild(I):(u.textContent=w,c.appendChild(u));let B=h("span","persona-text-xs persona-text-persona-primary");B.textContent=Ed(n),c.appendChild(B);let k=r.loadingAnimation??"none",M=f.activeTextTemplate,P=f.completeTextTemplate,z=l?M:P,K=I instanceof HTMLElement,x=(ge,Ce)=>{u.textContent="";let we=ra(ge,""),ee=0;for(let ce of we){let Y=ce.styles.length>0?(()=>{let ae=h("span",ce.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(ae),ae})():u;if(ce.isDuration&&l)Y.appendChild(C());else{let ae=ce.isDuration?oa(n):ce.text;Ce?ee=ro(Y,ae,ee):Y.appendChild(document.createTextNode(ae))}}};if(!K&&z)if(B.style.display="none",u.style.display="",l&&k!=="none"){let ge=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),k==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),x(z,!1)):(u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),k==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),x(z,!0))}else x(z,!1);else if(!K&&l&&k!=="none"){u.style.display="";let ge=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),k==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ge}ms`);else{u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),k==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Ce=u.textContent||w;u.textContent="",ro(u,Ce,0)}n.status==="complete"&&(u.style.display="none")}else K||(n.status==="complete"?u.style.display="none":u.style.display="");let U=null;if(s){U=h("div","persona-flex persona-items-center");let Ce=re(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?U.appendChild(Ce):U.textContent=a?"Hide":"Show";let we=h("div","persona-flex persona-items-center persona-ml-auto");we.append(U),d.append(c,we)}else d.append(c);let j=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","reasoning"),j.style.display="none",j.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&p){let ge=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});Lh(j,ge)||(j.textContent=p),j.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,j),o;let J=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");J.style.display=a?"":"none";let D=n.chunks.join(""),F=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return F.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),J.appendChild(F),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let Ce=re(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?U.appendChild(Ce):U.textContent=a?"Hide":"Show"}J.style.display=a?"":"none",j.style.display=a?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(d,j,J),o};var dr=new Set,Ih=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Rh=(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(`
41
41
  `);let r=no(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
42
- `):""},ul=(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)"},Sh=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Ah(t,o?.previewMaxLines??3),a=n?Ad(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=e?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=$i(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=$i(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},$p=(t,e,n)=>{let o=gr.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ne(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},fl=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","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"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),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&&gr.has(t.id),{summary:p,previewText:d,isActive:c}=Sh(t,e),u=m("button",a?"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":"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");u.type="button",a&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let w=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),C=()=>{let D=m("span","");return D.setAttribute("data-tool-elapsed",v),D.textContent=Gr(n),D},P=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:e??{},elapsed:Gr(n),createElapsedElement:C});typeof P=="string"&&P.trim()?(f.textContent=P,w.appendChild(f)):P instanceof HTMLElement?w.appendChild(P):(f.textContent=p,w.appendChild(f));let H=s.loadingAnimation??"none",E=o.activeTextTemplate,T=o.completeTextTemplate,I=c?E:T,z=P instanceof HTMLElement,N=(D,$)=>{f.textContent="";let fe=n.name?.trim()||"tool",ye=la(D,fe),Le=0;for(let Ce of ye){let te=Ce.styles.length>0?(()=>{let ge=m("span",Ce.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(ge),ge})():f;if(Ce.isDuration&&c)te.appendChild(C());else{let ge=Ce.isDuration?Gr(n):Ce.text;$?Le=ro(te,ge,Le):te.appendChild(document.createTextNode(ge))}}};if(!z)if(c&&H!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),H==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),I&&N(I,!1);else if(f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),H==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),I)N(I,!0);else{let $=f.textContent||p;f.textContent="",ro(f,$,0)}}else I&&N(I,!1);let x=null;if(a){x=m("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=ne(l?"chevron-up":"chevron-down",16,D,2);$?x.appendChild($):x.textContent=l?"Hide":"Show";let fe=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");fe.append(x),u.append(w,fe)}else u.append(w);let j=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let D=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:d,isActive:c,config:e??{}});Ch(j,D)||(j.textContent=d),j.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,j),r;let q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(q.style.display=l?"":"none",o.contentBackgroundColor&&(q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(q.style.color=o.contentTextColor),o.contentPaddingX&&(q.style.paddingLeft=o.contentPaddingX,q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(q.style.paddingTop=o.contentPaddingY,q.style.paddingBottom=o.contentPaddingY),n.name){let D=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,q.appendChild(D)}if(n.args!==void 0){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Arguments";let fe=m("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");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",ul(fe,o),fe.textContent=no(n.args),D.append($,fe),q.appendChild(D)}if(n.chunks&&n.chunks.length){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Activity";let fe=m("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");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",ul(fe,o),fe.textContent=n.chunks.join(""),D.append($,fe),q.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Result";let fe=m("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");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",ul(fe,o),fe.textContent=no(n.result),D.append($,fe),q.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,q.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),x){x.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=ne(l?"chevron-up":"chevron-down",16,D,2);$?x.appendChild($):x.textContent=l?"Hide":"Show"}q.style.display=l?"":"none",j.style.display=l?"none":j.textContent||j.childNodes.length?"":"none"})(),r.append(u,j,q),r};var Ho=new Map,qa=t=>{let n=(t.startsWith(Dn)?t.slice(Dn.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)},zp=t=>t?.approval!==!1?t?.approval:void 0,Up=(t,e)=>{let n=zp(e)?.detailsDisplay??"collapsed";return Ho.get(t)??n==="expanded"},jp=(t,e,n)=>{let o=zp(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=ne(e?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},qp=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Up(t,n);jp(o,s,n),r.style.display=s?"":"none"};var Va=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","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=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=m("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=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",c=ne(p,20,d,2);c&&l.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),w=m("div","persona-flex persona-items-center persona-gap-2"),f=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",w.appendChild(f),!r){let x=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");x.setAttribute("data-approval-status",n.status),n.status==="approved"?(x.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",x.style.color="var(--persona-palette-colors-success-700, #15803d)",x.textContent="Approved"):n.status==="denied"?(x.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",x.style.color="var(--persona-palette-colors-error-700, #b91c1c)",x.textContent="Denied"):n.status==="timeout"&&(x.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",x.style.color="var(--persona-palette-colors-warning-700, #b45309)",x.textContent="Timeout"),w.appendChild(x)}u.appendChild(w);let C=n.toolType==="webmcp"||n.toolName.startsWith(Dn)?jr(n.toolName):void 0,P=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),H=!n.toolName,E=P||(H?n.description:`The assistant wants to use \u201C${C??qa(n.toolName)}\u201D.`),T=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=E,u.appendChild(T),n.reason){let x=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");x.setAttribute("data-approval-reason","true"),o?.reasonColor?x.style.color=o.reasonColor:o?.descriptionColor&&(x.style.color=o.descriptionColor);let j=m("span","persona-font-medium");j.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,x.appendChild(j),x.appendChild(document.createTextNode(n.reason)),u.appendChild(x)}let I=o?.detailsDisplay??"collapsed",z=!!n.description&&!H,N=z||!!n.parameters;if(I!=="hidden"&&N){let x=Up(t.id,e),j=m("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");j.type="button",j.setAttribute("data-expand-header","true"),j.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(j.style.color=o.descriptionColor);let q=m("span");q.setAttribute("data-approval-details-label","true");let J=m("span","persona-inline-flex persona-items-center");J.setAttribute("data-approval-details-chevron","true"),j.append(q,J),jp(j,x,e),u.appendChild(j);let D=m("div");if(D.setAttribute("data-approval-details","true"),D.style.display=x?"":"none",z){let $=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&($.style.color=o.descriptionColor),$.textContent=n.description,D.appendChild($)}if(n.parameters){let $=m("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&&($.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&($.style.color=o.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=no(n.parameters),D.appendChild($)}u.appendChild(D)}if(r){let x=m("div","persona-flex persona-gap-2 persona-mt-2");x.setAttribute("data-approval-buttons","true");let j=m("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");j.type="button",j.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",j.style.color=o?.approveButtonTextColor??"#ffffff",j.setAttribute("data-approval-action","approve");let q=ne("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",j.appendChild(q));let J=document.createTextNode(o?.approveLabel??"Approve");j.appendChild(J);let D=m("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");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let $=ne("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);$&&($.style.marginRight="4px",D.appendChild($));let fe=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(fe),x.append(j,D),u.appendChild(x)}return a.append(l,u),s.appendChild(a),s};var Th=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Vp=(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))},Do=(t,e)=>{Vp(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)},Mh=t=>t?.approval!==!1?t?.approval:void 0,Eh=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return Ho.get(t)??n==="expanded"},gl=t=>{let e=m("span","persona-approval-kbd");return e.textContent=t,e},kh=(t,e)=>{let n=m("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Dn)?jr(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??qa(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},Lh=t=>{let e=m("div","persona-approval-resolved"),n=ne("ban",15,"currentColor",2);n&&e.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=t.toolName?qa(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Ph=(t,e,n,o,r,s,a)=>{let l=m("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 p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,w=u&&Eh(e.id,o),f=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",w?"true":"false"),C.setAttribute("aria-label",w?v:f)):C.setAttribute("data-static","true");let P=m("span","persona-approval-logo"),H=ne("shield-check",16,"currentColor",2);H&&P.appendChild(H),C.appendChild(P);let E=kh(n,o);if(u){let j=m("span","persona-approval-toggle");j.setAttribute("aria-hidden","true");let q=ne("chevron-down",14,"currentColor",2);q&&j.appendChild(q),E.append(" "),E.appendChild(j)}C.appendChild(E),l.appendChild(C);let T=m("div","persona-approval-body");if(u){let j=m("div","persona-approval-details");if(j.setAttribute("data-role","params"),j.hidden=!w,d){let q=m("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,j.appendChild(q)}if(c){let q=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=no(n.parameters),j.appendChild(q)}T.appendChild(j)}if(n.reason){let j=m("p","persona-approval-reason");o?.reasonColor?j.style.color=o.reasonColor:o?.descriptionColor&&(j.style.color=o.descriptionColor);let q=m("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,j.append(q,document.createTextNode(n.reason)),T.appendChild(j)}let I=m("div","persona-approval-actions"),z=null,N=j=>{o?.approveButtonColor&&(j.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(j.style.color=o.approveButtonTextColor)},x=m("button","persona-approval-deny");if(x.type="button",x.setAttribute("data-action","deny"),o?.denyButtonColor&&(x.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(x.style.color=o.denyButtonTextColor),x.append(o?.denyLabel??"Deny"),a){let j=m("div","persona-approval-split"),q=m("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),N(q),q.append(o?.approveLabel??"Always allow",gl("\u23CE"));let J=m("button","persona-approval-caret");J.type="button",J.setAttribute("data-action","toggle-menu"),J.setAttribute("aria-label","More options"),N(J);let D=ne("chevron-down",15,"currentColor",2);D&&J.appendChild(D),j.append(q,J),I.append(j,x),x.append(gl("Esc"));let $=m("div","persona-approval-menu"),fe=m("button","persona-approval-menu-item");fe.type="button",fe.append("Allow once",gl("\u2318\u23CE")),$.appendChild(fe),z=Gc({anchor:j,content:$,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),fe.addEventListener("click",()=>{Do(t,e.id),r()})}else{let j=m("button","persona-approval-primary persona-approval-primary--solo");j.type="button",j.setAttribute("data-action","allow"),N(j),j.append(o?.approveLabel??"Allow"),I.append(j,x)}return T.appendChild(I),l.appendChild(T),l.addEventListener("click",j=>{let q=j.target instanceof Element?j.target.closest("[data-action]"):null;if(!q)return;let J=q.getAttribute("data-action");if(J==="toggle-params"){let D=l.querySelector('[data-role="params"]');if(D){let $=D.hidden;D.hidden=!$,C.setAttribute("aria-expanded",$?"true":"false"),C.setAttribute("aria-label",$?v:f),Ho.set(e.id,$)}return}if(J==="toggle-menu"){z?.toggle();return}if(J==="always"){Do(t,e.id),r({remember:!0});return}if(J==="allow"){Do(t,e.id),r();return}if(J==="deny"){Do(t,e.id),s();return}}),l},Kp=()=>{let t=Th();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 p=Mh(a);if(l.status!=="pending"){if(Do(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Lh(l)}Vp(t,o.id);let d=p?.enableAlwaysAllow===!0,c=Ph(t,o,l,p,r,s,d);if(d){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let u=w=>{Qc(w)||o.id===t.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),Do(t,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])Do(t,o);t.latestPendingApprovalId=null}}};var Gp=t=>{let e=[],n=null;return{buttons:e,render:(r,s,a,l,p,d)=>{t.innerHTML="",e.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(s?s.getMessages():[])).some(P=>P.role==="user"))return;let u=document.createDocumentFragment(),w=s?s.isStreaming():!1,f=v=>{switch(v){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'}};if(r.forEach(v=>{let C=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=v,C.disabled=w,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(C),e.push(C)}),t.appendChild(u),c){let v=JSON.stringify(r);v!==n&&(n=v,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var ys=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 bs=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{}}};var Ih=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Rh=new Set(["step_start","execution_start"]),Wh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Bh=new Set(["step_complete","agent_turn_complete"]),Hh=new Set(["flow_complete","agent_complete"]),Qp=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Jp=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),rn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,No=(t,e)=>{let n=t[e];return Jp(n)?n:void 0};function ml(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ka(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Dh(t,e){return typeof e.type=="string"?e.type:t}function Nh(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 Fh(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 Xp(t){let e=No(t,"result"),n=[No(t,"tokens"),No(t,"totalTokens"),e?No(e,"tokens"):void 0,No(t,"usage"),e?No(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=rn(o.output)??rn(o.outputTokens)??rn(o.completionTokens);if(r!==void 0)return r}return rn(t.outputTokens)??rn(t.completionTokens)??(e?rn(e.outputTokens)??rn(e.completionTokens):void 0)}function Oh(t){let e=No(t,"result");return rn(t.executionTime)??rn(t.executionTimeMs)??rn(t.execution_time)??rn(t.duration)??(e?rn(e.executionTime)??rn(e.executionTimeMs):void 0)}function _h(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var vs=class{constructor(e=_h){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:Ka(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(!Jp(n)){Qp.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Dh(e,n),r=this.now();if(Ih.has(o)){this.startRun(r);return}if(Rh.has(o)){this.run||this.startRun(r);return}if(Wh.has(o)){if(!Fh(o,n))return;let s=Nh(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+ml(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ka(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Bh.has(o)){if(!this.run)return;let s=this.run,a=Xp(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+ml(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ka(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(Hh.has(o)){if(!this.run)return;let s=this.run,a=Xp(n),l=a??s.exactOutputTokens+ml(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ka(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Qp.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:Oh(n)??o-e.startedAt}};function mr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var $h={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)"}},zh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Uh=["flowName","stepName","reasoningText","text","name","tool","toolName"],jh=100;function qh(t,e){let n={...$h,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return zh}function Vh(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Kh(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 Gh(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 Qh(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 Xh(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 Jh(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Yh(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 Zh(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=m("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]"),p=m("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function hl(t,e,n,o,r,s,a,l){let p=r.has(t.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");mr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=m("div",""),f=m("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");f.setAttribute("data-event-id",t.id);let v=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ne(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&v.appendChild(C);let P=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),H=o.timestampFormat??"relative";P.textContent=H==="relative"?Vh(t.timestamp,n):Kh(t.timestamp);let E=null;o.showSequenceNumbers!==!1&&(E=m("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 T=qh(t.type,o.badgeColors),I=m("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");I.style.backgroundColor=T.bg,I.style.color=T.text,I.style.borderColor=T.text+"50",I.textContent=t.type;let z=o.descriptionFields??Uh,N=Gh(t.payload,z),x=null;N&&(x=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),x.textContent=N);let j=m("div","persona-flex-1 persona-min-w-0"),q=m("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"),J=ne("clipboard","12px","currentColor",1.5);return J&&q.appendChild(J),q.addEventListener("click",async D=>{D.stopPropagation(),await Qh(Xh(t)),q.innerHTML="";let $=ne("check","12px","currentColor",1.5);$&&q.appendChild($),setTimeout(()=>{q.innerHTML="";let fe=ne("clipboard","12px","currentColor",1.5);fe&&q.appendChild(fe)},1500)}),f.appendChild(v),f.appendChild(P),E&&f.appendChild(E),f.appendChild(I),x&&f.appendChild(x),f.appendChild(j),f.appendChild(q),w.appendChild(f),p&&w.appendChild(Zh(t,a,l)),w}}function Yp(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return f();function f(){let v=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");mr(C,v?.panel);let P=[],H="",E="",T=null,I=[],z={},N=0,x=ka(),j=0,q=0,J=!1,D=null,$=!1,fe=0,ye=new Set,Le=new Map,Ce="",te="",ge=null,Y,ae,Z,ve,we=null,ue=null,Te=null;function Ae(){let B=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),U=m("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(mr(U,v?.headerBar),a){ue=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ue.style.cursor="help",we=m("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"),we.textContent="-- tok/s",Te=m("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"),Te.style.display="none",Te.style.pointerEvents="none";let Ze=ue,co=Te,po=()=>{if(!co.textContent)return;let Ss=Ze.getBoundingClientRect(),Qt=B.getBoundingClientRect();co.style.left=`${Ss.left-Qt.left}px`,co.style.top=`${Ss.bottom-Qt.top+4}px`,co.style.display="block"},Xa=()=>{co.style.display="none"};ue.addEventListener("mouseenter",po),ue.addEventListener("mouseleave",Xa),ue.appendChild(we)}let oe=m("div","persona-flex-1");Y=m("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 Ke=m("option","");Ke.value="",Ke.textContent="All events (0)",Y.appendChild(Ke),ae=m("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"),ae.type="button",ae.title="Copy All";let lt=ne("clipboard-copy","12px","currentColor",1.5);lt&&ae.appendChild(lt);let K=m("span","persona-event-copy-all persona-text-xs");K.textContent="Copy All",ae.appendChild(K),ue&&U.appendChild(ue),U.appendChild(oe),U.appendChild(Y),U.appendChild(ae);let _e=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");mr(_e,v?.searchBar);let ke=ne("search","14px","var(--persona-muted, #9ca3af)",1.5),Be=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");ke&&Be.appendChild(ke),Z=m("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"),mr(Z,v?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",ve=m("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"),ve.type="button",ve.style.display="none";let Ie=ne("x","12px","currentColor",2);return Ie&&ve.appendChild(Ie),_e.appendChild(Be),_e.appendChild(Z),_e.appendChild(ve),B.appendChild(U),B.appendChild(_e),Te&&B.appendChild(Te),B}let ze,Ne=s.find(B=>B.renderEventStreamToolbar);Ne?.renderEventStreamToolbar&&r?ze=Ne.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ae(),eventCount:e.getSize(),filteredCount:0,onFilterChange:U=>{H=U,Pe(),be()},onSearchChange:U=>{E=U,Pe(),be()}})??Ae():ze=Ae();let it=m("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");it.style.display="none";function Je(){if(!a||!we||!ue)return;let B=a(),U=Jh(B);we.textContent=U;let oe=Yh(B);Te&&(Te.textContent=oe,oe||(Te.style.display="none")),ue.setAttribute("aria-label",oe?`Throughput: ${U}, ${oe}`:`Throughput: ${U}`)}let Re=m("div","persona-flex-1 persona-min-h-0 persona-relative"),Me=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Me.style.height="100%";let Ye=m("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");mr(Ye,v?.scrollIndicator),Ye.style.display="none",Ye.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let sn=ne(d,"14px","currentColor",2);sn&&Ye.appendChild(sn);let Mt=m("span","");Mt.textContent=c,Ye.appendChild(Mt);let yt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");yt.style.display="none",Re.appendChild(Me),Re.appendChild(yt),Re.appendChild(Ye),C.setAttribute("tabindex","0"),C.appendChild(ze),C.appendChild(it),C.appendChild(Re);function We(){let B=e.getAll(),U={};for(let _e of B)U[_e.type]=(U[_e.type]||0)+1;let oe=Object.keys(U).sort(),Ke=oe.length!==I.length||!oe.every((_e,ke)=>_e===I[ke]),Ee=!Ke&&oe.some(_e=>U[_e]!==z[_e]),lt=B.length!==Object.values(z).reduce((_e,ke)=>_e+ke,0);if(!Ke&&!Ee&&!lt||(I=oe,z=U,!Y))return;let K=Y.value;if(Y.options[0].textContent=`All events (${B.length})`,Ke){for(;Y.options.length>1;)Y.remove(1);for(let _e of oe){let ke=m("option","");ke.value=_e,ke.textContent=`${_e} (${U[_e]||0})`,Y.appendChild(ke)}K&&oe.includes(K)?Y.value=K:K&&(Y.value="",H="")}else for(let _e=1;_e<Y.options.length;_e++){let ke=Y.options[_e];ke.textContent=`${ke.value} (${U[ke.value]||0})`}}function me(){let B=e.getAll();if(H&&(B=B.filter(U=>U.type===H)),E){let U=E.toLowerCase();B=B.filter(oe=>oe.type.toLowerCase().includes(U)||oe.payload.toLowerCase().includes(U))}return B}function Qe(){return H!==""||E!==""}function Pe(){N=0,j=0,x.resume(),Ye.style.display="none"}function pe(B){ye.has(B)?ye.delete(B):ye.add(B),ge=B;let U=Me.scrollTop,oe=x.isFollowing();$=!0,x.pause(),be(),Me.scrollTop=U,oe&&x.resume(),$=!1}function ie(){return io(Me,50)}function be(){q=Date.now(),J=!1,Je(),We();let B=e.getEvictedCount();B>0?(it.textContent=`${B.toLocaleString()} older events truncated`,it.style.display=""):it.style.display="none",P=me();let U=P.length,oe=e.getSize()>0;U===0&&oe&&Qe()?(yt.textContent=E?`No events matching '${E}'`:"No events matching filter",yt.style.display="",Me.style.display="none"):(yt.style.display="none",Me.style.display=""),ae&&(ae.title=Qe()?`Copy Filtered (${U})`:"Copy All"),p&&!x.isFollowing()&&U>N&&(j+=U-N,Mt.textContent=c?`${c}${j>0?` (${j})`:""}`:"",Ye.style.display=""),N=U;let Ke=e.getAll(),Ee=Ke.length>0?Ke[0].timestamp:0,lt=new Set(P.map(ke=>ke.id));for(let ke of ye)lt.has(ke)||ye.delete(ke);let K=H!==Ce||E!==te,_e=Le.size===0&&P.length>0;if(K||_e||P.length===0){Me.innerHTML="",Le.clear();let ke=document.createDocumentFragment();for(let Be=0;Be<P.length;Be++){let Ie=hl(P[Be],Be,Ee,u,ye,pe,s,r);Le.set(P[Be].id,Ie),ke.appendChild(Ie)}Me.appendChild(ke),Ce=H,te=E,ge=null}else{if(ge!==null){let Be=Le.get(ge);if(Be&&Be.parentNode===Me){let Ie=P.findIndex(Ze=>Ze.id===ge);if(Ie>=0){let Ze=hl(P[Ie],Ie,Ee,u,ye,pe,s,r);Me.insertBefore(Ze,Be),Be.remove(),Le.set(ge,Ze)}}ge=null}let ke=new Set(P.map(Be=>Be.id));for(let[Be,Ie]of Le)ke.has(Be)||(Ie.remove(),Le.delete(Be));for(let Be=0;Be<P.length;Be++){let Ie=P[Be];if(!Le.has(Ie.id)){let Ze=hl(Ie,Be,Ee,u,ye,pe,s,r);Le.set(Ie.id,Ze),Me.appendChild(Ze)}}}x.isFollowing()&&(Me.scrollTop=Me.scrollHeight)}function bt(){if(Date.now()-q>=jh){D!==null&&(cancelAnimationFrame(D),D=null),be();return}J||(J=!0,D=requestAnimationFrame(()=>{D=null,be()}))}let he=(B,U)=>{if(!ae)return;ae.innerHTML="";let oe=ne(B,"12px","currentColor",1.5);oe&&ae.appendChild(oe);let Ke=m("span","persona-text-xs");Ke.textContent="Copy All",ae.appendChild(Ke),setTimeout(()=>{ae.innerHTML="";let Ee=ne("clipboard-copy","12px","currentColor",1.5);Ee&&ae.appendChild(Ee);let lt=m("span","persona-text-xs");lt.textContent="Copy All",ae.appendChild(lt),ae.disabled=!1},U)},de=async()=>{if(ae){ae.disabled=!0;try{let B;Qe()?B=P:n?(B=await n(),B.length===0&&(B=e.getAll())):B=e.getAll();let U=B.map(oe=>{try{return JSON.parse(oe.payload)}catch{return oe.payload}});await navigator.clipboard.writeText(JSON.stringify(U,null,2)),he("check",1500)}catch{he("x",1500)}}},fn=()=>{Y&&(H=Y.value,Pe(),be())},X=()=>{!Z||!ve||(ve.style.display=Z.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{E=Z.value,Pe(),be()},150))},M=()=>{!Z||!ve||(Z.value="",E="",ve.style.display="none",T&&clearTimeout(T),Pe(),be())},F=()=>{if($)return;let B=Me.scrollTop,{action:U,nextLastScrollTop:oe}=La({following:x.isFollowing(),currentScrollTop:B,lastScrollTop:fe,nearBottom:ie(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});fe=oe,U==="resume"?(x.resume(),j=0,Ye.style.display="none"):U==="pause"&&(x.pause(),p&&(Mt.textContent=c,Ye.style.display=""))},y=B=>{let U=Pa({following:x.isFollowing(),deltaY:B.deltaY,nearBottom:ie(),resumeWhenNearBottom:!0});U==="pause"?(x.pause(),p&&(Mt.textContent=c,Ye.style.display="")):U==="resume"&&(x.resume(),j=0,Ye.style.display="none")},A=()=>{p&&(Me.scrollTop=Me.scrollHeight,x.resume(),j=0,Ye.style.display="none")},k=B=>{let U=B.target;if(!U||U.closest("button"))return;let oe=U.closest("[data-event-id]");if(!oe)return;let Ke=oe.getAttribute("data-event-id");Ke&&pe(Ke)},W=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),Z?.focus(),Z?.select();return}B.key==="Escape"&&(Z&&document.activeElement===Z?(M(),Z.blur(),C.focus()):o&&o())};ae&&ae.addEventListener("click",de),Y&&Y.addEventListener("change",fn),Z&&Z.addEventListener("input",X),ve&&ve.addEventListener("click",M),Me.addEventListener("scroll",F),Me.addEventListener("wheel",y,{passive:!0}),Me.addEventListener("click",k),Ye.addEventListener("click",A),C.addEventListener("keydown",W);function V(){T&&clearTimeout(T),D!==null&&(cancelAnimationFrame(D),D=null),J=!1,Le.clear(),ae&&ae.removeEventListener("click",de),Y&&Y.removeEventListener("change",fn),Z&&Z.removeEventListener("input",X),ve&&ve.removeEventListener("click",M),Me.removeEventListener("scroll",F),Me.removeEventListener("wheel",y),Me.removeEventListener("click",k),Ye.removeEventListener("click",A),C.removeEventListener("keydown",W)}return{element:C,update:bt,destroy:V}}}function Zp(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=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let w=u;return s.findIndex(f=>f===w||f.contains(w))},d=u=>{let w=p(u.target);if(w<0)return;let f=w;if(u.key===r)f=Math.min(w+1,s.length-1);else if(u.key===o)f=Math.max(w-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==w&&e.onSelect(f)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return t.addEventListener("keydown",d),t.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((f,v)=>{f.setAttribute("role","tab");let C=v===w;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||w<0&&v===0?0:-1}),a){let f=(w>=0?u[w]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){t.removeEventListener("keydown",d),t.removeEventListener("focusin",c)}}}function eu(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(),p=n?.tabFadeSize?.trim(),d=X=>({start:X===!1?!1:typeof X=="object"&&X?X.start!==!1:!0,end:X===!1?!1:typeof X=="object"&&X?X.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),$?.hide()};w&&w.addEventListener("click",()=>{f(),e.onDismiss?.()});let v=m("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");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let C=m("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 P=m("span","persona-text-xs persona-font-medium persona-truncate");P.textContent=s;let H=Rt({icon:"x",label:a});H.addEventListener("click",()=>{f(),e.onDismiss?.()});let E="rendered",T=Aa({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:X=>{E=X==="source"?"source":"rendered",he()}}),I=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,N=n?.documentToolbarShowCopyChevron===!0,x=n?.documentToolbarCopyMenuItems,j=!!(N&&x&&x.length>0),q=null,J,D=null,$=null;if(r&&(z||N)&&!j){if(J=z?Wo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N){let X=ne("chevron-down",14,"currentColor",2);X&&J.appendChild(X)}}else r&&j?(q=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),J=z?Wo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=Rt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),q.append(J,D)):r?J=Rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(J=Rt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&J.classList.add("persona-hidden"));let fe=r?Rt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Rt({icon:"refresh-cw",label:"Refresh"}),ye=r?Rt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Rt({icon:"x",label:a}),Le=Rt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&Le.classList.add("persona-hidden");let Ce=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),te=t.features?.artifacts?.toolbarActions??[],ge=()=>{let X=Re.find(A=>A.id===Me)??Re[Re.length-1],M=X?.id??null,F=X?.artifactType==="markdown"?X.markdown??"":"",y=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:F,jsonPayload:y,id:M}},Y=async()=>{let X=Re.find(M=>M.id===Me)??Re[Re.length-1];try{await navigator.clipboard.writeText(ls(X))}catch{}};if(J.addEventListener("click",async()=>{let X=n?.onDocumentToolbarCopyMenuSelect;if(X&&j){let{markdown:M,jsonPayload:F,id:y}=ge();try{await X({actionId:"primary",artifactId:y,markdown:M,jsonPayload:F})}catch{}return}await Y()}),D&&x?.length){let X=()=>v.closest("[data-persona-root]")??document.body,M=()=>{$=dr({items:x.map(F=>({id:F.id,label:F.label})),onSelect:async F=>{let{markdown:y,jsonPayload:A,id:k}=ge(),W=n?.onDocumentToolbarCopyMenuSelect;try{W?await W({actionId:F,artifactId:k,markdown:y,jsonPayload:A}):F==="markdown"||F==="md"?await navigator.clipboard.writeText(y):F==="json"||F==="source"?await navigator.clipboard.writeText(A):await navigator.clipboard.writeText(y||A)}catch{}},anchor:q??D,position:"bottom-right",portal:X()})};v.isConnected?M():requestAnimationFrame(M),D.addEventListener("click",F=>{F.stopPropagation(),$?.toggle()})}fe.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}he()}),ye.addEventListener("click",()=>{f(),e.onDismiss?.()});let ae=m("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(),q?I.append(q,fe,ye):I.append(J,fe,ye),I.insertBefore(Ce,ye),I.insertBefore(Le,ye),C.append(T.element,ae,I);else{let X=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");X.append(J,Ce,Le,H),C.appendChild(P),C.appendChild(X)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let Z=m("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");p&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let ve=t.features?.artifacts?.renderTabBar,we=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ue=Zp(Z,{onSelect:X=>e.onSelect(Re[X].id)}),Te=X=>{let M=X.scrollWidth-X.clientWidth,F=M>1,y=Math.abs(X.scrollLeft);X.classList.toggle("persona-artifact-tab-fade-start",c&&F&&y>1),X.classList.toggle("persona-artifact-tab-fade-end",u&&F&&y<M-1)},Ae=0,ze=()=>{if(Ae)return;let X=()=>{Ae=0,Te(Z)};Ae=typeof requestAnimationFrame=="function"?requestAnimationFrame(X):setTimeout(X,0)};Z.addEventListener("scroll",()=>ze(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Te(Z)).observe(Z);let Ne=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),it=()=>{Ne.scrollLeft=0},Je=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(it):setTimeout(it,0)};if(l){for(let X of[Z,we])X.style.paddingLeft=l,X.style.paddingRight=l;Ne.style.padding=l}v.appendChild(C),v.appendChild(Z),v.appendChild(we),v.appendChild(Ne);let Re=[],Me=null,Ye=!1,sn=!1,Mt=!0,yt=!1,We=null,me="",Qe=null,Pe=!1,pe=X=>X.artifactType==="markdown"&&!!X.file||r?E:"rendered",ie=X=>{r||(X&&!Pe?(C.insertBefore(T.element,P),Pe=!0):!X&&Pe&&(T.element.remove(),Pe=!1))},be=()=>Me&&Re.find(X=>X.id===Me)||Re[Re.length-1],bt=()=>{let X=as(be());if(!X){Ce.replaceChildren();return}let M=te.filter(F=>F.visible===void 0||F.visible(X)).map(F=>pr(F,{documentChrome:r,onClick:()=>{let y=as(be());if(y)try{Promise.resolve(F.onClick(y)).catch(()=>{})}catch{}}}));Ce.replaceChildren(...M)},he=()=>{bt();let X=r&&Re.length<=1,M=!!ve;if(Z.classList.toggle("persona-hidden",X||M),we.classList.toggle("persona-hidden",X||!M),M&&ve){let A=Re.map(k=>k.id).join("|")+" "+(Me??"");if(A!==me){me=A;let k=ve({records:Re,selectedId:Me,onSelect:e.onSelect});we.firstElementChild!==k&&we.replaceChildren(k)}}else{ue.beforeRender(),Z.replaceChildren();let A=[],k=-1;for(let[W,V]of Re.entries()){let B=m("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");B.type="button";let U=V.artifactType==="markdown"?V.file:void 0,oe=U?Mn(U.path):V.title||V.id.slice(0,8),Ke=U?.path||V.title||oe;B.textContent=oe,B.title=Ke,B.setAttribute("aria-label",Ke),V.id===Me&&(B.classList.add("persona-bg-persona-container","persona-border-persona-border"),k=W),B.addEventListener("click",()=>e.onSelect(V.id)),Z.appendChild(B),A.push(B)}if(ue.render(A,k),k>=0&&Me!==We){We=Me;let W=A[k];typeof W.scrollIntoView=="function"&&W.scrollIntoView({block:"nearest",inline:"nearest"})}Te(Z)}let F=Me&&Re.find(A=>A.id===Me)||Re[Re.length-1];if(!F){Ne.replaceChildren(),Qe=null,ie(!1);return}let y=F.artifactType==="markdown"?F.file:void 0;if(ie(!!y),r){let A=y?oo(y):F.artifactType==="markdown"?"MD":F.component??"Component",k=(F.title||"Document").trim(),W=y?Mn(y.path):k.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ae.textContent=`${W} \xB7 ${A}`}else P.textContent=y?Mn(y.path):s;Qe?(Qe.el.parentElement!==Ne&&Ne.replaceChildren(Qe.el),Qe.update(F)):(Qe=Ma(F,{config:t,resolveViewMode:pe}),Ne.replaceChildren(Qe.el)),Ne.classList.toggle("persona-artifact-content-flush",!!Ne.querySelector(".persona-code-pre"))},de=()=>{let X=Re.length>0;if(v.classList.toggle("persona-hidden",!X),w){let y=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;X&&y&&Ye?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},fn=()=>{yt=!1,he(),de()};return{element:v,backdrop:w,update(X){let M=X.selectedId??X.artifacts[X.artifacts.length-1]?.id??null,F=M!==Me;Re=X.artifacts,Me=M,Re.length>0&&(Ye=!0),yt=!0,Mt&&fn(),F&&it()},setMobileOpen(X){Ye=X,!X&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):de()},setExpanded(X){X!==sn&&(sn=X,Je());let M=ne(X?"minimize":"maximize",16,"currentColor",2);M&&Le.replaceChildren(M);let F=X?"Collapse artifacts panel":"Expand artifacts panel";Le.setAttribute("aria-label",F),Le.title=F},setExpandToggleVisible(X){Le.classList.toggle("persona-hidden",!X)},setCopyButtonVisible(X){r||J.classList.toggle("persona-hidden",!X)},setCustomActions(X){te=X,bt()},setTabFade(X){let M=d(X);M.start===c&&M.end===u||(c=M.start,u=M.end,Te(Z))},setRenderTabBar(X){X!==ve&&(ve=X,me="",he())},setVisible(X){X!==Mt&&(Mt=X,X&&yt&&fn())}}}function Gt(t){return t?.features?.artifacts?.enabled===!0}function tu(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"),!Gt(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 ey(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 nu=["panel","seamless","detached"];function yl(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&nu.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function bl(t){return!t||!Gt(t)?!1:yl(t)==="detached"}function ws(t,e){if(!Gt(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-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),ey(t),tu(t,e);return}let n=e.features?.artifacts?.layout,o=yl(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?.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?.trim();a?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?t.style.setProperty("--persona-artifact-doc-toggle-active-border",p):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),tu(t,e)}function xs(t,e){for(let l of nu)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"),!Gt(e))return;let n=e.features?.artifacts?.layout,o=yl(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 ou(t,e){return!e||!Gt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function ty(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 ny(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 oy(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function ry(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function vl(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 ru(t,e,n,o,r,s){let a=ty(r,200),l=ry(e,n,o,200);l=Math.max(a,l);let p=ny(s);return p!==null&&(l=Math.min(l,p)),oy(t,a,l)}var su={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"}},wl=(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=su[a]??su.init;s.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let v=m("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,p.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${v.name}`;let P=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=v.label,C.appendChild(P);let H=v.type??"text",E;H==="textarea"?(E=document.createElement("textarea"),E.rows=3):(E=document.createElement("input"),E.type=H),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}-${v.name}`,E.name=v.name,E.placeholder=v.placeholder??"",v.required&&(E.required=!0),C.appendChild(E),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=m("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");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(w),u.appendChild(f),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async v=>{v.preventDefault();let C=n.formEndpoint??"/form",P=new FormData(c),H={};P.forEach((E,T)=>{H[T]=E}),H.type=a,f.disabled=!0,w.textContent="Submitting\u2026";try{let E=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let T=await E.json();w.textContent=T.message??"Thanks! We'll be in touch soon.",T.success&&T.nextPrompt&&await o.sendMessage(String(T.nextPrompt))}catch(E){w.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var xl=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()}},Cl=new xl;var au=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),sy=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),iu=(t,e,n)=>{if(!au(t)||!au(e)||sy.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]=iu(t[r],e[r],s)}return o};function lu(t,e){let n=iu(t,e,"");return ha(n)}var cu=()=>{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 ay=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},iy=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},Sl=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=ay(t),n=iy(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}},Al=t=>typeof t=="string"?t:t==null?"":String(t),Cs={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Al(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Al(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:Al(n.text)}}},du=t=>Array.isArray(t)?t.map(e=>String(e)):[],Tl=t=>{let e=new Set(du(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(du(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((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let p={action:l,message:s.message};t.emit("action:detected",p);for(let d of t.handlers)if(d)try{let c=()=>{t.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let w=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:w,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var ly=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}},cy=t=>t.map(e=>({...e,streaming:!1})),dy=t=>t.map(e=>({...e,status:"complete"})),pu=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?ly(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?cy(n.messages):void 0,artifacts:n.artifacts?dy(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)}}}};import{parse as zC,STR as UC,OBJ as jC}from"partial-json";function uu(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=_n.get(t.component);if(!s)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 fu(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 Ml(t){let e=fu(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 gu(t){let e=fu(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 py=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function mu(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:p=!0,ratingLabels:d=py}=t,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,w=document.createElement("div");w.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,f.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),w.appendChild(f);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-csat",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Satisfaction rating from 1 to 5");let H=[];for(let N=1;N<=5;N++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${N} star${N>1?"s":""}: ${d[N-1]}`),x.title=d[N-1],x.dataset.rating=String(N),x.innerHTML=`
42
+ `):""},fl=(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)"},Wh=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Rh(t,o?.previewMaxLines??3),a=n?kd(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=e?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=Oi(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=Oi(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},Kp=(t,e,n)=>{let o=dr.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=re(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},gl=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=h("div",["persona-message-bubble","persona-tool-bubble","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"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),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&&dr.has(t.id),{summary:p,previewText:d,isActive:c}=Wh(t,e),u=h("button",a?"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":"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");u.type="button",a&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let w=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),C=()=>{let D=h("span","");return D.setAttribute("data-tool-elapsed",v),D.textContent=zr(n),D},I=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:e??{},elapsed:zr(n),createElapsedElement:C});typeof I=="string"&&I.trim()?(f.textContent=I,w.appendChild(f)):I instanceof HTMLElement?w.appendChild(I):(f.textContent=p,w.appendChild(f));let B=s.loadingAnimation??"none",k=o.activeTextTemplate,M=o.completeTextTemplate,P=c?k:M,z=I instanceof HTMLElement,K=(D,F)=>{f.textContent="";let ie=n.name?.trim()||"tool",ge=ra(D,ie),Ce=0;for(let we of ge){let ee=we.styles.length>0?(()=>{let ce=h("span",we.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(ce),ce})():f;if(we.isDuration&&c)ee.appendChild(C());else{let ce=we.isDuration?zr(n):we.text;F?Ce=ro(ee,ce,Ce):ee.appendChild(document.createTextNode(ce))}}};if(!z)if(c&&B!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),B==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),P&&K(P,!1);else if(f.classList.add(`persona-tool-loading-${B}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),P)K(P,!0);else{let F=f.textContent||p;f.textContent="",ro(f,F,0)}}else P&&K(P,!1);let x=null;if(a){x=h("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",F=re(l?"chevron-up":"chevron-down",16,D,2);F?x.appendChild(F):x.textContent=l?"Hide":"Show";let ie=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(x),u.append(w,ie)}else u.append(w);let U=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let D=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:d,isActive:c,config:e??{}});Ih(U,D)||(U.textContent=d),U.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,U),r;let j=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(j.style.display=l?"":"none",o.contentBackgroundColor&&(j.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(j.style.color=o.contentTextColor),o.contentPaddingX&&(j.style.paddingLeft=o.contentPaddingX,j.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(j.style.paddingTop=o.contentPaddingY,j.style.paddingBottom=o.contentPaddingY),n.name){let D=h("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,j.appendChild(D)}if(n.args!==void 0){let D=h("div","persona-space-y-1"),F=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(F.style.color=o.labelTextColor),F.textContent="Arguments";let ie=h("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",fl(ie,o),ie.textContent=no(n.args),D.append(F,ie),j.appendChild(D)}if(n.chunks&&n.chunks.length){let D=h("div","persona-space-y-1"),F=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(F.style.color=o.labelTextColor),F.textContent="Activity";let ie=h("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",fl(ie,o),ie.textContent=n.chunks.join(""),D.append(F,ie),j.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=h("div","persona-space-y-1"),F=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(F.style.color=o.labelTextColor),F.textContent="Result";let ie=h("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",fl(ie,o),ie.textContent=no(n.result),D.append(F,ie),j.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=h("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,j.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),x){x.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",F=re(l?"chevron-up":"chevron-down",16,D,2);F?x.appendChild(F):x.textContent=l?"Hide":"Show"}j.style.display=l?"":"none",U.style.display=l?"none":U.textContent||U.childNodes.length?"":"none"})(),r.append(u,U,j),r};var Io=new Map,za=t=>{let n=(t.startsWith(Bn)?t.slice(Bn.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)},Gp=t=>t?.approval!==!1?t?.approval:void 0,Qp=(t,e)=>{let n=Gp(e)?.detailsDisplay??"collapsed";return Io.get(t)??n==="expanded"},Xp=(t,e,n)=>{let o=Gp(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=re(e?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Jp=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Qp(t,n);Xp(o,s,n),r.style.display=s?"":"none"};var Ua=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=h("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=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=h("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=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",c=re(p,20,d,2);c&&l.appendChild(c);let u=h("div","persona-flex-1 persona-min-w-0"),w=h("div","persona-flex persona-items-center persona-gap-2"),f=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",w.appendChild(f),!r){let x=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");x.setAttribute("data-approval-status",n.status),n.status==="approved"?(x.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",x.style.color="var(--persona-palette-colors-success-700, #15803d)",x.textContent="Approved"):n.status==="denied"?(x.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",x.style.color="var(--persona-palette-colors-error-700, #b91c1c)",x.textContent="Denied"):n.status==="timeout"&&(x.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",x.style.color="var(--persona-palette-colors-warning-700, #b45309)",x.textContent="Timeout"),w.appendChild(x)}u.appendChild(w);let C=n.toolType==="webmcp"||n.toolName.startsWith(Bn)?Nr(n.toolName):void 0,I=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,k=I||(B?n.description:`The assistant wants to use \u201C${C??za(n.toolName)}\u201D.`),M=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(M.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(M.style.color=o.descriptionColor),M.textContent=k,u.appendChild(M),n.reason){let x=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");x.setAttribute("data-approval-reason","true"),o?.reasonColor?x.style.color=o.reasonColor:o?.descriptionColor&&(x.style.color=o.descriptionColor);let U=h("span","persona-font-medium");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,x.appendChild(U),x.appendChild(document.createTextNode(n.reason)),u.appendChild(x)}let P=o?.detailsDisplay??"collapsed",z=!!n.description&&!B,K=z||!!n.parameters;if(P!=="hidden"&&K){let x=Qp(t.id,e),U=h("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");U.type="button",U.setAttribute("data-expand-header","true"),U.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(U.style.color=o.descriptionColor);let j=h("span");j.setAttribute("data-approval-details-label","true");let J=h("span","persona-inline-flex persona-items-center");J.setAttribute("data-approval-details-chevron","true"),U.append(j,J),Xp(U,x,e),u.appendChild(U);let D=h("div");if(D.setAttribute("data-approval-details","true"),D.style.display=x?"":"none",z){let F=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(F.style.color=o.descriptionColor),F.textContent=n.description,D.appendChild(F)}if(n.parameters){let F=h("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&&(F.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(F.style.color=o.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=no(n.parameters),D.appendChild(F)}u.appendChild(D)}if(r){let x=h("div","persona-flex persona-gap-2 persona-mt-2");x.setAttribute("data-approval-buttons","true");let U=h("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");U.type="button",U.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",U.style.color=o?.approveButtonTextColor??"#ffffff",U.setAttribute("data-approval-action","approve");let j=re("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);j&&(j.style.marginRight="4px",U.appendChild(j));let J=document.createTextNode(o?.approveLabel??"Approve");U.appendChild(J);let D=h("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");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let F=re("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);F&&(F.style.marginRight="4px",D.appendChild(F));let ie=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(ie),x.append(U,D),u.appendChild(x)}return a.append(l,u),s.appendChild(a),s};var Hh=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Yp=(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))},Ro=(t,e)=>{Yp(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)},Bh=t=>t?.approval!==!1?t?.approval:void 0,Dh=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return Io.get(t)??n==="expanded"},ml=t=>{let e=h("span","persona-approval-kbd");return e.textContent=t,e},Fh=(t,e)=>{let n=h("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Bn)?Nr(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??za(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},Nh=t=>{let e=h("div","persona-approval-resolved"),n=re("ban",15,"currentColor",2);n&&e.appendChild(n);let o=h("span","persona-approval-resolved-name");return o.textContent=t.toolName?za(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Oh=(t,e,n,o,r,s,a)=>{let l=h("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 p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,w=u&&Dh(e.id,o),f=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",C=h("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",w?"true":"false"),C.setAttribute("aria-label",w?v:f)):C.setAttribute("data-static","true");let I=h("span","persona-approval-logo"),B=re("shield-check",16,"currentColor",2);B&&I.appendChild(B),C.appendChild(I);let k=Fh(n,o);if(u){let U=h("span","persona-approval-toggle");U.setAttribute("aria-hidden","true");let j=re("chevron-down",14,"currentColor",2);j&&U.appendChild(j),k.append(" "),k.appendChild(U)}C.appendChild(k),l.appendChild(C);let M=h("div","persona-approval-body");if(u){let U=h("div","persona-approval-details");if(U.setAttribute("data-role","params"),U.hidden=!w,d){let j=h("p","persona-approval-desc");o?.descriptionColor&&(j.style.color=o.descriptionColor),j.textContent=n.description,U.appendChild(j)}if(c){let j=h("pre","persona-approval-params");o?.parameterBackgroundColor&&(j.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(j.style.color=o.parameterTextColor),j.textContent=no(n.parameters),U.appendChild(j)}M.appendChild(U)}if(n.reason){let U=h("p","persona-approval-reason");o?.reasonColor?U.style.color=o.reasonColor:o?.descriptionColor&&(U.style.color=o.descriptionColor);let j=h("span","persona-approval-reason-label");j.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,U.append(j,document.createTextNode(n.reason)),M.appendChild(U)}let P=h("div","persona-approval-actions"),z=null,K=U=>{o?.approveButtonColor&&(U.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(U.style.color=o.approveButtonTextColor)},x=h("button","persona-approval-deny");if(x.type="button",x.setAttribute("data-action","deny"),o?.denyButtonColor&&(x.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(x.style.color=o.denyButtonTextColor),x.append(o?.denyLabel??"Deny"),a){let U=h("div","persona-approval-split"),j=h("button","persona-approval-primary");j.type="button",j.setAttribute("data-action","always"),K(j),j.append(o?.approveLabel??"Always allow",ml("\u23CE"));let J=h("button","persona-approval-caret");J.type="button",J.setAttribute("data-action","toggle-menu"),J.setAttribute("aria-label","More options"),K(J);let D=re("chevron-down",15,"currentColor",2);D&&J.appendChild(D),U.append(j,J),P.append(U,x),x.append(ml("Esc"));let F=h("div","persona-approval-menu"),ie=h("button","persona-approval-menu-item");ie.type="button",ie.append("Allow once",ml("\u2318\u23CE")),F.appendChild(ie),z=Qc({anchor:U,content:F,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),ie.addEventListener("click",()=>{Ro(t,e.id),r()})}else{let U=h("button","persona-approval-primary persona-approval-primary--solo");U.type="button",U.setAttribute("data-action","allow"),K(U),U.append(o?.approveLabel??"Allow"),P.append(U,x)}return M.appendChild(P),l.appendChild(M),l.addEventListener("click",U=>{let j=U.target instanceof Element?U.target.closest("[data-action]"):null;if(!j)return;let J=j.getAttribute("data-action");if(J==="toggle-params"){let D=l.querySelector('[data-role="params"]');if(D){let F=D.hidden;D.hidden=!F,C.setAttribute("aria-expanded",F?"true":"false"),C.setAttribute("aria-label",F?v:f),Io.set(e.id,F)}return}if(J==="toggle-menu"){z?.toggle();return}if(J==="always"){Ro(t,e.id),r({remember:!0});return}if(J==="allow"){Ro(t,e.id),r();return}if(J==="deny"){Ro(t,e.id),s();return}}),l},Zp=()=>{let t=Hh();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 p=Bh(a);if(l.status!=="pending"){if(Ro(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Nh(l)}Yp(t,o.id);let d=p?.enableAlwaysAllow===!0,c=Oh(t,o,l,p,r,s,d);if(d){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let u=w=>{Xc(w)||o.id===t.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),Ro(t,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])Ro(t,o);t.latestPendingApprovalId=null}}};var eu=t=>{let e=[],n=null;return{buttons:e,render:(r,s,a,l,p,d)=>{t.innerHTML="",e.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(s?s.getMessages():[])).some(I=>I.role==="user"))return;let u=document.createDocumentFragment(),w=s?s.isStreaming():!1,f=v=>{switch(v){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'}};if(r.forEach(v=>{let C=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=v,C.disabled=w,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(C),e.push(C)}),t.appendChild(u),c){let v=JSON.stringify(r);v!==n&&(n=v,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var ps=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 us=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{}}};var _h=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),$h=new Set(["step_start","execution_start"]),zh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Uh=new Set(["step_complete","agent_turn_complete"]),jh=new Set(["flow_complete","agent_complete"]),tu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),ou=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),nn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Wo=(t,e)=>{let n=t[e];return ou(n)?n:void 0};function hl(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function ja(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function qh(t,e){return typeof e.type=="string"?e.type:t}function Vh(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 Kh(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 nu(t){let e=Wo(t,"result"),n=[Wo(t,"tokens"),Wo(t,"totalTokens"),e?Wo(e,"tokens"):void 0,Wo(t,"usage"),e?Wo(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=nn(o.output)??nn(o.outputTokens)??nn(o.completionTokens);if(r!==void 0)return r}return nn(t.outputTokens)??nn(t.completionTokens)??(e?nn(e.outputTokens)??nn(e.completionTokens):void 0)}function Gh(t){let e=Wo(t,"result");return nn(t.executionTime)??nn(t.executionTimeMs)??nn(t.execution_time)??nn(t.duration)??(e?nn(e.executionTime)??nn(e.executionTimeMs):void 0)}function Qh(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var fs=class{constructor(e=Qh){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:ja(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(!ou(n)){tu.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=qh(e,n),r=this.now();if(_h.has(o)){this.startRun(r);return}if($h.has(o)){this.run||this.startRun(r);return}if(zh.has(o)){if(!Kh(o,n))return;let s=Vh(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+hl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ja(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Uh.has(o)){if(!this.run)return;let s=this.run,a=nu(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+hl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:ja(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(jh.has(o)){if(!this.run)return;let s=this.run,a=nu(n),l=a??s.exactOutputTokens+hl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:ja(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(tu.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:Gh(n)??o-e.startedAt}};function pr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var Xh={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)"}},Jh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Yh=["flowName","stepName","reasoningText","text","name","tool","toolName"],Zh=100;function ey(t,e){let n={...Xh,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return Jh}function ty(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function ny(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 oy(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 ry(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 sy(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 ay(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function iy(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 ly(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=h("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]"),p=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function yl(t,e,n,o,r,s,a,l){let p=r.has(t.id),d=h("div","persona-border-b persona-border-persona-divider persona-text-xs");pr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=h("div",""),f=h("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");f.setAttribute("data-event-id",t.id);let v=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=re(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&v.appendChild(C);let I=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";I.textContent=B==="relative"?ty(t.timestamp,n):ny(t.timestamp);let k=null;o.showSequenceNumbers!==!1&&(k=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(e+1));let M=ey(t.type,o.badgeColors),P=h("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");P.style.backgroundColor=M.bg,P.style.color=M.text,P.style.borderColor=M.text+"50",P.textContent=t.type;let z=o.descriptionFields??Yh,K=oy(t.payload,z),x=null;K&&(x=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),x.textContent=K);let U=h("div","persona-flex-1 persona-min-w-0"),j=h("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"),J=re("clipboard","12px","currentColor",1.5);return J&&j.appendChild(J),j.addEventListener("click",async D=>{D.stopPropagation(),await ry(sy(t)),j.innerHTML="";let F=re("check","12px","currentColor",1.5);F&&j.appendChild(F),setTimeout(()=>{j.innerHTML="";let ie=re("clipboard","12px","currentColor",1.5);ie&&j.appendChild(ie)},1500)}),f.appendChild(v),f.appendChild(I),k&&f.appendChild(k),f.appendChild(P),x&&f.appendChild(x),f.appendChild(U),f.appendChild(j),w.appendChild(f),p&&w.appendChild(ly(t,a,l)),w}}function ru(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return f();function f(){let v=u.classNames,C=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");pr(C,v?.panel);let I=[],B="",k="",M=null,P=[],z={},K=0,x=Ta(),U=0,j=0,J=!1,D=null,F=!1,ie=0,ge=new Set,Ce=new Map,we="",ee="",ce=null,Y,ae,Z,he,ye=null,pe=null,Te=null;function Ae(){let H=h("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),$=h("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(pr($,v?.headerBar),a){pe=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),pe.style.cursor="help",ye=h("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"),ye.textContent="-- tok/s",Te=h("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"),Te.style.display="none",Te.style.pointerEvents="none";let Xe=pe,lo=Te,co=()=>{if(!lo.textContent)return;let bs=Xe.getBoundingClientRect(),Gt=H.getBoundingClientRect();lo.style.left=`${bs.left-Gt.left}px`,lo.style.top=`${bs.bottom-Gt.top+4}px`,lo.style.display="block"},Ka=()=>{lo.style.display="none"};pe.addEventListener("mouseenter",co),pe.addEventListener("mouseleave",Ka),pe.appendChild(ye)}let se=h("div","persona-flex-1");Y=h("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 je=h("option","");je.value="",je.textContent="All events (0)",Y.appendChild(je),ae=h("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"),ae.type="button",ae.title="Copy All";let rt=re("clipboard-copy","12px","currentColor",1.5);rt&&ae.appendChild(rt);let V=h("span","persona-event-copy-all persona-text-xs");V.textContent="Copy All",ae.appendChild(V),pe&&$.appendChild(pe),$.appendChild(se),$.appendChild(Y),$.appendChild(ae);let $e=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");pr($e,v?.searchBar);let Se=re("search","14px","var(--persona-muted, #9ca3af)",1.5),Pe=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Se&&Pe.appendChild(Se),Z=h("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"),pr(Z,v?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",he=h("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"),he.type="button",he.style.display="none";let Le=re("x","12px","currentColor",2);return Le&&he.appendChild(Le),$e.appendChild(Pe),$e.appendChild(Z),$e.appendChild(he),H.appendChild($),H.appendChild($e),Te&&H.appendChild(Te),H}let Oe,Fe=s.find(H=>H.renderEventStreamToolbar);Fe?.renderEventStreamToolbar&&r?Oe=Fe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ae(),eventCount:e.getSize(),filteredCount:0,onFilterChange:$=>{B=$,ke(),be()},onSearchChange:$=>{k=$,ke(),be()}})??Ae():Oe=Ae();let ot=h("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");ot.style.display="none";function Ge(){if(!a||!ye||!pe)return;let H=a(),$=ay(H);ye.textContent=$;let se=iy(H);Te&&(Te.textContent=se,se||(Te.style.display="none")),pe.setAttribute("aria-label",se?`Throughput: ${$}, ${se}`:`Throughput: ${$}`)}let Ie=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Me=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Me.style.height="100%";let Qe=h("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");pr(Qe,v?.scrollIndicator),Qe.style.display="none",Qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let on=re(d,"14px","currentColor",2);on&&Qe.appendChild(on);let Tt=h("span","");Tt.textContent=c,Qe.appendChild(Tt);let yt=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");yt.style.display="none",Ie.appendChild(Me),Ie.appendChild(yt),Ie.appendChild(Qe),C.setAttribute("tabindex","0"),C.appendChild(Oe),C.appendChild(ot),C.appendChild(Ie);function Re(){let H=e.getAll(),$={};for(let $e of H)$[$e.type]=($[$e.type]||0)+1;let se=Object.keys($).sort(),je=se.length!==P.length||!se.every(($e,Se)=>$e===P[Se]),Ee=!je&&se.some($e=>$[$e]!==z[$e]),rt=H.length!==Object.values(z).reduce(($e,Se)=>$e+Se,0);if(!je&&!Ee&&!rt||(P=se,z=$,!Y))return;let V=Y.value;if(Y.options[0].textContent=`All events (${H.length})`,je){for(;Y.options.length>1;)Y.remove(1);for(let $e of se){let Se=h("option","");Se.value=$e,Se.textContent=`${$e} (${$[$e]||0})`,Y.appendChild(Se)}V&&se.includes(V)?Y.value=V:V&&(Y.value="",B="")}else for(let $e=1;$e<Y.options.length;$e++){let Se=Y.options[$e];Se.textContent=`${Se.value} (${$[Se.value]||0})`}}function me(){let H=e.getAll();if(B&&(H=H.filter($=>$.type===B)),k){let $=k.toLowerCase();H=H.filter(se=>se.type.toLowerCase().includes($)||se.payload.toLowerCase().includes($))}return H}function Ve(){return B!==""||k!==""}function ke(){K=0,U=0,x.resume(),Qe.style.display="none"}function ue(H){ge.has(H)?ge.delete(H):ge.add(H),ce=H;let $=Me.scrollTop,se=x.isFollowing();F=!0,x.pause(),be(),Me.scrollTop=$,se&&x.resume(),F=!1}function le(){return ao(Me,50)}function be(){j=Date.now(),J=!1,Ge(),Re();let H=e.getEvictedCount();H>0?(ot.textContent=`${H.toLocaleString()} older events truncated`,ot.style.display=""):ot.style.display="none",I=me();let $=I.length,se=e.getSize()>0;$===0&&se&&Ve()?(yt.textContent=k?`No events matching '${k}'`:"No events matching filter",yt.style.display="",Me.style.display="none"):(yt.style.display="none",Me.style.display=""),ae&&(ae.title=Ve()?`Copy Filtered (${$})`:"Copy All"),p&&!x.isFollowing()&&$>K&&(U+=$-K,Tt.textContent=c?`${c}${U>0?` (${U})`:""}`:"",Qe.style.display=""),K=$;let je=e.getAll(),Ee=je.length>0?je[0].timestamp:0,rt=new Set(I.map(Se=>Se.id));for(let Se of ge)rt.has(Se)||ge.delete(Se);let V=B!==we||k!==ee,$e=Ce.size===0&&I.length>0;if(V||$e||I.length===0){Me.innerHTML="",Ce.clear();let Se=document.createDocumentFragment();for(let Pe=0;Pe<I.length;Pe++){let Le=yl(I[Pe],Pe,Ee,u,ge,ue,s,r);Ce.set(I[Pe].id,Le),Se.appendChild(Le)}Me.appendChild(Se),we=B,ee=k,ce=null}else{if(ce!==null){let Pe=Ce.get(ce);if(Pe&&Pe.parentNode===Me){let Le=I.findIndex(Xe=>Xe.id===ce);if(Le>=0){let Xe=yl(I[Le],Le,Ee,u,ge,ue,s,r);Me.insertBefore(Xe,Pe),Pe.remove(),Ce.set(ce,Xe)}}ce=null}let Se=new Set(I.map(Pe=>Pe.id));for(let[Pe,Le]of Ce)Se.has(Pe)||(Le.remove(),Ce.delete(Pe));for(let Pe=0;Pe<I.length;Pe++){let Le=I[Pe];if(!Ce.has(Le.id)){let Xe=yl(Le,Pe,Ee,u,ge,ue,s,r);Ce.set(Le.id,Xe),Me.appendChild(Xe)}}}x.isFollowing()&&(Me.scrollTop=Me.scrollHeight)}function bt(){if(Date.now()-j>=Zh){D!==null&&(cancelAnimationFrame(D),D=null),be();return}J||(J=!0,D=requestAnimationFrame(()=>{D=null,be()}))}let ve=(H,$)=>{if(!ae)return;ae.innerHTML="";let se=re(H,"12px","currentColor",1.5);se&&ae.appendChild(se);let je=h("span","persona-text-xs");je.textContent="Copy All",ae.appendChild(je),setTimeout(()=>{ae.innerHTML="";let Ee=re("clipboard-copy","12px","currentColor",1.5);Ee&&ae.appendChild(Ee);let rt=h("span","persona-text-xs");rt.textContent="Copy All",ae.appendChild(rt),ae.disabled=!1},$)},de=async()=>{if(ae){ae.disabled=!0;try{let H;Ve()?H=I:n?(H=await n(),H.length===0&&(H=e.getAll())):H=e.getAll();let $=H.map(se=>{try{return JSON.parse(se.payload)}catch{return se.payload}});await navigator.clipboard.writeText(JSON.stringify($,null,2)),ve("check",1500)}catch{ve("x",1500)}}},un=()=>{Y&&(B=Y.value,ke(),be())},X=()=>{!Z||!he||(he.style.display=Z.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{k=Z.value,ke(),be()},150))},T=()=>{!Z||!he||(Z.value="",k="",he.style.display="none",M&&clearTimeout(M),ke(),be())},O=()=>{if(F)return;let H=Me.scrollTop,{action:$,nextLastScrollTop:se}=Ma({following:x.isFollowing(),currentScrollTop:H,lastScrollTop:ie,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ie=se,$==="resume"?(x.resume(),U=0,Qe.style.display="none"):$==="pause"&&(x.pause(),p&&(Tt.textContent=c,Qe.style.display=""))},y=H=>{let $=Ea({following:x.isFollowing(),deltaY:H.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});$==="pause"?(x.pause(),p&&(Tt.textContent=c,Qe.style.display="")):$==="resume"&&(x.resume(),U=0,Qe.style.display="none")},S=()=>{p&&(Me.scrollTop=Me.scrollHeight,x.resume(),U=0,Qe.style.display="none")},E=H=>{let $=H.target;if(!$||$.closest("button"))return;let se=$.closest("[data-event-id]");if(!se)return;let je=se.getAttribute("data-event-id");je&&ue(je)},W=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),Z?.focus(),Z?.select();return}H.key==="Escape"&&(Z&&document.activeElement===Z?(T(),Z.blur(),C.focus()):o&&o())};ae&&ae.addEventListener("click",de),Y&&Y.addEventListener("change",un),Z&&Z.addEventListener("input",X),he&&he.addEventListener("click",T),Me.addEventListener("scroll",O),Me.addEventListener("wheel",y,{passive:!0}),Me.addEventListener("click",E),Qe.addEventListener("click",S),C.addEventListener("keydown",W);function q(){M&&clearTimeout(M),D!==null&&(cancelAnimationFrame(D),D=null),J=!1,Ce.clear(),ae&&ae.removeEventListener("click",de),Y&&Y.removeEventListener("change",un),Z&&Z.removeEventListener("input",X),he&&he.removeEventListener("click",T),Me.removeEventListener("scroll",O),Me.removeEventListener("wheel",y),Me.removeEventListener("click",E),Qe.removeEventListener("click",S),C.removeEventListener("keydown",W)}return{element:C,update:bt,destroy:q}}}function su(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=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let w=u;return s.findIndex(f=>f===w||f.contains(w))},d=u=>{let w=p(u.target);if(w<0)return;let f=w;if(u.key===r)f=Math.min(w+1,s.length-1);else if(u.key===o)f=Math.max(w-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==w&&e.onSelect(f)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return t.addEventListener("keydown",d),t.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((f,v)=>{f.setAttribute("role","tab");let C=v===w;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||w<0&&v===0?0:-1}),a){let f=(w>=0?u[w]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){t.removeEventListener("keydown",d),t.removeEventListener("focusin",c)}}}function au(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(),p=n?.tabFadeSize?.trim(),d=X=>({start:X===!1?!1:typeof X=="object"&&X?X.start!==!1:!0,end:X===!1?!1:typeof X=="object"&&X?X.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),F?.hide()};w&&w.addEventListener("click",()=>{f(),e.onDismiss?.()});let v=h("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");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let C=h("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 I=h("span","persona-text-xs persona-font-medium persona-truncate");I.textContent=s;let B=Rt({icon:"x",label:a});B.addEventListener("click",()=>{f(),e.onDismiss?.()});let k="rendered",M=wa({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:X=>{k=X==="source"?"source":"rendered",ve()}}),P=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,K=n?.documentToolbarShowCopyChevron===!0,x=n?.documentToolbarCopyMenuItems,U=!!(K&&x&&x.length>0),j=null,J,D=null,F=null;if(r&&(z||K)&&!U){if(J=z?Lo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),K){let X=re("chevron-down",14,"currentColor",2);X&&J.appendChild(X)}}else r&&U?(j=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),J=z?Lo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=Rt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),j.append(J,D)):r?J=Rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(J=Rt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&J.classList.add("persona-hidden"));let ie=r?Rt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Rt({icon:"refresh-cw",label:"Refresh"}),ge=r?Rt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Rt({icon:"x",label:a}),Ce=Rt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ce.classList.add("persona-hidden");let we=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ee=t.features?.artifacts?.toolbarActions??[],ce=()=>{let X=Ie.find(S=>S.id===Me)??Ie[Ie.length-1],T=X?.id??null,O=X?.artifactType==="markdown"?X.markdown??"":"",y=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:O,jsonPayload:y,id:T}},Y=async()=>{let X=Ie.find(T=>T.id===Me)??Ie[Ie.length-1];try{await navigator.clipboard.writeText(ns(X))}catch{}};if(J.addEventListener("click",async()=>{let X=n?.onDocumentToolbarCopyMenuSelect;if(X&&U){let{markdown:T,jsonPayload:O,id:y}=ce();try{await X({actionId:"primary",artifactId:y,markdown:T,jsonPayload:O})}catch{}return}await Y()}),D&&x?.length){let X=()=>v.closest("[data-persona-root]")??document.body,T=()=>{F=ar({items:x.map(O=>({id:O.id,label:O.label})),onSelect:async O=>{let{markdown:y,jsonPayload:S,id:E}=ce(),W=n?.onDocumentToolbarCopyMenuSelect;try{W?await W({actionId:O,artifactId:E,markdown:y,jsonPayload:S}):O==="markdown"||O==="md"?await navigator.clipboard.writeText(y):O==="json"||O==="source"?await navigator.clipboard.writeText(S):await navigator.clipboard.writeText(y||S)}catch{}},anchor:j??D,position:"bottom-right",portal:X()})};v.isConnected?T():requestAnimationFrame(T),D.addEventListener("click",O=>{O.stopPropagation(),F?.toggle()})}ie.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ve()}),ge.addEventListener("click",()=>{f(),e.onDismiss?.()});let ae=h("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(),j?P.append(j,ie,ge):P.append(J,ie,ge),P.insertBefore(we,ge),P.insertBefore(Ce,ge),C.append(M.element,ae,P);else{let X=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");X.append(J,we,Ce,B),C.appendChild(I),C.appendChild(X)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let Z=h("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");p&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let he=t.features?.artifacts?.renderTabBar,ye=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),pe=su(Z,{onSelect:X=>e.onSelect(Ie[X].id)}),Te=X=>{let T=X.scrollWidth-X.clientWidth,O=T>1,y=Math.abs(X.scrollLeft);X.classList.toggle("persona-artifact-tab-fade-start",c&&O&&y>1),X.classList.toggle("persona-artifact-tab-fade-end",u&&O&&y<T-1)},Ae=0,Oe=()=>{if(Ae)return;let X=()=>{Ae=0,Te(Z)};Ae=typeof requestAnimationFrame=="function"?requestAnimationFrame(X):setTimeout(X,0)};Z.addEventListener("scroll",()=>Oe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Te(Z)).observe(Z);let Fe=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),ot=()=>{Fe.scrollLeft=0},Ge=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(ot):setTimeout(ot,0)};if(l){for(let X of[Z,ye])X.style.paddingLeft=l,X.style.paddingRight=l;Fe.style.padding=l}v.appendChild(C),v.appendChild(Z),v.appendChild(ye),v.appendChild(Fe);let Ie=[],Me=null,Qe=!1,on=!1,Tt=!0,yt=!1,Re=null,me="",Ve=null,ke=!1,ue=X=>X.artifactType==="markdown"&&!!X.file||r?k:"rendered",le=X=>{r||(X&&!ke?(C.insertBefore(M.element,I),ke=!0):!X&&ke&&(M.element.remove(),ke=!1))},be=()=>Me&&Ie.find(X=>X.id===Me)||Ie[Ie.length-1],bt=()=>{let X=es(be());if(!X){we.replaceChildren();return}let T=ee.filter(O=>O.visible===void 0||O.visible(X)).map(O=>ir(O,{documentChrome:r,onClick:()=>{let y=es(be());if(y)try{Promise.resolve(O.onClick(y)).catch(()=>{})}catch{}}}));we.replaceChildren(...T)},ve=()=>{bt();let X=r&&Ie.length<=1,T=!!he;if(Z.classList.toggle("persona-hidden",X||T),ye.classList.toggle("persona-hidden",X||!T),T&&he){let S=Ie.map(E=>E.id).join("|")+" "+(Me??"");if(S!==me){me=S;let E=he({records:Ie,selectedId:Me,onSelect:e.onSelect});ye.firstElementChild!==E&&ye.replaceChildren(E)}}else{pe.beforeRender(),Z.replaceChildren();let S=[],E=-1;for(let[W,q]of Ie.entries()){let H=h("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");H.type="button";let $=q.artifactType==="markdown"?q.file:void 0,se=$?Sn($.path):q.title||q.id.slice(0,8),je=$?.path||q.title||se;H.textContent=se,H.title=je,H.setAttribute("aria-label",je),q.id===Me&&(H.classList.add("persona-bg-persona-container","persona-border-persona-border"),E=W),H.addEventListener("click",()=>e.onSelect(q.id)),Z.appendChild(H),S.push(H)}if(pe.render(S,E),E>=0&&Me!==Re){Re=Me;let W=S[E];typeof W.scrollIntoView=="function"&&W.scrollIntoView({block:"nearest",inline:"nearest"})}Te(Z)}let O=Me&&Ie.find(S=>S.id===Me)||Ie[Ie.length-1];if(!O){Fe.replaceChildren(),Ve=null,le(!1);return}let y=O.artifactType==="markdown"?O.file:void 0;if(le(!!y),r){let S=y?oo(y):O.artifactType==="markdown"?"MD":O.component??"Component",E=(O.title||"Document").trim(),W=y?Sn(y.path):E.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ae.textContent=`${W} \xB7 ${S}`}else I.textContent=y?Sn(y.path):s;Ve?(Ve.el.parentElement!==Fe&&Fe.replaceChildren(Ve.el),Ve.update(O)):(Ve=Aa(O,{config:t,resolveViewMode:ue}),Fe.replaceChildren(Ve.el)),Fe.classList.toggle("persona-artifact-content-flush",!!Fe.querySelector(".persona-code-pre"))},de=()=>{let X=Ie.length>0;if(v.classList.toggle("persona-hidden",!X),w){let y=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;X&&y&&Qe?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},un=()=>{yt=!1,ve(),de()};return{element:v,backdrop:w,update(X){let T=X.selectedId??X.artifacts[X.artifacts.length-1]?.id??null,O=T!==Me;Ie=X.artifacts,Me=T,Ie.length>0&&(Qe=!0),yt=!0,Tt&&un(),O&&ot()},setMobileOpen(X){Qe=X,!X&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):de()},setExpanded(X){X!==on&&(on=X,Ge());let T=re(X?"minimize":"maximize",16,"currentColor",2);T&&Ce.replaceChildren(T);let O=X?"Collapse artifacts panel":"Expand artifacts panel";Ce.setAttribute("aria-label",O),Ce.title=O},setExpandToggleVisible(X){Ce.classList.toggle("persona-hidden",!X)},setCopyButtonVisible(X){r||J.classList.toggle("persona-hidden",!X)},setCustomActions(X){ee=X,bt()},setTabFade(X){let T=d(X);T.start===c&&T.end===u||(c=T.start,u=T.end,Te(Z))},setRenderTabBar(X){X!==he&&(he=X,me="",ve())},setVisible(X){X!==Tt&&(Tt=X,X&&yt&&un())}}}function Kt(t){return t?.features?.artifacts?.enabled===!0}function iu(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"),!Kt(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 cy(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 lu=["panel","seamless","detached"];function bl(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&lu.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function vl(t){return!t||!Kt(t)?!1:bl(t)==="detached"}function gs(t,e){if(!Kt(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-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),cy(t),iu(t,e);return}let n=e.features?.artifacts?.layout,o=bl(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?.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?.trim();a?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?t.style.setProperty("--persona-artifact-doc-toggle-active-border",p):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),iu(t,e)}function ms(t,e){for(let l of lu)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"),!Kt(e))return;let n=e.features?.artifacts?.layout,o=bl(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 cu(t,e){return!e||!Kt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function dy(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 py(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 uy(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function fy(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function wl(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 du(t,e,n,o,r,s){let a=dy(r,200),l=fy(e,n,o,200);l=Math.max(a,l);let p=py(s);return p!==null&&(l=Math.min(l,p)),uy(t,a,l)}var pu={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"}},xl=(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=pu[a]??pu.init;s.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),d=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let v=h("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,p.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let C=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${v.name}`;let I=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");I.textContent=v.label,C.appendChild(I);let B=v.type??"text",k;B==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=B),k.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",k.id=`${e.id}-${a}-${v.name}`,k.name=v.name,k.placeholder=v.placeholder??"",v.required&&(k.required=!0),C.appendChild(k),c.appendChild(C)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=h("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");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(w),u.appendChild(f),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async v=>{v.preventDefault();let C=n.formEndpoint??"/form",I=new FormData(c),B={};I.forEach((k,M)=>{B[M]=k}),B.type=a,f.disabled=!0,w.textContent="Submitting\u2026";try{let k=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let M=await k.json();w.textContent=M.message??"Thanks! We'll be in touch soon.",M.success&&M.nextPrompt&&await o.sendMessage(String(M.nextPrompt))}catch(k){w.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Cl=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()}},Al=new Cl;var uu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),gy=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),fu=(t,e,n)=>{if(!uu(t)||!uu(e)||gy.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]=fu(t[r],e[r],s)}return o};function gu(t,e){let n=fu(t,e,"");return fa(n)}var mu=()=>{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 my=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},hy=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},Tl=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=my(t),n=hy(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}},Sl=t=>typeof t=="string"?t:t==null?"":String(t),hs={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Sl(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Sl(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:Sl(n.text)}}},hu=t=>Array.isArray(t)?t.map(e=>String(e)):[],Ml=t=>{let e=new Set(hu(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(hu(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((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let p={action:l,message:s.message};t.emit("action:detected",p);for(let d of t.handlers)if(d)try{let c=()=>{t.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let w=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:w,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var yy=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}},by=t=>t.map(e=>({...e,streaming:!1})),vy=t=>t.map(e=>({...e,status:"complete"})),yu=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?yy(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?by(n.messages):void 0,artifacts:n.artifacts?vy(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)}}}};import{parse as nA,STR as oA,OBJ as rA}from"partial-json";function bu(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=On.get(t.component);if(!s)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 vu(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 El(t){let e=vu(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 wu(t){let e=vu(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 wy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function xu(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:p=!0,ratingLabels:d=wy}=t,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,w=document.createElement("div");w.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,f.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),w.appendChild(f);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let K=1;K<=5;K++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${K} star${K>1?"s":""}: ${d[K-1]}`),x.title=d[K-1],x.dataset.rating=String(K),x.innerHTML=`
43
43
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
44
44
  <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>
45
45
  </svg>
46
- `,x.addEventListener("click",()=>{u=N,H.forEach((j,q)=>{let J=q<N;j.classList.toggle("selected",J),j.setAttribute("aria-checked",q===N-1?"true":"false")})}),H.push(x),P.appendChild(x)}w.appendChild(P);let E=null;if(p){let N=document.createElement("div");N.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"),N.appendChild(E),w.appendChild(N)}let T=document.createElement("div");T.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=l,I.addEventListener("click",()=>{n?.(),c.remove()});let z=document.createElement("button");return z.type="button",z.className="persona-feedback-btn persona-feedback-btn-submit",z.textContent=a,z.addEventListener("click",async()=>{if(u===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let N=E?.value.trim()||void 0;await e(u,N),c.remove()}catch(N){z.disabled=!1,z.textContent=a,console.error("[CSAT Feedback] Failed to submit:",N)}}),T.appendChild(I),T.appendChild(z),w.appendChild(T),c.appendChild(w),c}function hu(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:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let w=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let P=document.createElement("p");P.className="persona-feedback-subtitle",P.textContent=r,v.appendChild(P),f.appendChild(v);let H=document.createElement("div");H.className="persona-feedback-rating persona-feedback-rating-nps",H.setAttribute("role","radiogroup"),H.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=d;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=c,E.appendChild(T),E.appendChild(I);let z=document.createElement("div");z.className="persona-feedback-numbers";let N=[];for(let D=0;D<=10;D++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${D} out of 10`),$.textContent=String(D),$.dataset.rating=String(D),D<=6?$.classList.add("persona-feedback-detractor"):D<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{w=D,N.forEach((fe,ye)=>{fe.classList.toggle("selected",ye===D),fe.setAttribute("aria-checked",ye===D?"true":"false")})}),N.push($),z.appendChild($)}H.appendChild(E),H.appendChild(z),f.appendChild(H);let x=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),D.appendChild(x),f.appendChild(D)}let j=document.createElement("div");j.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=l,q.addEventListener("click",()=>{n?.(),u.remove()});let J=document.createElement("button");return J.type="button",J.className="persona-feedback-btn persona-feedback-btn-submit",J.textContent=a,J.addEventListener("click",async()=>{if(w===null){z.classList.add("persona-feedback-shake"),setTimeout(()=>z.classList.remove("persona-feedback-shake"),500);return}J.disabled=!0,J.textContent="Submitting...";try{let D=x?.value.trim()||void 0;await e(w,D),u.remove()}catch(D){J.disabled=!1,J.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),j.appendChild(q),j.appendChild(J),f.appendChild(j),u.appendChild(f),u}var hr="persona-chat-history",uy=30*1e3,fy=641,gy={"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 my(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=gy[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 Ga(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 hy(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 yy(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var El=t=>!t||typeof t!="object"?{}:{...t},yu=t=>t.map(e=>({...e,streaming:!1})),bu=(t,e,n)=>{let o=t?.markdown?Js(t.markdown):null,r=Ys(t?.sanitize);return 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."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(e){let c=e.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Hn()!==null,d;if(t?.postprocessMessage){let c=t.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Zc(a):a,u=o(c);d=r&&p?r(u):u}else d=Zn(a);return d}};function vu(t){let e=m("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=ne(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=m("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var by=(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},vy=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:by(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),wu=(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=ha(e),r=Cl.getForInstance(o.plugins),{plugin:s,teardown:a}=Kp();o.components&&_n.registerAll(o.components);let l=cu(),d=o.persistState===!1?null:o.storageAdapter??pu(),c={},u=null,w=!1,f=i=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(i);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:b}=g;return b&&(w=!0),h}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")u=i.then(g=>f(g??{messages:[],metadata:{}}));else{let h=f(i??{messages:[],metadata:{}});h.metadata&&(c=El(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let v=()=>c,C=i=>{c=i({...c})??{},ui()},P=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sl],H=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Cs.message,Cs.messageAndClick],E=Tl({parsers:P,handlers:H,getSessionMetadata:v,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null});E.syncFromMetadata();let T=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,N=I,x=T,j=o.layout?.header?.layout,q=!1,J=()=>gs(o),D=()=>T||J(),$=J()?!1:T?I:!0,fe=!1,ye=null,Le=()=>{fe=!0,ye&&clearTimeout(ye),ye=setTimeout(()=>{fe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),fe=!1)},1e4)},Ce=bu(o,E,Le),te=o.features?.showReasoning??!0,ge=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,ae=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},we=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ue=Y?new bs(we):null,Te=o.features?.eventStream?.maxEvents??2e3,Ae=Y?new ys(Te,ue):null,ze=Y?new vs:null,Ne=null,it=!1,Je=null,Re=0;ue?.open().then(()=>Ae?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Me={onCopy:i=>{l.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{l.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(i)}},Ye=o.statusIndicator??{},sn=i=>i==="idle"?Ye.idleText??It.idle:i==="connecting"?Ye.connectingText??It.connecting:i==="connected"?Ye.connectedText??It.connected:i==="error"?Ye.errorText??It.error:i==="paused"?Ye.pausedText??It.paused:i==="resuming"?Ye.resumingText??It.resuming:It[i];function Mt(i,g,h,b){if(b==="idle"&&h.idleLink){i.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=g,S.style.color="inherit",S.style.textDecoration="none",i.appendChild(S)}else i.textContent=g}let yt=Hp({config:o,showClose:D()}),{wrapper:We,panel:me,pillRoot:Qe}=yt.shell,Pe=yt.panelElements,{container:pe,body:ie,messagesWrapper:be,suggestions:bt,textarea:he,sendButton:de,sendButtonWrapper:fn,composerForm:X,statusText:M,introTitle:F,introSubtitle:y,closeButton:A,iconHolder:k,headerTitle:W,headerSubtitle:V,header:B,footer:U,actionsRow:oe,rightActions:Ke}=Pe,Ee=Pe.leftActions,lt=Pe.setSendButtonMode,K=Pe.micButton,_e=Pe.micButtonWrapper,ke=Pe.attachmentButton,Be=Pe.attachmentButtonWrapper,Ie=Pe.attachmentInput,Ze=Pe.attachmentPreviewsContainer;pe.classList.add("persona-relative"),ie.classList.add("persona-relative");let co=12,po=()=>ae.label??"",Xa=()=>ae.iconName??"arrow-down",Ss=()=>ae.enabled!==!1,Qt=()=>Z.mode??"anchor-top",$n=()=>Qt()==="follow"||Qt()==="anchor-top"&&Mr,Bl=()=>Z.anchorTopOffset??16,Ru=()=>Z.restorePosition??"bottom",Hl=()=>Z.pauseOnInteraction===!0,Dl=()=>Z.showActivityWhilePinned!==!1,Nl=()=>Z.announce===!0,Lt=m("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");Lt.type="button",Lt.style.display="none",Lt.setAttribute("data-persona-scroll-to-bottom","true");let br=m("span","persona-flex persona-items-center"),Ja=m("span",""),uo=m("span","");uo.setAttribute("data-persona-scroll-to-bottom-count",""),uo.style.display="none",Lt.append(br,Ja,uo),pe.appendChild(Lt);let zn=m("div","persona-stream-anchor-spacer");zn.setAttribute("aria-hidden","true"),zn.setAttribute("data-persona-anchor-spacer",""),zn.style.flexShrink="0",zn.style.pointerEvents="none",zn.style.height="0px",ie.appendChild(zn);let fo=m("div","persona-sr-only");fo.setAttribute("aria-live","polite"),fo.setAttribute("aria-atomic","true"),fo.setAttribute("role","status"),fo.setAttribute("data-persona-live-region",""),Object.assign(fo.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(fo);let vr=null,Ts=null,Fl=i=>{!Nl()||!i||(Ts=i,vr===null&&(vr=setTimeout(()=>{vr=null,Ts&&Nl()&&(fo.textContent=Ts),Ts=null},400)))},Fo=()=>{let g=U.style.display==="none"?0:U.offsetHeight;Lt.style.bottom=`${g+co}px`};Fo();let Ol=()=>{let i=!!po();Lt.setAttribute("aria-label",po()||"Jump to latest"),Lt.title=po(),Lt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),br.innerHTML="";let g=ne(Xa(),"14px","currentColor",2);g?(br.appendChild(g),br.style.display=""):br.style.display="none",Ja.textContent=po(),Ja.style.display=i?"":"none"};Ol();let St=null,Yt=null,_l=null,$l=r.find(i=>i.renderHeader);if($l?.renderHeader){let i=$l.renderHeader({config:o,defaultRenderer:()=>{let g=Bo({config:o,showClose:D()});return ms(pe,g,o),g.header},onClose:()=>ft(!1,"user")});if(i){let g=pe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),B=i,yt.header.element=i)}}let Ya=()=>{if(!Ae)return;if(it=!0,!Ne&&Ae&&(Ne=Yp({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>wr(),config:o,plugins:r,getThroughput:()=>ze?.getMetric()??{status:"idle"}})),Ne&&(ie.style.display="none",U.parentNode?.insertBefore(Ne.element,U),Ne.update()),st){st.style.boxShadow=`inset 0 0 0 1.5px ${Kt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(h=>h&&st.classList.add(h))}let i=()=>{if(!it)return;let g=Date.now();g-Re>=200&&(Ne?.update(),Re=g),Je=requestAnimationFrame(i)};Re=0,Je=requestAnimationFrame(i),en(),l.emit("eventStream:opened",{timestamp:Date.now()})},wr=()=>{if(it){if(it=!1,Ne&&Ne.element.remove(),ie.style.display="",st){st.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&st.classList.remove(g))}Je!==null&&(cancelAnimationFrame(Je),Je=null),en(),l.emit("eventStream:closed",{timestamp:Date.now()})}},st=null;if(Y){let i=o.features?.eventStream?.classNames,g="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=m("button",g),st.style.width="28px",st.style.height="28px",st.style.color=Kt.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let h=ne("activity","18px","currentColor",1.5);h&&st.appendChild(h);let b=Pe.clearChatButtonWrapper,S=Pe.closeButtonWrapper,L=b||S;L&&L.parentNode===B?B.insertBefore(st,L):B.appendChild(st),st.addEventListener("click",()=>{it?wr():Ya()})}let Wu=i=>{let g=o.attachments;if(!g?.enabled)return;let h=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!h){h=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let S=i.querySelector("[data-persona-composer-form]");S?.parentNode?S.parentNode.insertBefore(h,S):i.insertBefore(h,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let S=m("input");S.type="file",S.setAttribute("data-persona-composer-attachment-input",""),S.accept=(g.allowedTypes??Fn).join(","),S.multiple=(g.maxFiles??4)>1,S.style.display="none",S.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),i.appendChild(S)}},zl=r.find(i=>i.renderComposer);if(zl?.renderComposer){let i=o.composer,g=zl.renderComposer({config:o,defaultRenderer:()=>ja({config:o}).footer,onSubmit:h=>{if(!_||_.isStreaming())return;let b=h.trim(),S=St?.hasAttachments()??!1;if(!b&&!S)return;yc();let L;S&&(L=[],L.push(...St.getContentParts()),b&&L.push(or(b))),_.sendMessage(b,{contentParts:L}),S&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ie?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{_l?.()}:void 0});g&&(yt.replaceComposer(g),U=yt.composer.footer)}let Bu=i=>{let g=(...le)=>{for(let se of le){let xe=i.querySelector(se);if(xe)return xe}return null},h=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),S=i.querySelector("[data-persona-composer-submit]"),L=i.querySelector("[data-persona-composer-mic]"),Q=i.querySelector("[data-persona-composer-status]");h&&(X=h),b&&(he=b),S&&(de=S),L&&(K=L,_e=L.parentElement),Q&&(M=Q);let O=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(bt=O);let G=g("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(ke=G,Be=G.parentElement),Ie=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Ze=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(oe=re),Ee=g(".persona-widget-composer__left-actions")};Wu(U),Bu(U);let Un=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Un&&(be.style.maxWidth=Un,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%"),Un&&X&&!J()&&(X.style.maxWidth=Un,X.style.marginLeft="auto",X.style.marginRight="auto"),Un&&bt&&!J()&&(bt.style.maxWidth=Un,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Un&&Ze&&!J()&&(Ze.style.maxWidth=Un,Ze.style.marginLeft="auto",Ze.style.marginRight="auto"),o.attachments?.enabled&&Ie&&Ze){St=ts.fromConfig(o.attachments),St.setPreviewsContainer(Ze),Ie.addEventListener("change",h=>{let b=h.target;St?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,g=vu(i);pe.appendChild(g)}let Hu=()=>Yt?.prefetch();if(o.contextMentions?.enabled&&he&&(Yt=Ud({config:o,textarea:he,anchor:X??he,getMessages:()=>_.getMessages(),liveRegionHost:pe}),Yt)){let i=he;i.parentElement?.insertBefore(Yt.contextRow,i);let g=Yt.affordanceButtons;for(let h=g.length-1;h>=0;h--){let b=g[h];Ee?Ee.insertBefore(b,Ee.firstChild):X?.appendChild(b)}}(()=>{let i=o.layout?.slots??{},g=b=>{switch(b){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return be;case"footer-top":return bt;case"composer":return X;case"footer-bottom":return M;default:return null}},h=(b,S)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")B.insertBefore(S,B.firstChild);else if(b==="header-right")B.appendChild(S);else{let L=B.querySelector(".persona-flex-col");L?L.parentNode?.insertBefore(S,L.nextSibling):B.appendChild(S)}break;case"body-top":{let L=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");L?L.replaceWith(S):ie.insertBefore(S,ie.firstChild);break}case"body-bottom":ie.appendChild(S);break;case"footer-top":bt.replaceWith(S);break;case"footer-bottom":M.replaceWith(S);break;default:break}};for(let[b,S]of Object.entries(i))if(S)try{let L=S({config:o,defaultContent:()=>g(b)});L&&h(b,L)}catch(L){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,L)}})();let Ul=i=>{let h=i.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let L=h.getAttribute("data-bubble-type");if(L==="reasoning")fr.has(S)?fr.delete(S):fr.add(S),_p(S,b);else if(L==="tool")gr.has(S)?gr.delete(S):gr.add(S),$p(S,b,o);else if(L==="approval"){let O=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Ho.get(S)??O;Ho.set(S,!G),qp(S,b,o)}yo.delete(S)};be.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Ul(i))}),be.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Ul(i))}),be.addEventListener("copy",i=>{let{clipboardData:g}=i;if(!g)return;let h=be.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),L=yp(S);!L||L===S||(g.setData("text/plain",L),i.preventDefault())});let Za=new Map,jl=null,ql="idle",Du={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Nu=(i,g)=>{let{icon:h,label:b}=Du[g];i.setAttribute("aria-label",b),i.title=b,i.setAttribute("aria-pressed",g==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",g!=="idle"),i.classList.toggle("persona-message-action-loading",g==="loading");let S=ne(h,14,"currentColor",2);S&&(i.innerHTML="",i.appendChild(S))},Vl=()=>{be.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let b=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Nu(g,b&&b===jl?ql:"idle")})};be.addEventListener("click",i=>{let h=i.target.closest(".persona-message-action-btn[data-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let L=h.getAttribute("data-action");if(L==="copy"){let O=_.getMessages().find(G=>G.id===S);if(O&&Me.onCopy){let G=O.content||"";navigator.clipboard.writeText(G).then(()=>{h.classList.add("persona-message-action-success");let re=ne("check",14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let le=ne("copy",14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),Me.onCopy(O)}}else if(L==="read-aloud")_.toggleReadAloud(S);else if(L==="upvote"||L==="downvote"){let O=(Za.get(S)??null)===L,G=L==="upvote"?"thumbs-up":"thumbs-down";if(O){Za.delete(S),h.classList.remove("persona-message-action-active");let re=ne(G,14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re))}else{let re=L==="upvote"?"downvote":"upvote",le=b.querySelector(`[data-action="${re}"]`);if(le){le.classList.remove("persona-message-action-active");let at=ne(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);at&&(le.innerHTML="",le.appendChild(at))}Za.set(S,L),h.classList.add("persona-message-action-active");let se=ne(G,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(se)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ve=_.getMessages().find(gt=>gt.id===S);Ve&&Me.onFeedback&&Me.onFeedback({type:L,messageId:Ve.id,message:Ve})}}}),be.addEventListener("click",i=>{let h=i.target.closest("button[data-approval-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let L=h.getAttribute("data-approval-action");if(!L)return;let Q=L==="approve"?"approved":"denied",G=_.getMessages().find(le=>le.id===S);if(!G?.approval)return;let re=b.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?_.resolveWebMcpApproval(S,Q):_.resolveApproval(G.approval,Q)});let et=null,xr=null,Cr=()=>{},Ar="none",Ms=null,gn={artifacts:[],selectedId:null},kn=!1,mn=!1,Sr=!1,Oo=!1,Kl=()=>Oo||gn.artifacts.some(i=>ko(o.features?.artifacts,i.artifactType)==="panel"),Es=()=>gn.artifacts.length>0&&!kn&&Kl(),ut={current:null},ei=(i,g)=>{let h=_.getArtifactById(g),b=h?.markdown,S=h?.title||"artifact",L=h?.file,Q=h?.artifactType??"markdown";if(!b){let re=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let se=_.getMessages().find(xe=>xe.id===re);if(se?.rawContent)try{let xe=JSON.parse(se.rawContent);b=xe?.props?.markdown,S=xe?.props?.title||S,xe?.props?.file&&typeof xe.props.file=="object"&&(L=xe.props.file),!h&&typeof xe?.props?.artifactType=="string"&&(Q=xe.props.artifactType)}catch{}}}return{markdown:b,title:S,file:L,artifactType:Q}};be.addEventListener("click",i=>{let h=i.target.closest("[data-download-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:L,title:Q,file:O}=ei(h,b);if(!L)return;let{filename:G,mime:re,content:le}=Zd({title:Q,markdown:L,file:O}),se=new Blob([le],{type:re}),xe=URL.createObjectURL(se),Ve=document.createElement("a");Ve.href=xe,Ve.download=G,Ve.click(),URL.revokeObjectURL(xe)}),be.addEventListener("click",i=>{let h=i.target.closest("[data-artifact-custom-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.getAttribute("data-artifact-custom-action");if(!b)return;let S=h.closest("[data-artifact-inline]"),L=S?null:h.closest("[data-open-artifact]"),Q=S?S.getAttribute("data-artifact-inline"):L?.getAttribute("data-open-artifact")??null,G=(S?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===b);if(!G)return;let{markdown:re,title:le,file:se,artifactType:xe}=ei(h,Q??""),Ve={artifactId:Q,title:le,artifactType:xe,markdown:re,file:se};try{Promise.resolve(G.onClick(Ve)).catch(()=>{})}catch{}}),be.addEventListener("click",i=>{let h=i.target.closest("[data-copy-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.getAttribute("data-copy-artifact");if(!b)return;let S=_.getArtifactById(b),L="";if(S)L=ls(S);else{let{markdown:Q,file:O,artifactType:G}=ei(h,b);G==="markdown"&&(L=ls({id:b,artifactType:"markdown",status:"complete",markdown:Q??"",...O?{file:O}:{}}))}L&&navigator.clipboard.writeText(L).then(()=>{let Q=ne("check",16,"currentColor",2);Q&&(h.replaceChildren(Q),setTimeout(()=>{let O=ne("copy",16,"currentColor",2);O&&h.replaceChildren(O)},1500))}).catch(()=>{})}),be.addEventListener("click",i=>{let h=i.target.closest("[data-expand-artifact-inline]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(kn=!1,Oo=!0,mn=!0,Sr=!0,_.selectArtifact(b),Ln())}),be.addEventListener("click",i=>{let g=i.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let h=g.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(i.preventDefault(),i.stopPropagation(),kn=!1,Oo=!0,_.selectArtifact(b),Ln())}),be.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let g=i.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),g.click())});let _o=Pe.composerOverlay,$o=(i,g,h)=>{let b=g.trim();if(!b||!ut.current)return;let S=i.getAttribute("data-tool-call-id")??"",L=h.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:h.structured,values:h.values??(h.source==="multi"?b.split(", "):[b]),isFreeText:L,source:h.source},bubbles:!0,composed:!0})),tr(_o,S);let Q=ut.current.getMessages().find(O=>O.toolCall?.id===S);Q?.agentMetadata?.awaitingLocalTool?ut.current.resolveAskUserQuestion(Q,h.structured??b):ut.current.sendMessage(b)},go=i=>{let g=ut.current;if(!g)return;let h=i.getAttribute("data-tool-call-id")??"",b=g.getMessages().find(S=>S.toolCall?.id===h);b&&g.persistAskUserQuestionProgress(b,{answers:na(i,b),currentIndex:pn(i)})},Gl=i=>Object.entries(i).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),ti=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=pn(i),h=er(i);if(g>=h-1)return;let b=ut.current?.getMessages().find(S=>S.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(ra(i,b,o,g+1),go(i))};_o.addEventListener("click",i=>{let h=i.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let S=h.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),S==="dismiss"){let L=b.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),tr(_o,L);let Q=ut.current?.getMessages().find(O=>O.toolCall?.id===L);Q?.agentMetadata?.awaitingLocalTool&&(ut.current?.markAskUserQuestionResolved(Q),ut.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(S==="pick"){let L=h.getAttribute("data-option-label");if(!L)return;let Q=b.getAttribute("data-multi-select")==="true",O=eo(b);if(O&&Q){let G=Po(b)[pn(b)],re=new Set(Array.isArray(G)?G:[]);re.has(L)?re.delete(L):re.add(L),to(b,Array.from(re)),go(b);return}if(O){to(b,L),go(b),ti(b);return}if(Q){let G=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",G?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!G);let re=b.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=Fi(b).length===0);return}$o(b,L,{source:"pick",values:[L]});return}if(S==="submit-multi"){let L=Fi(b);if(L.length===0)return;$o(b,L.join(", "),{source:"multi",values:L});return}if(S==="open-free-text"){let L=b.querySelector('[data-ask-free-text-row="true"]');L&&(L.classList.remove("persona-hidden"),L.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(S==="focus-free-text"){b.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(S==="submit-free-text"){let Q=b.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(eo(b)){to(b,Q.trim()),go(b),ti(b);return}$o(b,Q,{source:"free-text"});return}if(S==="next"||S==="back"){if(!ut.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=ut.current.getMessages().find(se=>se.toolCall?.id===L);if(!Q)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let se=Po(b)[pn(b)];(typeof se!="string"||se!==G)&&to(b,G)}let re=S==="next"?1:-1,le=pn(b)+re;ra(b,Q,o,le),go(b);return}if(S==="submit-all"){if(!ut.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=ut.current.getMessages().find(se=>se.toolCall?.id===L);if(!Q)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&to(b,G);let re=na(b,Q);ut.current.persistAskUserQuestionProgress(Q,{answers:re,currentIndex:pn(b)});let le=Gl(re);$o(b,le||"(submitted)",{source:"submit-all",structured:re});return}if(S==="skip"){if(!ut.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=ut.current.getMessages().find(xe=>xe.toolCall?.id===L);if(!Q)return;let O=eo(b),G=pn(b),re=er(b),le=G>=re-1;if(!O){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),tr(_o,L),Q.agentMetadata?.awaitingLocalTool&&(ut.current.markAskUserQuestionResolved(Q),ut.current.resolveAskUserQuestion(Q,"(dismissed)"));return}to(b,"");let se=b.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),le){let xe=na(b,Q),Ve=Gl(xe);$o(b,Ve||"(skipped)",{source:"submit-all",structured:xe});return}ra(b,Q,o,G+1),go(b);return}}),_o.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let h=i.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;i.preventDefault();let S=h.value;if(S.trim()){if(eo(b)){to(b,S.trim()),go(b),ti(b);return}$o(b,S,{source:"free-text"})}});let Ql=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let g=i.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let h=_o.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(i.key),L=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];L&&(i.preventDefault(),L.click())};document.addEventListener("keydown",Ql);let jn=null,vt=null,Tr=null,ks=null,ni=()=>{},Xl=!1,Ls="",Ps="";function oi(){ks?.(),ks=null}let Jl=()=>{if(!jn||!vt)return;let i=t.classList.contains("persona-artifact-welded-split"),g=t.ownerDocument.defaultView??window,h=g.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||h){vt.style.removeProperty("position"),vt.style.removeProperty("left"),vt.style.removeProperty("top"),vt.style.removeProperty("bottom"),vt.style.removeProperty("width"),vt.style.removeProperty("z-index");return}let b=jn.firstElementChild;if(!b||b===vt)return;let S=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${S}px`,vt.style.zIndex="5";let L=vl(jn,g),Q=b.offsetWidth+L/2-S/2;vt.style.left=`${Math.max(0,Q)}px`},Is=()=>{},Fu=()=>{let i=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>h?!1:T||Nt(o)},Rs=()=>!Gt(o)||!Es()||t.classList.contains("persona-artifact-narrow-host")||Fu()||(t.ownerDocument.defaultView??window).innerWidth<fy?"none":bl(o)?"detached":"welded",Ln=()=>{if(!et||!Gt(o))return;ws(t,o),xs(t,o),Is();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=me.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=i);let h=Es();et.setVisible(h),et.update(gn),kn?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),mn=!1,Sr=!1):gn.artifacts.length>0&&Kl()?(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)):(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),mn=!1,Sr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(et.setExpandToggleVisible(b),et.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),et.setCustomActions(o.features?.artifacts?.toolbarActions??[]),et.setTabFade(o.features?.artifacts?.layout?.tabFade),et.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!Sr&&(mn=!1),mn!==Xl){let L=et.element;mn?(Ls=L.style.width,Ps=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(Ls&&(L.style.width=Ls),Ps&&(L.style.maxWidth=Ps),Ls="",Ps=""),Xl=mn}t.classList.toggle("persona-artifact-expanded",mn),et.setExpanded(mn);let S=Rs();S!==Ar&&(Ar=S,Cr()),ni()};if(Gt(o)){me.style.position="relative";let i=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(pe),et=eu(o,{onSelect:h=>ut.current?.selectArtifact(h),onDismiss:()=>{kn=!0,Ln()},onToggleExpand:()=>{let h=!mn,b=gn.selectedId??gn.artifacts[gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:b,expanded:h})!==!0&&(mn=h,h||(Sr=!1),Ln())}}),et.element.classList.add("persona-hidden"),jn=g,g.appendChild(i),g.appendChild(et.element),et.backdrop&&me.appendChild(et.backdrop),me.appendChild(g),ni=()=>{if(!jn||!et)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Tr?.(),Tr=null,oi(),vt&&(vt.remove(),vt=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!vt){let b=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let S=t.ownerDocument,L=S.defaultView??window,Q=O=>{if(!et||O.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||L.innerWidth<=640)return;O.preventDefault(),oi();let G=O.clientX,re=et.element.getBoundingClientRect().width,le=o.features?.artifacts?.layout,se=Ve=>{let gt=jn.getBoundingClientRect().width,at=t.classList.contains("persona-artifact-welded-split"),jt=vl(jn,L),Wt=at?0:b.getBoundingClientRect().width||6,R=re-(Ve.clientX-G),Fe=ru(R,gt,jt,Wt,le?.resizableMinWidth,le?.resizableMaxWidth);et.element.style.width=`${Fe}px`,et.element.style.maxWidth="none",Jl()},xe=()=>{S.removeEventListener("pointermove",se),S.removeEventListener("pointerup",xe),S.removeEventListener("pointercancel",xe),ks=null;try{b.releasePointerCapture(O.pointerId)}catch{}};ks=xe,S.addEventListener("pointermove",se),S.addEventListener("pointerup",xe),S.addEventListener("pointercancel",xe);try{b.setPointerCapture(O.pointerId)}catch{}};b.addEventListener("pointerdown",Q),vt=b,jn.insertBefore(b,et.element),Tr=()=>{b.removeEventListener("pointerdown",Q)}}if(vt){let b=Es();vt.classList.toggle("persona-hidden",!b),Jl()}},Is=()=>{if(!T||!et||(o.launcher?.sidebarMode??!1)||Nt(o)&&un(o).reveal==="emerge")return;let b=t.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(S&&b.innerWidth<=L||!ou(o,T))return;let Q=o.launcher?.width??o.launcherWidth??On,O=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Es()?(me.style.width=O,me.style.maxWidth=O):(me.style.width=Q,me.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(xr=new ResizeObserver(()=>{Ln()}),xr.observe(me))}else me.appendChild(pe);J()&&Qe&&(Pe.peekBanner&&Qe.appendChild(Pe.peekBanner),Qe.appendChild(U)),t.appendChild(We),Qe&&t.appendChild(Qe);let Ws=()=>{if(J()){me.style.width="100%",me.style.maxWidth="100%";let kt=o.launcher?.composerBar??{},Xt=We.dataset.state==="expanded",Vs=kt.expandedSize??"anchored";if(!(Xt&&Vs!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let Or=o.theme?.components?.panel,Ks=ir(o),Qo=(Wn,To)=>Wn==null||Wn===""?To:Vt(Ks,Wn)??Wn,_r="1px solid var(--persona-border)",ki="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",So="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Qo(Or?.border,_r),pe.style.borderRadius=Qo(Or?.borderRadius,So),pe.style.boxShadow=Qo(Or?.shadow,ki),pe.style.overflow="hidden";return}let i=Nt(o),g=o.launcher?.sidebarMode??!1,h=i||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,S=o.launcher?.detachedPanel===!0,L=o.theme?.components?.panel,Q=ir(o),O=(kt,Xt)=>kt==null||kt===""?Xt:Vt(Q,kt)??kt,G=t.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,le=o.launcher?.mobileBreakpoint??640,se=G.innerWidth<=le,xe=re&&se&&T,Ve=i&&re&&se,gt=o.launcher?.position??"bottom-left",at=gt==="bottom-left"||gt==="top-left",jt=o.launcher?.zIndex??zt,Wt="var(--persona-panel-border, 1px solid var(--persona-border))",R="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Fe="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Se=S&&!xe&&!Ve;Se?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Oe=Se?Wt:g||xe?"none":Wt,At=Se?R:xe?"none":g?at?"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))":b?"none":R;i&&!xe&&!Se&&(At="none",Oe="none");let dt=Se?Fe:g||xe?"0":Fe,xt=O(L?.border,Oe),ht=O(L?.shadow,At),_t=O(L?.borderRadius,dt),Co=Rs(),pt=Co==="detached",ce=Co==="welded";t.classList.toggle("persona-artifact-detached-split",pt),t.classList.toggle("persona-artifact-welded-split",ce);let Ct="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)))))",ot=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Gt(o)&&bl(o)&&b&&!i;t.classList.toggle("persona-artifact-chat-flush",ot);let Ue=pt||ot?"none":ht,tt=pt?Wt:ce?"none":xt,Et=pt?Fe:_t;ot&&(tt="none",Et="0");let He=L?.borderRadius!=null&&L.borderRadius!=="",nt=ot&&!He?"0":_t,tn=ie.scrollTop;t.style.cssText="",We.style.cssText="",me.style.cssText="",pe.style.cssText="",ie.style.cssText="",U.style.cssText="",it&&(ie.style.display="none"),(h||b)&&(t.style.minWidth="0");let Ao=()=>{if(tn<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===tn)return;let Xt=ie.scrollHeight-ie.clientHeight;Xt<=0||(ie.scrollTop=Math.min(tn,Xt))})};if(xe){We.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"),We.style.cssText=`
46
+ `,x.addEventListener("click",()=>{u=K,B.forEach((U,j)=>{let J=j<K;U.classList.toggle("selected",J),U.setAttribute("aria-checked",j===K-1?"true":"false")})}),B.push(x),I.appendChild(x)}w.appendChild(I);let k=null;if(p){let K=document.createElement("div");K.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),K.appendChild(k),w.appendChild(K)}let M=document.createElement("div");M.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=l,P.addEventListener("click",()=>{n?.(),c.remove()});let z=document.createElement("button");return z.type="button",z.className="persona-feedback-btn persona-feedback-btn-submit",z.textContent=a,z.addEventListener("click",async()=>{if(u===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let K=k?.value.trim()||void 0;await e(u,K),c.remove()}catch(K){z.disabled=!1,z.textContent=a,console.error("[CSAT Feedback] Failed to submit:",K)}}),M.appendChild(P),M.appendChild(z),w.appendChild(M),c.appendChild(w),c}function Cu(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:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let w=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let I=document.createElement("p");I.className="persona-feedback-subtitle",I.textContent=r,v.appendChild(I),f.appendChild(v);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=d;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=c,k.appendChild(M),k.appendChild(P);let z=document.createElement("div");z.className="persona-feedback-numbers";let K=[];for(let D=0;D<=10;D++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-number-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`Rating ${D} out of 10`),F.textContent=String(D),F.dataset.rating=String(D),D<=6?F.classList.add("persona-feedback-detractor"):D<=8?F.classList.add("persona-feedback-passive"):F.classList.add("persona-feedback-promoter"),F.addEventListener("click",()=>{w=D,K.forEach((ie,ge)=>{ie.classList.toggle("selected",ge===D),ie.setAttribute("aria-checked",ge===D?"true":"false")})}),K.push(F),z.appendChild(F)}B.appendChild(k),B.appendChild(z),f.appendChild(B);let x=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),D.appendChild(x),f.appendChild(D)}let U=document.createElement("div");U.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=l,j.addEventListener("click",()=>{n?.(),u.remove()});let J=document.createElement("button");return J.type="button",J.className="persona-feedback-btn persona-feedback-btn-submit",J.textContent=a,J.addEventListener("click",async()=>{if(w===null){z.classList.add("persona-feedback-shake"),setTimeout(()=>z.classList.remove("persona-feedback-shake"),500);return}J.disabled=!0,J.textContent="Submitting...";try{let D=x?.value.trim()||void 0;await e(w,D),u.remove()}catch(D){J.disabled=!1,J.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),U.appendChild(j),U.appendChild(J),f.appendChild(U),u.appendChild(f),u}var ur="persona-chat-history",xy=30*1e3,Cy=641,Ay={"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 Sy(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=Ay[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 qa(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 Ty(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 My(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var kl=t=>!t||typeof t!="object"?{}:{...t},Au=t=>t.map(e=>({...e,streaming:!1})),Su=(t,e,n)=>{let o=t?.markdown?Ks(t.markdown):null,r=Gs(t?.sanitize);return 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."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(e){let c=e.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Hn()!==null,d;if(t?.postprocessMessage){let c=t.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?ed(a):a,u=o(c);d=r&&p?r(u):u}else d=Zn(a);return d}};function Tu(t){let e=h("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=re(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=h("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var Ey=(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},ky=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:Ey(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Mu=(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=fa(e),r=Al.getForInstance(o.plugins),{plugin:s,teardown:a}=Zp();o.components&&On.registerAll(o.components);let l=mu(),d=o.persistState===!1?null:o.storageAdapter??yu(),c={},u=null,w=!1,f=i=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(i);if(g&&typeof g=="object"&&"state"in g){let{state:m,open:b}=g;return b&&(w=!0),m}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")u=i.then(g=>f(g??{messages:[],metadata:{}}));else{let m=f(i??{messages:[],metadata:{}});m.metadata&&(c=kl(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let v=()=>c,C=i=>{c=i({...c})??{},ci()},I=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Tl],B=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[hs.message,hs.messageAndClick],k=Ml({parsers:I,handlers:B,getSessionMetadata:v,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null});k.syncFromMetadata();let M=o.launcher?.enabled??!0,P=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,K=P,x=M,U=o.layout?.header?.layout,j=!1,J=()=>ls(o),D=()=>M||J(),F=J()?!1:M?P:!0,ie=!1,ge=null,Ce=()=>{ie=!0,ge&&clearTimeout(ge),ge=setTimeout(()=>{ie&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ie=!1)},1e4)},we=Su(o,k,Ce),ee=o.features?.showReasoning??!0,ce=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,ae=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,pe=Y?new us(ye):null,Te=o.features?.eventStream?.maxEvents??2e3,Ae=Y?new ps(Te,pe):null,Oe=Y?new fs:null,Fe=null,ot=!1,Ge=null,Ie=0;pe?.open().then(()=>Ae?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Me={onCopy:i=>{l.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{l.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(i)}},Qe=o.statusIndicator??{},on=i=>i==="idle"?Qe.idleText??It.idle:i==="connecting"?Qe.connectingText??It.connecting:i==="connected"?Qe.connectedText??It.connected:i==="error"?Qe.errorText??It.error:i==="paused"?Qe.pausedText??It.paused:i==="resuming"?Qe.resumingText??It.resuming:It[i];function Tt(i,g,m,b){if(b==="idle"&&m.idleLink){i.textContent="";let A=document.createElement("a");A.href=m.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=g,A.style.color="inherit",A.style.textDecoration="none",i.appendChild(A)}else i.textContent=g}let yt=$p({config:o,showClose:D()}),{wrapper:Re,panel:me,pillRoot:Ve}=yt.shell,ke=yt.panelElements,{container:ue,body:le,messagesWrapper:be,suggestions:bt,textarea:ve,sendButton:de,sendButtonWrapper:un,composerForm:X,statusText:T,introTitle:O,introSubtitle:y,closeButton:S,iconHolder:E,headerTitle:W,headerSubtitle:q,header:H,footer:$,actionsRow:se,rightActions:je}=ke,Ee=ke.leftActions,rt=ke.setSendButtonMode,V=ke.micButton,$e=ke.micButtonWrapper,Se=ke.attachmentButton,Pe=ke.attachmentButtonWrapper,Le=ke.attachmentInput,Xe=ke.attachmentPreviewsContainer;ue.classList.add("persona-relative"),le.classList.add("persona-relative");let lo=12,co=()=>ae.label??"",Ka=()=>ae.iconName??"arrow-down",bs=()=>ae.enabled!==!1,Gt=()=>Z.mode??"anchor-top",_n=()=>Gt()==="follow"||Gt()==="anchor-top"&&Cr,Bl=()=>Z.anchorTopOffset??16,Nu=()=>Z.restorePosition??"bottom",Dl=()=>Z.pauseOnInteraction===!0,Fl=()=>Z.showActivityWhilePinned!==!1,Nl=()=>Z.announce===!0,Et=h("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");Et.type="button",Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom","true");let gr=h("span","persona-flex persona-items-center"),Ga=h("span",""),po=h("span","");po.setAttribute("data-persona-scroll-to-bottom-count",""),po.style.display="none",Et.append(gr,Ga,po),ue.appendChild(Et);let $n=h("div","persona-stream-anchor-spacer");$n.setAttribute("aria-hidden","true"),$n.setAttribute("data-persona-anchor-spacer",""),$n.style.flexShrink="0",$n.style.pointerEvents="none",$n.style.height="0px",le.appendChild($n);let uo=h("div","persona-sr-only");uo.setAttribute("aria-live","polite"),uo.setAttribute("aria-atomic","true"),uo.setAttribute("role","status"),uo.setAttribute("data-persona-live-region",""),Object.assign(uo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ue.appendChild(uo);let mr=null,vs=null,Ol=i=>{!Nl()||!i||(vs=i,mr===null&&(mr=setTimeout(()=>{mr=null,vs&&Nl()&&(uo.textContent=vs),vs=null},400)))},Ho=()=>{let g=$.style.display==="none"?0:$.offsetHeight;Et.style.bottom=`${g+lo}px`};Ho();let _l=()=>{let i=!!co();Et.setAttribute("aria-label",co()||"Jump to latest"),Et.title=co(),Et.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),gr.innerHTML="";let g=re(Ka(),"14px","currentColor",2);g?(gr.appendChild(g),gr.style.display=""):gr.style.display="none",Ga.textContent=co(),Ga.style.display=i?"":"none"};_l();let Ct=null,Jt=null,$l=null,zl=r.find(i=>i.renderHeader);if(zl?.renderHeader){let i=zl.renderHeader({config:o,defaultRenderer:()=>{let g=Po({config:o,showClose:D()});return cs(ue,g,o),g.header},onClose:()=>dt(!1,"user")});if(i){let g=ue.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),H=i,yt.header.element=i)}}let Qa=()=>{if(!Ae)return;if(ot=!0,!Fe&&Ae&&(Fe=ru({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>hr(),config:o,plugins:r,getThroughput:()=>Oe?.getMetric()??{status:"idle"}})),Fe&&(le.style.display="none",$.parentNode?.insertBefore(Fe.element,$),Fe.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${Vt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(m=>m&&et.classList.add(m))}let i=()=>{if(!ot)return;let g=Date.now();g-Ie>=200&&(Fe?.update(),Ie=g),Ge=requestAnimationFrame(i)};Ie=0,Ge=requestAnimationFrame(i),Zt(),l.emit("eventStream:opened",{timestamp:Date.now()})},hr=()=>{if(ot){if(ot=!1,Fe&&Fe.element.remove(),le.style.display="",et){et.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&et.classList.remove(g))}Ge!==null&&(cancelAnimationFrame(Ge),Ge=null),Zt(),l.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(Y){let i=o.features?.eventStream?.classNames,g="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:"");et=h("button",g),et.style.width="28px",et.style.height="28px",et.style.color=Vt.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let m=re("activity","18px","currentColor",1.5);m&&et.appendChild(m);let b=ke.clearChatButtonWrapper,A=ke.closeButtonWrapper,L=b||A;L&&L.parentNode===H?H.insertBefore(et,L):H.appendChild(et),et.addEventListener("click",()=>{ot?hr():Qa()})}let Ou=i=>{let g=o.attachments;if(!g?.enabled)return;let m=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!m){m=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let A=i.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(m,A):i.insertBefore(m,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let A=h("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(g.allowedTypes??Fn).join(","),A.multiple=(g.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),i.appendChild(A)}},Ul=r.find(i=>i.renderComposer);if(Ul?.renderComposer){let i=o.composer,g=Ul.renderComposer({config:o,defaultRenderer:()=>$a({config:o}).footer,onSubmit:m=>{if(!_||_.isStreaming())return;let b=m.trim(),A=Ct?.hasAttachments()??!1;if(!b&&!A)return;bc();let L;A&&(L=[],L.push(...Ct.getContentParts()),b&&L.push(Zo(b))),_.sendMessage(b,{contentParts:L}),A&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Le?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:m=>{o.composer={...o.composer,selectedModelId:m},o.agent&&(o.agent={...o.agent,model:m})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{$l?.()}:void 0});g&&(yt.replaceComposer(g),$=yt.composer.footer)}let _u=i=>{let g=(...fe)=>{for(let ne of fe){let xe=i.querySelector(ne);if(xe)return xe}return null},m=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),A=i.querySelector("[data-persona-composer-submit]"),L=i.querySelector("[data-persona-composer-mic]"),Q=i.querySelector("[data-persona-composer-status]");m&&(X=m),b&&(ve=b),A&&(de=A),L&&(V=L,$e=L.parentElement),Q&&(T=Q);let N=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(bt=N);let G=g("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(Se=G,Pe=G.parentElement),Le=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Xe=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(se=oe),Ee=g(".persona-widget-composer__left-actions")};Ou($),_u($);let zn=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(zn&&(be.style.maxWidth=zn,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%"),zn&&X&&!J()&&(X.style.maxWidth=zn,X.style.marginLeft="auto",X.style.marginRight="auto"),zn&&bt&&!J()&&(bt.style.maxWidth=zn,bt.style.marginLeft="auto",bt.style.marginRight="auto"),zn&&Xe&&!J()&&(Xe.style.maxWidth=zn,Xe.style.marginLeft="auto",Xe.style.marginRight="auto"),o.attachments?.enabled&&Le&&Xe){Ct=Qr.fromConfig(o.attachments),Ct.setPreviewsContainer(Xe),Le.addEventListener("change",m=>{let b=m.target;Ct?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,g=Tu(i);ue.appendChild(g)}let $u=()=>Jt?.prefetch();if(o.contextMentions?.enabled&&ve&&(Jt=Qd({config:o,textarea:ve,anchor:X??ve,getMessages:()=>_.getMessages(),liveRegionHost:ue}),Jt)){let i=ve;i.parentElement?.insertBefore(Jt.contextRow,i);let g=Jt.affordanceButtons;for(let m=g.length-1;m>=0;m--){let b=g[m];Ee?Ee.insertBefore(b,Ee.firstChild):X?.appendChild(b)}}(()=>{let i=o.layout?.slots??{},g=b=>{switch(b){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return be;case"footer-top":return bt;case"composer":return X;case"footer-bottom":return T;default:return null}},m=(b,A)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")H.insertBefore(A,H.firstChild);else if(b==="header-right")H.appendChild(A);else{let L=H.querySelector(".persona-flex-col");L?L.parentNode?.insertBefore(A,L.nextSibling):H.appendChild(A)}break;case"body-top":{let L=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");L?L.replaceWith(A):le.insertBefore(A,le.firstChild);break}case"body-bottom":le.appendChild(A);break;case"footer-top":bt.replaceWith(A);break;case"footer-bottom":T.replaceWith(A);break;default:break}};for(let[b,A]of Object.entries(i))if(A)try{let L=A({config:o,defaultContent:()=>g(b)});L&&m(b,L)}catch(L){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,L)}})();let jl=i=>{let m=i.target.closest('button[data-expand-header="true"]');if(!m)return;let b=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let A=b.getAttribute("data-message-id");if(!A)return;let L=m.getAttribute("data-bubble-type");if(L==="reasoning")cr.has(A)?cr.delete(A):cr.add(A),Vp(A,b);else if(L==="tool")dr.has(A)?dr.delete(A):dr.add(A),Kp(A,b,o);else if(L==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Io.get(A)??N;Io.set(A,!G),Jp(A,b,o)}ho.delete(A)};be.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),jl(i))}),be.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),jl(i))}),be.addEventListener("copy",i=>{let{clipboardData:g}=i;if(!g)return;let m=be.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let A=b.toString(),L=Ap(A);!L||L===A||(g.setData("text/plain",L),i.preventDefault())});let Xa=new Map,ql=null,Vl="idle",zu={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Uu=(i,g)=>{let{icon:m,label:b}=zu[g];i.setAttribute("aria-label",b),i.title=b,i.setAttribute("aria-pressed",g==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",g!=="idle"),i.classList.toggle("persona-message-action-loading",g==="loading");let A=re(m,14,"currentColor",2);A&&(i.innerHTML="",i.appendChild(A))},Kl=()=>{be.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let b=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Uu(g,b&&b===ql?Vl:"idle")})};be.addEventListener("click",i=>{let m=i.target.closest(".persona-message-action-btn[data-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest("[data-actions-for]");if(!b)return;let A=b.getAttribute("data-actions-for");if(!A)return;let L=m.getAttribute("data-action");if(L==="copy"){let N=_.getMessages().find(G=>G.id===A);if(N&&Me.onCopy){let G=N.content||"";navigator.clipboard.writeText(G).then(()=>{m.classList.add("persona-message-action-success");let oe=re("check",14,"currentColor",2);oe&&(m.innerHTML="",m.appendChild(oe)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let fe=re("copy",14,"currentColor",2);fe&&(m.innerHTML="",m.appendChild(fe))},2e3)}).catch(oe=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",oe)}),Me.onCopy(N)}}else if(L==="read-aloud")_.toggleReadAloud(A);else if(L==="upvote"||L==="downvote"){let N=(Xa.get(A)??null)===L,G=L==="upvote"?"thumbs-up":"thumbs-down";if(N){Xa.delete(A),m.classList.remove("persona-message-action-active");let oe=re(G,14,"currentColor",2);oe&&(m.innerHTML="",m.appendChild(oe))}else{let oe=L==="upvote"?"downvote":"upvote",fe=b.querySelector(`[data-action="${oe}"]`);if(fe){fe.classList.remove("persona-message-action-active");let tt=re(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);tt&&(fe.innerHTML="",fe.appendChild(tt))}Xa.set(A,L),m.classList.add("persona-message-action-active");let ne=re(G,14,"currentColor",2);ne&&(ne.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(ne)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ue=_.getMessages().find(pt=>pt.id===A);Ue&&Me.onFeedback&&Me.onFeedback({type:L,messageId:Ue.id,message:Ue})}}}),be.addEventListener("click",i=>{let m=i.target.closest("button[data-approval-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest(".persona-approval-bubble");if(!b)return;let A=b.getAttribute("data-message-id");if(!A)return;let L=m.getAttribute("data-approval-action");if(!L)return;let Q=L==="approve"?"approved":"denied",G=_.getMessages().find(fe=>fe.id===A);if(!G?.approval)return;let oe=b.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?_.resolveWebMcpApproval(A,Q):_.resolveApproval(G.approval,Q)});let Je=null,yr=null,br=()=>{},vr="none",ws=null,fn={artifacts:[],selectedId:null},Mn=!1,gn=!1,wr=!1,Bo=!1,Gl=()=>Bo||fn.artifacts.some(i=>So(o.features?.artifacts,i.artifactType)==="panel"),xs=()=>fn.artifacts.length>0&&!Mn&&Gl(),lt={current:null},Ja=(i,g)=>{let m=_.getArtifactById(g),b=m?.markdown,A=m?.title||"artifact",L=m?.file,Q=m?.artifactType??"markdown";if(!b){let oe=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(oe){let ne=_.getMessages().find(xe=>xe.id===oe);if(ne?.rawContent)try{let xe=JSON.parse(ne.rawContent);b=xe?.props?.markdown,A=xe?.props?.title||A,xe?.props?.file&&typeof xe.props.file=="object"&&(L=xe.props.file),!m&&typeof xe?.props?.artifactType=="string"&&(Q=xe.props.artifactType)}catch{}}}return{markdown:b,title:A,file:L,artifactType:Q}};be.addEventListener("click",i=>{let m=i.target.closest("[data-download-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:L,title:Q,file:N}=Ja(m,b);if(!L)return;let{filename:G,mime:oe,content:fe}=sp({title:Q,markdown:L,file:N}),ne=new Blob([fe],{type:oe}),xe=URL.createObjectURL(ne),Ue=document.createElement("a");Ue.href=xe,Ue.download=G,Ue.click(),URL.revokeObjectURL(xe)}),be.addEventListener("click",i=>{let m=i.target.closest("[data-artifact-custom-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-artifact-custom-action");if(!b)return;let A=m.closest("[data-artifact-inline]"),L=A?null:m.closest("[data-open-artifact]"),Q=A?A.getAttribute("data-artifact-inline"):L?.getAttribute("data-open-artifact")??null,G=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===b);if(!G)return;let{markdown:oe,title:fe,file:ne,artifactType:xe}=Ja(m,Q??""),Ue={artifactId:Q,title:fe,artifactType:xe,markdown:oe,file:ne};try{Promise.resolve(G.onClick(Ue)).catch(()=>{})}catch{}}),be.addEventListener("click",i=>{let m=i.target.closest("[data-copy-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-copy-artifact");if(!b)return;let A=_.getArtifactById(b),L="";if(A)L=ns(A);else{let{markdown:Q,file:N,artifactType:G}=Ja(m,b);G==="markdown"&&(L=ns({id:b,artifactType:"markdown",status:"complete",markdown:Q??"",...N?{file:N}:{}}))}L&&navigator.clipboard.writeText(L).then(()=>{let Q=re("check",16,"currentColor",2);Q&&(m.replaceChildren(Q),setTimeout(()=>{let N=re("copy",16,"currentColor",2);N&&m.replaceChildren(N)},1500))}).catch(()=>{})}),be.addEventListener("click",i=>{let m=i.target.closest("[data-expand-artifact-inline]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(Mn=!1,Bo=!0,gn=!0,wr=!0,_.selectArtifact(b),En())}),be.addEventListener("click",i=>{let g=i.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let m=g.closest("[data-open-artifact]");if(!m)return;let b=m.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(i.preventDefault(),i.stopPropagation(),Mn=!1,Bo=!0,_.selectArtifact(b),En())}),be.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let g=i.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),g.click())});let Do=ke.composerOverlay,Fo=(i,g,m)=>{let b=g.trim();if(!b||!lt.current)return;let A=i.getAttribute("data-tool-call-id")??"",L=m.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:b,answers:m.structured,values:m.values??(m.source==="multi"?b.split(", "):[b]),isFreeText:L,source:m.source},bubbles:!0,composed:!0})),Jo(Do,A);let Q=lt.current.getMessages().find(N=>N.toolCall?.id===A);Q?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(Q,m.structured??b):lt.current.sendMessage(b)},fo=i=>{let g=lt.current;if(!g)return;let m=i.getAttribute("data-tool-call-id")??"",b=g.getMessages().find(A=>A.toolCall?.id===m);b&&g.persistAskUserQuestionProgress(b,{answers:Ys(i,b),currentIndex:dn(i)})},Ql=i=>Object.entries(i).map(([g,m])=>`${g}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),Ya=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=dn(i),m=Xo(i);if(g>=m-1)return;let b=lt.current?.getMessages().find(A=>A.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(ea(i,b,o,g+1),fo(i))};Do.addEventListener("click",i=>{let m=i.target.closest("[data-ask-user-action]");if(!m)return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;let A=m.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),A==="dismiss"){let L=b.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),Jo(Do,L);let Q=lt.current?.getMessages().find(N=>N.toolCall?.id===L);Q?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(Q),lt.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(A==="pick"){let L=m.getAttribute("data-option-label");if(!L)return;let Q=b.getAttribute("data-multi-select")==="true",N=eo(b);if(N&&Q){let G=Mo(b)[dn(b)],oe=new Set(Array.isArray(G)?G:[]);oe.has(L)?oe.delete(L):oe.add(L),to(b,Array.from(oe)),fo(b);return}if(N){to(b,L),fo(b),Ya(b);return}if(Q){let G=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",G?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!G);let oe=b.querySelector('[data-ask-user-action="submit-multi"]');oe&&(oe.disabled=Di(b).length===0);return}Fo(b,L,{source:"pick",values:[L]});return}if(A==="submit-multi"){let L=Di(b);if(L.length===0)return;Fo(b,L.join(", "),{source:"multi",values:L});return}if(A==="open-free-text"){let L=b.querySelector('[data-ask-free-text-row="true"]');L&&(L.classList.remove("persona-hidden"),L.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){b.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let Q=b.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(eo(b)){to(b,Q.trim()),fo(b),Ya(b);return}Fo(b,Q,{source:"free-text"});return}if(A==="next"||A==="back"){if(!lt.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(ne=>ne.toolCall?.id===L);if(!Q)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let ne=Mo(b)[dn(b)];(typeof ne!="string"||ne!==G)&&to(b,G)}let oe=A==="next"?1:-1,fe=dn(b)+oe;ea(b,Q,o,fe),fo(b);return}if(A==="submit-all"){if(!lt.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(ne=>ne.toolCall?.id===L);if(!Q)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&to(b,G);let oe=Ys(b,Q);lt.current.persistAskUserQuestionProgress(Q,{answers:oe,currentIndex:dn(b)});let fe=Ql(oe);Fo(b,fe||"(submitted)",{source:"submit-all",structured:oe});return}if(A==="skip"){if(!lt.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(xe=>xe.toolCall?.id===L);if(!Q)return;let N=eo(b),G=dn(b),oe=Xo(b),fe=G>=oe-1;if(!N){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),Jo(Do,L),Q.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(Q),lt.current.resolveAskUserQuestion(Q,"(dismissed)"));return}to(b,"");let ne=b.querySelector('[data-ask-free-text-input="true"]');if(ne&&(ne.value=""),fe){let xe=Ys(b,Q),Ue=Ql(xe);Fo(b,Ue||"(skipped)",{source:"submit-all",structured:xe});return}ea(b,Q,o,G+1),fo(b);return}}),Do.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let m=i.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;i.preventDefault();let A=m.value;if(A.trim()){if(eo(b)){to(b,A.trim()),fo(b),Ya(b);return}Fo(b,A,{source:"free-text"})}});let Xl=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let g=i.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let m=Do.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let b=Number(i.key),L=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];L&&(i.preventDefault(),L.click())};document.addEventListener("keydown",Xl);let Un=null,vt=null,xr=null,Cs=null,Za=()=>{},Jl=!1,As="",Ss="";function ei(){Cs?.(),Cs=null}let Yl=()=>{if(!Un||!vt)return;let i=t.classList.contains("persona-artifact-welded-split"),g=t.ownerDocument.defaultView??window,m=g.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||m){vt.style.removeProperty("position"),vt.style.removeProperty("left"),vt.style.removeProperty("top"),vt.style.removeProperty("bottom"),vt.style.removeProperty("width"),vt.style.removeProperty("z-index");return}let b=Un.firstElementChild;if(!b||b===vt)return;let A=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${A}px`,vt.style.zIndex="5";let L=wl(Un,g),Q=b.offsetWidth+L/2-A/2;vt.style.left=`${Math.max(0,Q)}px`},Ts=()=>{},ju=()=>{let i=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>m?!1:M||Ht(o)},Ms=()=>!Kt(o)||!xs()||t.classList.contains("persona-artifact-narrow-host")||ju()||(t.ownerDocument.defaultView??window).innerWidth<Cy?"none":vl(o)?"detached":"welded",En=()=>{if(!Je||!Kt(o))return;gs(t,o),ms(t,o),Ts();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=me.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=i);let m=xs();Je.setVisible(m),Je.update(fn),Mn?(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),gn=!1,wr=!1):fn.artifacts.length>0&&Gl()?(Je.element.classList.remove("persona-hidden"),Je.setMobileOpen(!0)):(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),gn=!1,wr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Je.setExpandToggleVisible(b),Je.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Je.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Je.setTabFade(o.features?.artifacts?.layout?.tabFade),Je.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!wr&&(gn=!1),gn!==Jl){let L=Je.element;gn?(As=L.style.width,Ss=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(As&&(L.style.width=As),Ss&&(L.style.maxWidth=Ss),As="",Ss=""),Jl=gn}t.classList.toggle("persona-artifact-expanded",gn),Je.setExpanded(gn);let A=Ms();A!==vr&&(vr=A,br()),Za()};if(Kt(o)){me.style.position="relative";let i=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ue),Je=au(o,{onSelect:m=>lt.current?.selectArtifact(m),onDismiss:()=>{Mn=!0,En()},onToggleExpand:()=>{let m=!gn,b=fn.selectedId??fn.artifacts[fn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:b,expanded:m})!==!0&&(gn=m,m||(wr=!1),En())}}),Je.element.classList.add("persona-hidden"),Un=g,g.appendChild(i),g.appendChild(Je.element),Je.backdrop&&me.appendChild(Je.backdrop),me.appendChild(g),Za=()=>{if(!Un||!Je)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){xr?.(),xr=null,ei(),vt&&(vt.remove(),vt=null),Je.element.style.removeProperty("width"),Je.element.style.removeProperty("maxWidth");return}if(!vt){let b=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let A=t.ownerDocument,L=A.defaultView??window,Q=N=>{if(!Je||N.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||L.innerWidth<=640)return;N.preventDefault(),ei();let G=N.clientX,oe=Je.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,ne=Ue=>{let pt=Un.getBoundingClientRect().width,tt=t.classList.contains("persona-artifact-welded-split"),en=wl(Un,L),At=tt?0:b.getBoundingClientRect().width||6,Lt=oe-(Ue.clientX-G),R=du(Lt,pt,en,At,fe?.resizableMinWidth,fe?.resizableMaxWidth);Je.element.style.width=`${R}px`,Je.element.style.maxWidth="none",Yl()},xe=()=>{A.removeEventListener("pointermove",ne),A.removeEventListener("pointerup",xe),A.removeEventListener("pointercancel",xe),Cs=null;try{b.releasePointerCapture(N.pointerId)}catch{}};Cs=xe,A.addEventListener("pointermove",ne),A.addEventListener("pointerup",xe),A.addEventListener("pointercancel",xe);try{b.setPointerCapture(N.pointerId)}catch{}};b.addEventListener("pointerdown",Q),vt=b,Un.insertBefore(b,Je.element),xr=()=>{b.removeEventListener("pointerdown",Q)}}if(vt){let b=xs();vt.classList.toggle("persona-hidden",!b),Yl()}},Ts=()=>{if(!M||!Je||(o.launcher?.sidebarMode??!1)||Ht(o)&&pn(o).reveal==="emerge")return;let b=t.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(A&&b.innerWidth<=L||!cu(o,M))return;let Q=o.launcher?.width??o.launcherWidth??Nn,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";xs()?(me.style.width=N,me.style.maxWidth=N):(me.style.width=Q,me.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(yr=new ResizeObserver(()=>{En()}),yr.observe(me))}else me.appendChild(ue);J()&&Ve&&(ke.peekBanner&&Ve.appendChild(ke.peekBanner),Ve.appendChild($)),t.appendChild(Re),Ve&&t.appendChild(Ve);let Es=()=>{if(J()){me.style.width="100%",me.style.maxWidth="100%";let Mt=o.launcher?.composerBar??{},Xt=Re.dataset.state==="expanded",$s=Mt.expandedSize??"anchored";if(!(Xt&&$s!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Dr=o.theme?.components?.panel,zs=or(o),qo=(In,Ao)=>In==null||In===""?Ao:qt(zs,In)??In,Us="1px solid var(--persona-border)",Ti="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Co="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=qo(Dr?.border,Us),ue.style.borderRadius=qo(Dr?.borderRadius,Co),ue.style.boxShadow=qo(Dr?.shadow,Ti),ue.style.overflow="hidden";return}let i=Ht(o),g=o.launcher?.sidebarMode??!1,m=i||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,L=o.theme?.components?.panel,Q=or(o),N=(Mt,Xt)=>Mt==null||Mt===""?Xt:qt(Q,Mt)??Mt,G=t.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,ne=G.innerWidth<=fe,xe=oe&&ne&&M,Ue=i&&oe&&ne,pt=o.launcher?.position??"bottom-left",tt=pt==="bottom-left"||pt==="top-left",en=o.launcher?.zIndex??$t,At="var(--persona-panel-border, 1px solid var(--persona-border))",Lt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",R="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",We=A&&!xe&&!Ue;We?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let He=We?At:g||xe?"none":At,_e=We?Lt:xe?"none":g?tt?"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))":b?"none":Lt;i&&!xe&&!We&&(_e="none",He="none");let St=We?R:g||xe?"0":R,ut=N(L?.border,He),Ut=N(L?.shadow,_e),ft=N(L?.borderRadius,St),Qt=Ms(),Pt=Qt==="detached",Be=Qt==="welded";t.classList.toggle("persona-artifact-detached-split",Pt),t.classList.toggle("persona-artifact-welded-split",Be);let Ze="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)))))",st=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Kt(o)&&vl(o)&&b&&!i;t.classList.toggle("persona-artifact-chat-flush",st);let ct=Pt||st?"none":Ut,gt=Pt?At:Be?"none":ut,Ye=Pt?R:ft;st&&(gt="none",Ye="0");let De=L?.borderRadius!=null&&L.borderRadius!=="",ht=st&&!De?"0":ft,Nt=le.scrollTop;t.style.cssText="",Re.style.cssText="",me.style.cssText="",ue.style.cssText="",le.style.cssText="",$.style.cssText="",ot&&(le.style.display="none"),(m||b)&&(t.style.minWidth="0");let cn=()=>{if(Nt<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===Nt)return;let Xt=le.scrollHeight-le.clientHeight;Xt<=0||(le.scrollTop=Math.min(Nt,Xt))})};if(xe){Re.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"),Re.style.cssText=`
47
47
  position: fixed !important;
48
48
  inset: 0 !important;
49
49
  width: 100% !important;
@@ -53,7 +53,7 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
53
53
  padding: 0 !important;
54
54
  display: flex !important;
55
55
  flex-direction: column !important;
56
- z-index: ${jt} !important;
56
+ z-index: ${en} !important;
57
57
  background-color: var(--persona-surface, #ffffff) !important;
58
58
  `,me.style.cssText=`
59
59
  position: relative !important;
@@ -68,7 +68,7 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
68
68
  padding: 0 !important;
69
69
  box-shadow: none !important;
70
70
  border-radius: 0 !important;
71
- `,pe.style.cssText=`
71
+ `,ue.style.cssText=`
72
72
  display: flex !important;
73
73
  flex-direction: column !important;
74
74
  flex: 1 1 0% !important;
@@ -79,32 +79,32 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
79
79
  overflow: hidden !important;
80
80
  border-radius: 0 !important;
81
81
  border: none !important;
82
- `,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",U.style.flexShrink="0",q=!0,Ao();return}let qs=o?.launcher?.width??o?.launcherWidth??On;if(!g&&!i)b&&h?(me.style.width="100%",me.style.maxWidth="100%"):(me.style.width=qs,me.style.maxWidth=qs);else if(i)if(un(o).reveal==="emerge"&&!S){let Xt=un(o).width;me.style.width=Xt,me.style.maxWidth=Xt}else me.style.width="100%",me.style.maxWidth="100%";if(Is(),me.style.boxShadow=Ue,me.style.borderRadius=nt,pt?me.style.border="none":ce&&(me.style.border=xt),pe.style.border=tt,pe.style.borderRadius=Et,pe.style.boxShadow=pt&&!ot?Ct:"",ot&&(pe.style.background="transparent",ie.style.background="transparent",U.style.background="transparent",U.style.borderTop="none"),ce){let kt=o.features?.artifacts?.layout;Ms=kt?.unifiedSplitOuterRadius?.trim()||kt?.paneBorderRadius?.trim()||_t}else Ms=null;if(i&&!xe&&!Se&&!pt&&!ce&&L?.border===void 0&&(pe.style.border="none",un(o).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),i&&!xe&&ce&&L?.border===void 0&&(un(o).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),h&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",b&&(t.style.width="100%"),We.style.display="flex",We.style.flexDirection="column",We.style.flex="1 1 0%",We.style.minHeight="0",We.style.maxHeight="100%",We.style.height="100%",b&&(We.style.overflow="hidden"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.height="100%",pt||(me.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",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",U.style.flexShrink="0"),b&&(Se||pt||ot)&&!i&&(ot||(We.style.padding="var(--persona-panel-inset)"),We.style.background="var(--persona-panel-canvas-bg)"),We.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"),!g&&!b&&!i&&(xn[gt]??xn["bottom-right"]).split(" ").forEach(Xt=>We.classList.add(Xt)),g){let kt=o.launcher?.sidebarWidth??"420px";S?We.style.cssText=`
82
+ `,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",$.style.flexShrink="0",j=!0,cn();return}let _s=o?.launcher?.width??o?.launcherWidth??Nn;if(!g&&!i)b&&m?(me.style.width="100%",me.style.maxWidth="100%"):(me.style.width=_s,me.style.maxWidth=_s);else if(i)if(pn(o).reveal==="emerge"&&!A){let Xt=pn(o).width;me.style.width=Xt,me.style.maxWidth=Xt}else me.style.width="100%",me.style.maxWidth="100%";if(Ts(),me.style.boxShadow=ct,me.style.borderRadius=ht,Pt?me.style.border="none":Be&&(me.style.border=ut),ue.style.border=gt,ue.style.borderRadius=Ye,ue.style.boxShadow=Pt&&!st?Ze:"",st&&(ue.style.background="transparent",le.style.background="transparent",$.style.background="transparent",$.style.borderTop="none"),Be){let Mt=o.features?.artifacts?.layout;ws=Mt?.unifiedSplitOuterRadius?.trim()||Mt?.paneBorderRadius?.trim()||ft}else ws=null;if(i&&!xe&&!We&&!Pt&&!Be&&L?.border===void 0&&(ue.style.border="none",pn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),i&&!xe&&Be&&L?.border===void 0&&(pn(o).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),m&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",b&&(t.style.width="100%"),Re.style.display="flex",Re.style.flexDirection="column",Re.style.flex="1 1 0%",Re.style.minHeight="0",Re.style.maxHeight="100%",Re.style.height="100%",b&&(Re.style.overflow="hidden"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.height="100%",Pt||(me.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",$.style.flexShrink="0"),b&&(We||Pt||st)&&!i&&(st||(Re.style.padding="var(--persona-panel-inset)"),Re.style.background="var(--persona-panel-canvas-bg)"),Re.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"),!g&&!b&&!i&&(wn[pt]??wn["bottom-right"]).split(" ").forEach(Xt=>Re.classList.add(Xt)),g){let Mt=o.launcher?.sidebarWidth??"420px";A?Re.style.cssText=`
83
83
  position: fixed !important;
84
84
  top: var(--persona-panel-inset) !important;
85
85
  bottom: var(--persona-panel-inset) !important;
86
- width: ${kt} !important;
86
+ width: ${Mt} !important;
87
87
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
88
88
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
89
89
  margin: 0 !important;
90
90
  padding: 0 !important;
91
91
  display: flex !important;
92
92
  flex-direction: column !important;
93
- z-index: ${jt} !important;
94
- ${at?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
95
- `:We.style.cssText=`
93
+ z-index: ${en} !important;
94
+ ${tt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
95
+ `:Re.style.cssText=`
96
96
  position: fixed !important;
97
97
  top: 0 !important;
98
98
  bottom: 0 !important;
99
- width: ${kt} !important;
99
+ width: ${Mt} !important;
100
100
  height: 100vh !important;
101
101
  max-height: 100vh !important;
102
102
  margin: 0 !important;
103
103
  padding: 0 !important;
104
104
  display: flex !important;
105
105
  flex-direction: column !important;
106
- z-index: ${jt} !important;
107
- ${at?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
106
+ z-index: ${en} !important;
107
+ ${tt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
108
108
  `,me.style.cssText=`
109
109
  position: relative !important;
110
110
  display: flex !important;
@@ -116,10 +116,10 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
116
116
  min-height: 0 !important;
117
117
  margin: 0 !important;
118
118
  padding: 0 !important;
119
- box-shadow: ${Ue} !important;
120
- border-radius: ${nt} !important;
121
- ${pt?"border: none !important;":ce?`border: ${xt} !important;`:""}
122
- `,me.style.setProperty("width","100%","important"),me.style.setProperty("max-width","100%","important"),pe.style.cssText=`
119
+ box-shadow: ${ct} !important;
120
+ border-radius: ${ht} !important;
121
+ ${Pt?"border: none !important;":Be?`border: ${ut} !important;`:""}
122
+ `,me.style.setProperty("width","100%","important"),me.style.setProperty("max-width","100%","important"),ue.style.cssText=`
123
123
  display: flex !important;
124
124
  flex-direction: column !important;
125
125
  flex: 1 1 0% !important;
@@ -128,16 +128,16 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
128
128
  min-height: 0 !important;
129
129
  max-height: 100% !important;
130
130
  overflow: hidden !important;
131
- border-radius: ${Et} !important;
132
- border: ${tt} !important;
133
- ${pt&&!ot?`box-shadow: ${Ct} !important;`:""}
134
- ${ot?"background: transparent !important;":""}
135
- `,U.style.cssText=`
131
+ border-radius: ${Ye} !important;
132
+ border: ${gt} !important;
133
+ ${Pt&&!st?`box-shadow: ${Ze} !important;`:""}
134
+ ${st?"background: transparent !important;":""}
135
+ `,$.style.cssText=`
136
136
  flex-shrink: 0 !important;
137
137
  border-top: none !important;
138
138
  padding: 8px 16px 12px 16px !important;
139
- ${ot?"background: transparent !important;":""}
140
- `}if(!b&&!i){let kt="max-height: -moz-available !important; max-height: stretch !important;",Xt=g?"":"padding-top: 1.25em !important;",Vs=g?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;We.style.cssText+=kt+Xt+Vs}Ao()};Ws(),rs(t,o),ws(t,o),xs(t,o),Cr=()=>{Ws(),rs(t,o),ws(t,o),xs(t,o),Ms?t.style.setProperty("--persona-artifact-welded-outer-radius",Ms):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let qe=[];qe.push(()=>{document.removeEventListener("keydown",Ql)}),qe.push(()=>{vr!==null&&clearTimeout(vr)});let Cn=null,An=null;qe.push(()=>{Cn?.(),Cn=null,An?.(),An=null}),xr&&qe.push(()=>{xr?.disconnect(),xr=null}),qe.push(()=>{Tr?.(),Tr=null,oi(),vt&&(vt.remove(),vt=null),et?.element.style.removeProperty("width"),et?.element.style.removeProperty("maxWidth")}),Y&&qe.push(()=>{Je!==null&&(cancelAnimationFrame(Je),Je=null),Ne?.destroy(),Ne=null,Ae?.destroy(),Ae=null,ue=null});let mo=null,Yl=()=>{mo&&(mo(),mo=null),o.colorScheme==="auto"&&(mo=va(()=>{rs(t,o)}))};Yl(),qe.push(()=>{mo&&(mo(),mo=null)}),qe.push(a);let Bs=o.features?.streamAnimation;if(Bs?.type&&Bs.type!=="none"){let i=ur(Bs.type,Bs.plugins);i&&(Ba(i,t),qe.push(()=>Lp(t)))}let Hs=Gp(bt),ho=null,_,ri=i=>{if(!_)return;let g=i??_.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?vd(g):null;h?Hs.render(h,_,he,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(b=>b.role==="user")?Hs.render([],_,he,g):Hs.render(o.suggestionChips,_,he,g,o.suggestionChipsConfig)},hn=!1,yo=wp(),zo=new Map,bo=new Map,qn=new Map,si=0,Ou=Hn()!==null,Zt=ka(),an=0,Vn=null,ln=!1,Ds=!1,Kn=0,yn=null,vo=null,ai=!1,Ns=!1,ii=null,Mr=!0,li=!1,ci=null,_u=4,Fs=24,$u=80,di=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Zl=o.voiceRecognition?.autoResume??!1,Pn=i=>{l.emit("voice:state",{active:Xe.active,source:i,timestamp:Date.now()})},bn=()=>{C(i=>({...i,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},zu=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=El(c.voiceState),g=!!i.active,h=Number(i.timestamp??0);Xe.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-h<uy&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Xe.active=_.isVoiceActive(),Pn("restore"),_.isVoiceActive()&&Ko()}):$s("restore"))},1e3)},Uu=()=>_?yu(_.getMessages()).filter(i=>!i.__skipPersist):[],Os=null,ec=(i,g)=>{typeof console<"u"&&console.error(i,g)},pi=(i,g)=>{let h=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(O=>{ec(g,O)})}catch(Q){return ec(g,Q),null}},b=Os,S=b?b.then(()=>h()??void 0):h();if(!S)return;let L=S.finally(()=>{Os===L&&(Os=null)});Os=L};function ui(i){if(!d?.save)return;let h={messages:i?yu(i):_?Uu():[],metadata:c,artifacts:gn.artifacts,selectedArtifactId:gn.selectedId};pi(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let Uo=null,tc=()=>We.querySelector("#persona-scroll-container")||ie,Er=()=>{Uo!==null&&(cancelAnimationFrame(Uo),Uo=null),ln=!1},nc=()=>{Vn!==null&&(cancelAnimationFrame(Vn),Vn=null),Ds=!1,Er()},ju=()=>hn&&gi()&&(Qt()!=="anchor-top"||Dl()),fi=()=>{let i=po()||"Jump to latest",g=ju();Lt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Kn>0?(uo.textContent=String(Kn),uo.style.display="",Lt.setAttribute("aria-label",`${i} (${Kn} new)`)):(uo.textContent="",uo.style.display="none",Lt.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},oc=()=>{Kn!==0&&(Kn=0,fi())},gi=()=>$n()?!Zt.isFollowing():!io(ie,Fs),en=()=>{if(!Ss()||it){Lt.parentNode&&Lt.remove(),Lt.style.display="none";return}Lt.parentNode!==pe&&pe.appendChild(Lt),Fo();let g=En(ie)>0&&gi();g?fi():oc(),Lt.style.display=g?"":"none"},kr=()=>{Zt.pause()&&(nc(),en())},Gn=()=>{Zt.resume(),oc(),en()},Qn=(i=!1)=>{$n()&&Zt.isFollowing()&&(!i&&!hn||(Vn!==null&&(cancelAnimationFrame(Vn),Vn=null),Ds=!0,Vn=requestAnimationFrame(()=>{Vn=null,Ds=!1,Zt.isFollowing()&&qu(tc(),i?220:140)})))},rc=(i,g,h,b=()=>!0)=>{let S=i.scrollTop,L=g(),Q=L-S;if(Er(),Math.abs(Q)<1){ln=!0,i.scrollTop=L,an=i.scrollTop,ln=!1;return}let O=performance.now();ln=!0;let G=le=>1-Math.pow(1-le,3),re=le=>{if(!b()){Er();return}let se=g();se!==L&&(L=se,Q=L-S);let xe=le-O,Ve=Math.min(xe/h,1),gt=G(Ve),at=S+Q*gt;i.scrollTop=at,an=i.scrollTop,Ve<1?Uo=requestAnimationFrame(re):(i.scrollTop=L,an=i.scrollTop,Uo=null,ln=!1)};Uo=requestAnimationFrame(re)},qu=(i,g=500)=>{let h=En(i)-i.scrollTop;if(Math.abs(h)<1){an=i.scrollTop;return}if(Math.abs(h)>=$u){Er(),ln=!0,i.scrollTop=En(i),an=i.scrollTop,ln=!1;return}rc(i,()=>En(i),g,()=>Zt.isFollowing())},sc=()=>{let i=tc();ln=!0,i.scrollTop=En(i),an=i.scrollTop,ln=!1,en()},ac=i=>{let g=0,h=i;for(;h&&h!==ie;)g+=h.offsetTop,h=h.offsetParent;return g},ic=()=>{if(Ru()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let g=[...i].reverse().find(L=>L.role==="user");if(!g)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ie.querySelector(`[data-message-id="${h}"]`);if(!b)return!1;let S=Math.min(Math.max(0,ac(b)-Bl()),En(ie));return ln=!0,ie.scrollTop=S,an=ie.scrollTop,ln=!1,Qt()==="follow"&&!io(ie,Fs)&&Zt.pause(),en(),!0},lc=i=>{zn.style.height=`${Math.max(0,Math.round(i))}px`,yn&&(yn.spacerHeight=Math.max(0,i))},Lr=()=>{vo!==null&&(cancelAnimationFrame(vo),vo=null),Er(),yn=null,zn.style.height="0px"},Vu=i=>{vo!==null&&cancelAnimationFrame(vo),vo=requestAnimationFrame(()=>{vo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ie.querySelector(`[data-message-id="${g}"]`);if(!h)return;let b=ac(h),S=yn?.spacerHeight??0,L=ie.scrollHeight-S,{targetScrollTop:Q,spacerHeight:O}=Tp({anchorOffsetTop:b,topOffset:Bl(),viewportHeight:ie.clientHeight,contentHeight:L});yn={initialSpacerHeight:O,contentHeightAtAnchor:L,spacerHeight:O},lc(O),rc(ie,()=>Q,220)})},Ku=()=>{if($n()){if(!Zt.isFollowing()||io(ie,1))return;Qn(!hn);return}if(yn&&yn.initialSpacerHeight>0){let i=ie.scrollHeight-yn.spacerHeight,g=Mp({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:i});g!==yn.spacerHeight&&lc(g)}en()},Gu=i=>{let g=Qt();g==="follow"?(Gn(),Qn(!0)):g==="anchor-top"&&(Mr=!1,li=!0,Vu(i))},Qu=()=>{if(Qt()==="anchor-top"){if(li){Mr=!1;return}Mr=!0,Lr(),Gn(),Qn(!0)}},Xu=i=>{let g=new Map;i.forEach(h=>{let b=di.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(l.emit("assistant:message",h),!Ns&&(Qt()!=="anchor-top"||Dl())&&gi()&&(Kn+=1,fi(),en(),Fl(Kn===1?"1 new message below.":`${Kn} new messages below.`))),h.role==="assistant"&&b?.streaming&&h.streaming===!1&&l.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&l.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):l.emit("approval:requested",{approval:h.approval,message:h}))}),di.clear(),g.forEach((h,b)=>{di.set(b,h)})},Ju=(i,g,h)=>{let b=document.createElement("div"),L=(()=>{let R=r.find(Fe=>Fe.renderLoadingIndicator);if(R?.renderLoadingIndicator)return R.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(R,Fe)=>Fe==null?!1:typeof Fe=="string"?(R.textContent=Fe,!0):(R.appendChild(Fe),!0),O=new Set,G=new Set,re=r.some(R=>R.renderAskUserQuestion),le=[],se=[],xe=o.enableComponentStreaming!==!1,Ve=o.approval!==!1,gt=[];if(g.forEach(R=>{O.add(R.id);let Fe=re&&Lo(R),Se=Ve&&R.variant==="approval"&&!!R.approval,Oe=!Fe&&R.role==="assistant"&&!R.variant&&xe&&Ml(R);!Se&&qn.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),qn.delete(R.id)),!Oe&&bo.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(R.id));let At=Lo(R)?`:${R.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${R.agentMetadata?.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=vp(R,si)+At,xt=Fe||Se||Oe?null:xp(yo,R.id,dt);if(xt){b.appendChild(xt.cloneNode(!0)),Lo(R)&&R.toolCall?.id&&R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(G.add(R.toolCall.id),oa(R,o,Pe.composerOverlay));return}let ht=null,_t=r.find(ce=>!!(R.variant==="reasoning"&&ce.renderReasoning||R.variant==="tool"&&ce.renderToolCall||!R.variant&&ce.renderMessage)),Co=o.layout?.messages;if(Lo(R)&&R.agentMetadata?.askUserQuestionAnswered===!0){zo.delete(R.id),i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime");return}if(_i(R)&&o.features?.suggestReplies?.enabled!==!1)return;if(Lo(R)&&o.features?.askUserQuestion?.enabled!==!1){let ce=r.find(Ct=>typeof Ct.renderAskUserQuestion=="function");if(ce&&ut.current){let Ct=zo.get(R.id),qt=Ct!==dt,Bt=null;if(qt){let{payload:tt,complete:Et}=Zo(R),He=R.id,nt=()=>ut.current?.getMessages().find(tn=>tn.id===He);Bt=ce.renderAskUserQuestion({message:R,payload:tt,complete:Et,resolve:tn=>{let Ao=nt();Ao&&ut.current?.resolveAskUserQuestion(Ao,tn)},dismiss:()=>{let tn=nt();tn?.agentMetadata?.awaitingLocalTool&&(ut.current?.markAskUserQuestionResolved(tn),ut.current?.resolveAskUserQuestion(tn,"(dismissed)"))},config:o})}let ot=Ct!=null;if(qt&&Bt===null&&!ot){R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(G.add(R.toolCall.id),oa(R,o,Pe.composerOverlay));return}let Ue=document.createElement("div");Ue.className="persona-flex",Ue.id=`wrapper-${R.id}`,Ue.setAttribute("data-wrapper-id",R.id),Ue.setAttribute("data-ask-plugin-stub","true"),Ue.setAttribute("data-preserve-runtime","true"),b.appendChild(Ue),le.push({messageId:R.id,fingerprint:dt,bubble:Bt});return}else{R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(G.add(R.toolCall.id),oa(R,o,Pe.composerOverlay));return}}else if(Se){let ce=r.find(ot=>typeof ot.renderApproval=="function")??s,qt=qn.get(R.id)!==dt,Bt=null;if(qt&&ce?.renderApproval){let ot=R.id,Ue=(tt,Et)=>{let He=ut.current?.getMessages().find(nt=>nt.id===ot);He?.approval&&(He.approval.toolType==="webmcp"?ut.current?.resolveWebMcpApproval(He.id,tt):ut.current?.resolveApproval(He.approval,tt,Et))};Bt=ce.renderApproval({message:R,defaultRenderer:()=>Va(R,o),config:o,approve:tt=>Ue("approved",tt),deny:tt=>Ue("denied",tt)})}if(qt&&Bt===null)i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),qn.delete(R.id),ht=Va(R,o);else{let ot=document.createElement("div");ot.className="persona-flex",ot.id=`wrapper-${R.id}`,ot.setAttribute("data-wrapper-id",R.id),ot.setAttribute("data-approval-plugin-stub","true"),ot.setAttribute("data-preserve-runtime","true"),b.appendChild(ot),gt.push({messageId:R.id,fingerprint:dt,bubble:Bt});return}}else if(_t)if(R.variant==="reasoning"&&R.reasoning&&_t.renderReasoning){if(!te)return;ht=_t.renderReasoning({message:R,defaultRenderer:()=>pl(R,o),config:o})}else if(R.variant==="tool"&&R.toolCall&&_t.renderToolCall){if(!ge)return;ht=_t.renderToolCall({message:R,defaultRenderer:()=>fl(R,o),config:o})}else _t.renderMessage&&(ht=_t.renderMessage({message:R,defaultRenderer:()=>{let ce=dl(R,h,Co,o.messageActions,Me,{loadingIndicatorRenderer:L,widgetConfig:o});return R.role!=="user"&&wl(ce,R,o,_),ce},config:o}));if(!ht&&Oe){let ce=gu(R);if(ce){let Ct=bo.get(R.id),qt=Ct!==dt,Bt=o.wrapComponentDirectiveInBubble!==!1&&_n.getOptions(ce.component)?.bubbleChrome!==!1,ot=null;if(qt){let Ue=uu(ce,{config:o,message:R,transform:h});if(Ue&&ce.component==="PersonaArtifactInline"){let tt=Ue.hasAttribute("data-artifact-inline")?Ue:Ue.querySelector("[data-artifact-inline]"),Et=tt?.getAttribute("data-artifact-inline")??"",He=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Et):Et,nt=Et?i.querySelector(`#wrapper-${R.id}`)?.querySelector(`[data-artifact-inline="${He}"]`)??null:null;tt&&nt&&nt!==tt&&gp(nt)&&(tt===Ue?Ue=nt:tt.replaceWith(nt))}if(Ue)if(Bt){let tt=document.createElement("div");if(tt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),tt.id=`bubble-${R.id}`,tt.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let Et=document.createElement("div");Et.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Et.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),tt.appendChild(Et)}tt.appendChild(Ue),ot=tt}else{let tt=document.createElement("div");if(tt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",tt.id=`bubble-${R.id}`,tt.setAttribute("data-message-id",R.id),tt.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let Et=document.createElement("div");Et.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Et.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),tt.appendChild(Et)}tt.appendChild(Ue),ot=tt}}if(ot||Ct!=null){let Ue=document.createElement("div");Ue.className="persona-flex",Ue.id=`wrapper-${R.id}`,Ue.setAttribute("data-wrapper-id",R.id),Ue.setAttribute("data-component-directive-stub","true"),Ue.setAttribute("data-preserve-runtime","true"),Bt||Ue.classList.add("persona-w-full"),b.appendChild(Ue),se.push({messageId:R.id,fingerprint:dt,bubble:ot});return}}}if(!ht)if(R.variant==="reasoning"&&R.reasoning){if(!te)return;ht=pl(R,o)}else if(R.variant==="tool"&&R.toolCall){if(!ge)return;ht=fl(R,o)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;ht=Va(R,o)}else{let ce=o.layout?.messages;ce?.renderUserMessage&&R.role==="user"?ht=ce.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):ce?.renderAssistantMessage&&R.role==="assistant"?ht=ce.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):ht=dl(R,h,ce,o.messageActions,Me,{loadingIndicatorRenderer:L,widgetConfig:o}),R.role!=="user"&&ht&&wl(ht,R,o,_)}let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-${R.id}`,pt.setAttribute("data-wrapper-id",R.id),R.role==="user"&&pt.classList.add("persona-justify-end"),ht?.getAttribute("data-persona-component-directive")==="true"&&pt.classList.add("persona-w-full"),pt.appendChild(ht),Cp(yo,R.id,dt,pt),b.appendChild(pt)}),Pe.composerOverlay&&Pe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let Se=Fe.getAttribute("data-persona-ask-sheet-for");Se&&!G.has(Se)&&tr(Pe.composerOverlay,Se)}),o.features?.toolCallDisplay?.grouped){let R=[],Fe=[];g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&ge){Fe.push(Se);return}Se.variant==="reasoning"&&!te||(Fe.length>1&&R.push(Fe),Fe=[])}),Fe.length>1&&R.push(Fe),R.forEach((Se,Oe)=>{let At=Se.map(Ct=>Array.from(b.children).find(qt=>qt instanceof HTMLElement&&qt.getAttribute("data-wrapper-id")===Ct.id)).filter(Ct=>!!Ct);if(At.length<2)return;let dt=document.createElement("div");dt.className="persona-flex",dt.id=`wrapper-tool-group-${Oe}-${Se[0].id}`,dt.setAttribute("data-wrapper-id",`tool-group-${Oe}-${Se[0].id}`);let xt=document.createElement("div");xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",xt.setAttribute("data-persona-tool-group","true");let ht=document.createElement("div");ht.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let _t=`Called ${Se.length} tools`,Co=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Ct=>Ct.toolCall).filter(Ct=>!!Ct),defaultSummary:_t,config:o});Q(ht,Co)||(ht.textContent=_t);let pt=document.createElement("div");pt.className="persona-tool-group-stack persona-flex persona-flex-col";let ce=o.features?.toolCallDisplay?.groupedMode==="summary";xt.appendChild(ht),ce||xt.appendChild(pt),dt.appendChild(xt),At[0].before(dt),At.forEach((Ct,qt)=>{if(ce){Ct.remove();return}let Bt=document.createElement("div");Bt.className="persona-tool-group-item persona-relative",Bt.setAttribute("data-persona-tool-group-item","true"),qt<At.length-1&&Bt.setAttribute("data-persona-tool-group-connector","true"),Bt.appendChild(Ct),pt.appendChild(Bt)})})}Ap(yo,O);let at=g.some(R=>R.role==="assistant"&&R.streaming),jt=g[g.length-1],Wt=jt?.role==="assistant"&&!jt.streaming&&jt.variant!=="approval";if(hn&&g.some(R=>R.role==="user")&&!at&&!Wt){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:hs},Fe=r.find(Oe=>Oe.renderLoadingIndicator),Se=null;if(Fe?.renderLoadingIndicator&&(Se=Fe.renderLoadingIndicator(R)),Se===null&&o.loadingIndicator?.render&&(Se=o.loadingIndicator.render(R)),Se===null&&(Se=hs()),Se){let Oe=document.createElement("div"),At=o.loadingIndicator?.showBubble!==!1;Oe.className=At?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Oe.setAttribute("data-typing-indicator","true"),Oe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Oe.appendChild(Se);let dt=document.createElement("div");dt.className="persona-flex",dt.id="wrapper-typing-indicator",dt.setAttribute("data-wrapper-id","typing-indicator"),dt.appendChild(Oe),b.appendChild(dt)}}if(!hn&&g.length>0){let R=g[g.length-1],Fe={config:o,lastMessage:R,messageCount:g.length},Se=r.find(At=>At.renderIdleIndicator),Oe=null;if(Se?.renderIdleIndicator&&(Oe=Se.renderIdleIndicator(Fe)),Oe===null&&o.loadingIndicator?.renderIdle&&(Oe=o.loadingIndicator.renderIdle(Fe)),Oe){let At=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;At.className=dt?["persona-max-w-[85%]","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-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),At.setAttribute("data-idle-indicator","true"),At.appendChild(Oe);let xt=document.createElement("div");xt.className="persona-flex",xt.id="wrapper-idle-indicator",xt.setAttribute("data-wrapper-id","idle-indicator"),xt.appendChild(At),b.appendChild(xt)}}if(Ea(i,b),le.length>0)for(let{messageId:R,fingerprint:Fe,bubble:Se}of le){let Oe=i.querySelector(`#wrapper-${R}`);Oe&&Se!==null&&(Oe.replaceChildren(Se),Oe.setAttribute("data-bubble-fp",Fe),zo.set(R,Fe))}if(zo.size>0)for(let R of zo.keys())O.has(R)||zo.delete(R);if(se.length>0)for(let{messageId:R,fingerprint:Fe,bubble:Se}of se){let Oe=i.querySelector(`#wrapper-${R}`);Oe&&Se!==null&&(Oe.replaceChildren(Se),Oe.setAttribute("data-bubble-fp",Fe),bo.set(R,Fe))}if(bo.size>0)for(let R of bo.keys())O.has(R)||bo.delete(R);if(gt.length>0)for(let{messageId:R,fingerprint:Fe,bubble:Se}of gt){let Oe=i.querySelector(`#wrapper-${R}`);Oe&&Se!==null&&(Oe.replaceChildren(Se),Oe.setAttribute("data-bubble-fp",Fe),qn.set(R,Fe))}if(qn.size>0)for(let R of qn.keys())O.has(R)||qn.delete(R)},Pr=(i,g,h)=>{Ju(i,g,h),Vl()},Ir=null,Yu=()=>{if(Ir)return;let i=h=>{let b=h.composedPath();b.includes(We)||Qe&&b.includes(Qe)||ft(!1,"user")};Ir=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},cc=()=>{if(!Ir)return;(t.ownerDocument??document).removeEventListener("pointerdown",Ir,!0),Ir=null};qe.push(()=>cc());let Rr=null,Zu=()=>{if(Rr)return;let i=h=>{h.key==="Escape"&&(h.isComposing||ft(!1,"user"))};Rr=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},dc=()=>{if(!Rr)return;(t.ownerDocument??document).removeEventListener("keydown",Rr,!0),Rr=null};qe.push(()=>dc());let Wr=!1,pc=new Set,ef=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},jo=()=>{if(!J())return;let i=Pe.peekBanner,g=Pe.peekTextNode;if(!i||!g)return;if($){i.classList.remove("persona-pill-peek--visible");return}let h=_?.getMessages()??[],b;for(let Wt=h.length-1;Wt>=0;Wt--){let R=h[Wt];if(R.role==="assistant"&&R.content){b=R;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let S=b.content,L=!!b.streaming,Q=ef(),O=Ia(Q),G=O.type!=="none"?ur(O.type,Q?.plugins):null,re=G?.isAnimating?.(b)===!0,le=G!==null&&(L||re);le&&G&&!pc.has(G.name)&&(Ba(G,t),pc.add(G.name));let se=le&&G?.containerClass?G.containerClass:null,xe=g.dataset.personaPeekStreamClass??null;xe&&xe!==se&&(g.classList.remove(xe),delete g.dataset.personaPeekStreamClass),se&&xe!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),le?(g.style.setProperty("--persona-stream-step",`${O.speed}ms`),g.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ve=le?Ra(S,O.buffer,G,b,L):S;if(le&&O.placeholder==="skeleton"&&L&&(!Ve||!Ve.trim())){let Wt=document.createElement("div"),R=ps();R.classList.add("persona-pill-peek__skeleton"),Wt.appendChild(R),Ea(g,Wt)}else{let Wt=Math.max(0,Ve.length-100),R=Ve.length>100?Ve.slice(-100):Ve,Fe=Zn(R);if(!le||!G){let Se=Ve.length>100?`\u2026${R}`:R;g.textContent!==Se&&(g.textContent=Se)}else{let Se=Fe;(G.wrap==="char"||G.wrap==="word")&&(Se=ds(Fe,G.wrap,`peek-${b.id}`,{skipTags:G.skipTags,startIndex:Wt}));let Oe=document.createElement("div");if(Oe.innerHTML=Se,G.useCaret&&R.length>0){let At=Wa(),dt=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),xt=dt[dt.length-1];xt?.parentNode?xt.parentNode.insertBefore(At,xt.nextSibling):Oe.appendChild(At)}Ea(g,Oe),G.onAfterRender?.({container:g,bubble:i,messageId:b.id,message:b,speed:O.speed,duration:O.duration})}}let jt=hn||Wr;i.classList.toggle("persona-pill-peek--visible",jt)};if(J()){let i=Pe.peekBanner;if(i){let b=S=>{S.preventDefault(),S.stopPropagation(),ft(!0,"user")};i.addEventListener("pointerdown",b),qe.push(()=>{i.removeEventListener("pointerdown",b)})}let g=()=>{Wr||(Wr=!0,jo())},h=()=>{Wr&&(Wr=!1,jo())};me.addEventListener("pointerenter",g),me.addEventListener("pointerleave",h),qe.push(()=>{me.removeEventListener("pointerenter",g),me.removeEventListener("pointerleave",h)}),Qe&&(Qe.addEventListener("pointerenter",g),Qe.addEventListener("pointerleave",h),qe.push(()=>{Qe.removeEventListener("pointerenter",g),Qe.removeEventListener("pointerleave",h)}))}let tf=i=>{let g=o.launcher?.composerBar??{},h=g.expandedSize??"anchored",b=g.bottomOffset??"16px",S=g.collapsedMaxWidth,L=g.expandedMaxWidth??"880px",Q=g.expandedTopOffset??"5vh",O=g.modalMaxWidth??"880px",G=g.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",se=We.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Qe){let xe=Qe.style;xe.bottom=b,xe.width=S??""}if(i&&h!=="fullscreen"){if(h==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=O,se.maxWidth=re,se.maxHeight=G,se.height=G;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${b} + ${le})`,se.top=Q,se.width=L,se.maxWidth=re}},Br=()=>{if(!D())return;if(J()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",le=$?"expanded":"collapsed";We.dataset.state=le,We.dataset.expandedSize=re,Qe&&(Qe.dataset.state=le,Qe.dataset.expandedSize=re),We.style.removeProperty("display"),We.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),tf($),pe.style.display=$?"flex":"none",Ws(),$?(Yu(),Zu()):(cc(),dc()),jo();return}let i=Nt(o),g=t.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,S=g.innerWidth<=h,L=b&&S&&T,Q=un(o).reveal;$?(We.style.removeProperty("display"),We.style.display=i?"flex":"",We.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0"),me.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Ut&&(Ut.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!L?(We.style.removeProperty("display"),We.style.display="flex",We.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(We.style.setProperty("display","none","important"),We.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(We.style.display="",We.classList.add("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100"),me.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=i?"none":"":Ut&&(Ut.style.display=i?"none":""))},ft=(i,g="user")=>{if(!D()||$===i)return;let h=$;$=i,Br();let b=(()=>{let L=o.launcher?.sidebarMode??!1,Q=t.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,re=Q.innerWidth<=G,le=Nt(o)&&O&&re,se=J()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return L||O&&re&&T||le||se})();if($&&b){if(!Cn){let L=t.getRootNode(),Q=L instanceof ShadowRoot?L.host:t.closest(".persona-host");Q&&(Cn=rl(Q,o.launcher?.zIndex??zt))}An||(An=sl(t.ownerDocument))}else $||(Cn?.(),Cn=null,An?.(),An=null);$&&(Nr(),ic()||(Qt()==="follow"?Qn(!0):sc()));let S={open:$,source:g,timestamp:Date.now()};$&&!h?l.emit("widget:opened",S):!$&&h&&l.emit("widget:closed",S),l.emit("widget:state",{open:$,launcherEnabled:T,voiceActive:Xe.active,streaming:_.isStreaming()})},mi=i=>{lt(i?"stop":"send"),K&&(K.disabled=i),Hs.buttons.forEach(g=>{g.disabled=i}),U.dataset.personaComposerStreaming=i?"true":"false",U.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=i)})},hi=()=>{Xe.active||he&&he.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>hi(),200)});let uc=()=>{F.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",y.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",he.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ie.querySelector("[data-persona-intro-card]");if(i){let h=o.copy?.showWelcomeCard!==!1;i.style.display=h?"":"none",h?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(de.textContent=o.copy?.sendButtonLabel??"Send"),he.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',he.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=c.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{C(g=>({...g,sessionId:i}))}});let wo=null,nf=()=>{wo==null&&(wo=setInterval(()=>{let i=be.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(wo),wo=null;return}let g=Date.now();i.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=aa(g-b))})},100))},yi=(i,g)=>{if(Object.is(i,g))return!0;if(i===null||g===null||typeof i!="object"||typeof g!="object")return!1;if(Array.isArray(i)||Array.isArray(g))return!Array.isArray(i)||!Array.isArray(g)||i.length!==g.length?!1:i.every((Q,O)=>yi(Q,g[O]));let h=i,b=g,S=Object.keys(h),L=Object.keys(b);return S.length===L.length&&S.every(Q=>Object.prototype.hasOwnProperty.call(b,Q)&&yi(h[Q],b[Q]))},fc=i=>{let{content:g,rawContent:h,llmContent:b,...S}=i;return S},bi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Ml(i),of=(i,g,h)=>{if(i.length!==g.length)return!1;let b=i[h.index],S=g[h.index];return!b||!S||b.id!==h.id||S.id!==h.id?!1:(!Object.is(b.content,S.content)||!Object.is(b.rawContent,S.rawContent)||!Object.is(b.llmContent,S.llmContent))&&bi(b)&&bi(S)&&yi(fc(b),fc(S))},gc=null,qo=null,xo=null,In=null,_s=i=>{gc=i;let g,h;qo=null;for(let S=i.length-1;S>=0;S-=1){let L=i[S];if(!g&&L.role==="user"&&(g=L),!h&&L.role==="assistant"&&(h=L),!qo&&bi(L)&&(qo={index:S,id:L.id}),g&&h&&qo)break}Pr(be,i,Ce),Yi(be,gn.artifacts,{suppressTransition:hn}),nf(),ri(i),Qn(!hn),Xu(i),i.length===0&&(Lr(),Mr=!0,li=!1),!ai||Ns?(ai=!0,ii=g?.id??null,ci=h?.id??null):g&&g.id!==ii?(ii=g.id,Gu(g.id)):h&&h.id!==ci&&Qu(),h&&(ci=h.id);let b=Xe.lastUserMessageId;g&&g.id!==b&&(Xe.lastUserMessageId=g.id,l.emit("user:message",g)),Xe.lastUserMessageWasVoice=!!g?.viaVoice,ui(i),jo()},vi=()=>{In!==null&&(cancelAnimationFrame(In),In=null);let i=xo;xo=null,i&&_s(i)},mc=()=>{In!==null&&cancelAnimationFrame(In),In=null,xo=null},rf=i=>{let g=xo??gc;if(hn&&g&&qo&&of(g,i,qo)){xo=i,In===null&&(In=requestAnimationFrame(()=>{In=null;let h=xo;xo=null,h&&_s(h)}));return}if(i.length===0){mc(),_s(i);return}vi(),_s(i)};_=new ga(o,{onMessagesChanged(i){rf(i)},onStatusChanged(i){let g=o.statusIndicator??{};Mt(M,(b=>b==="idle"?g.idleText??It.idle:b==="connecting"?g.connectingText??It.connecting:b==="connected"?g.connectedText??It.connected:b==="error"?g.errorText??It.error:b==="paused"?g.pausedText??It.paused:b==="resuming"?g.resumingText??It.resuming:It[b])(i),g,i)},onStreamingChanged(i){i||(_?.getMessages().length===0?mc():vi()),hn=i,mi(i),_&&Pr(be,_.getMessages(),Ce),i||Qn(!0),en(),Fl(i?"Responding\u2026":"Response complete."),jo()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Rn(),Ko();break;case"processing":Rn(),hf();break;case"speaking":Rn(),yf();break;default:i==="idle"&&_.isBargeInActive()?(Rn(),Ko(),K?.setAttribute("aria-label","End voice session")):(Xe.active=!1,Rn(),Pn("system"),bn());break}},onArtifactsState(i){gn=i,i.artifacts.length===0&&(Oo=!1),Yi(be,i.artifacts,{suppressTransition:hn}),Ln(),ui()},onReconnect(i){let{executionId:g,lastEventId:h}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:g,after:h}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:g,after:h,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:g,after:h})}}),ut.current=_,qe.push(()=>_.cancel());let wi=null;if(_.onReadAloudChange((i,g)=>{jl=i,ql=g,Vl();let h=i??wi;i&&(wi=i);let b=h?_.getMessages().find(S=>S.id===h)??null:null;l.emit("message:read-aloud",{messageId:h,message:b,state:g,timestamp:Date.now()}),g==="idle"&&(wi=null)}),ai=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&_.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ae||o.onSSEEvent)&&_.setSSEEventCallback((i,g)=>{o.onSSEEvent?.(i,g),ze?.processEvent(i,g),Ae?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(g)})});let hc=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=El(i.metadata),E.syncFromMetadata()),i.messages?.length){Ns=!0;try{_.hydrateMessages(i.messages)}finally{Ns=!1}}i.artifacts?.length&&_.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>hc()):hc();let yc=()=>{!J()||$||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ft(!0,"auto")},sf=(i,g)=>i?g?{refs:[...i.refs,...g.refs],finalize:async()=>{let[h,b]=await Promise.allSettled([i.finalize(),g.finalize()]),S=[];return h.status==="fulfilled"?S.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),b.status==="fulfilled"?S.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),vy(S)}}:i:g,af=()=>{let g=he.getInlineMessageFields?.();return g&&g.contentSegments.some(b=>b.kind==="mention")?g.contentSegments:void 0},Hr=!1,lf=async i=>{let g=he.value.trim(),h=St?.hasAttachments()??!1,b=g?await(Yt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(b?.kind==="action"){he.value="",he.style.height="auto",Dr(),Yt?.clear();return}let S=Yt?.collectForSubmit()??null,L=b?.kind==="server"?b.mentions:null,Q=sf(S,L),O=b?.kind==="prompt"?b.sendText:g,G=!!S&&S.refs.length>0;if(!O&&!h&&!G&&!L)return;yc();let re;h&&(re=[],re.push(...St.getContentParts()),O&&re.push(or(O)));let le=b?.kind==="prompt"?void 0:af();he.value="",he.style.height="auto",Dr(),_.sendMessage(O,{contentParts:re,mentions:Q??void 0,contentSegments:le,viaVoice:i?.viaVoice}),h&&St.clearAttachments(),S&&Yt?.clear()},xi=async i=>{if(!Hr){Hr=!0;try{await lf(i)}finally{Hr=!1}}},bc=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),ze?.reset(),Ne?.update();return}Hr||xi()},cf=()=>o.features?.composerHistory!==!1,Ci={...tl},Ai=!1,Dr=()=>{Ci={...tl}},df=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),pf=i=>{if(!he)return;Ai=!0,he.value=i,he.dispatchEvent(new Event("input",{bubbles:!0})),Ai=!1;let g=he.value.length;he.setSelectionRange(g,g)},uf=i=>{Ai||(i.isComposing||Yt?.handleInput(i.inputType??void 0),Dr())},ff=i=>{if(he&&!(!i.isComposing&&Yt?.handleKeydown(i))){if(cf()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let g=he.selectionStart===0&&he.selectionEnd===0,h=bp({direction:i.key==="ArrowUp"?"up":"down",history:df(),currentValue:he.value,atStart:g,state:Ci});if(Ci=h.state,h.handled){i.preventDefault(),h.value!==void 0&&pf(h.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(_.isStreaming()){i.preventDefault();return}if(Hr){i.preventDefault();return}Dr(),i.preventDefault(),de.click()}}},vc=i=>{i.key!=="Escape"||i.isComposing||_.isStreaming()&&i.composedPath().includes(pe)&&(_.cancel(),ze?.reset(),Ne?.update(),Dr(),i.preventDefault(),i.stopImmediatePropagation())},gf=async i=>{if(o.attachments?.enabled!==!0||!St)return;let g=my(i.clipboardData);g.length!==0&&(i.preventDefault(),await St.handleFiles(g))},cn=null,Sn=!1,Vo=null,wt=null,wc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$s=(i="user")=>{if(Sn||_.isStreaming())return;let g=wc();if(!g)return;cn=new g;let b=(o.voiceRecognition??{}).pauseDuration??2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let S=he.value;cn.onresult=L=>{let Q="",O="";for(let re=0;re<L.results.length;re++){let le=L.results[re],se=le[0].transcript;le.isFinal?Q+=se+" ":O=se}let G=S+Q+O;he.value=G,Vo&&clearTimeout(Vo),(Q||O)&&(Vo=window.setTimeout(()=>{he.value.trim()&&cn&&Sn&&(Xn(),xi({viaVoice:!0}))},b))},cn.onerror=L=>{L.error!=="no-speech"&&Xn()},cn.onend=()=>{if(Sn){let L=he.value.trim();L&&L!==S.trim()&&xi({viaVoice:!0}),Xn()}};try{if(cn.start(),Sn=!0,Xe.active=!0,i!=="system"&&(Xe.manuallyDeactivated=!1),Pn(i),bn(),K){let L=o.voiceRecognition??{};wt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:L.iconName??"mic",iconSize:parseFloat(L.iconSize??o.sendButton?.size??"40")||24};let Q=L.recordingBackgroundColor,O=L.recordingIconColor,G=L.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=O??"var(--persona-voice-recording-indicator, #ffffff)",O){let re=K.querySelector("svg");re&&re.setAttribute("stroke",O)}G&&(K.style.borderColor=G),K.setAttribute("aria-label","Stop voice recognition")}}catch{Xn("system")}},Xn=(i="user")=>{if(Sn){if(Sn=!1,Vo&&(clearTimeout(Vo),Vo=null),cn){try{cn.stop()}catch{}cn=null}if(Xe.active=!1,Pn(i),bn(),K){if(K.classList.remove("persona-voice-recording"),wt){K.style.backgroundColor=wt.backgroundColor,K.style.color=wt.color,K.style.borderColor=wt.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",wt.color||"currentColor"),wt=null}K.setAttribute("aria-label","Start voice recognition")}}},mf=(i,g)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),b=i?.provider?.type==="runtype",S=i?.provider?.type==="custom";if(!(h||b||S))return null;let Q=m("div","persona-send-button-wrapper"),O=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let G=i?.iconName??"mic",re=g?.size??"40px",le=i?.iconSize??re,se=parseFloat(le)||24,xe=i?.backgroundColor??g?.backgroundColor,Ve=i?.iconColor??g?.textColor;O.style.width=le,O.style.height=le,O.style.minWidth=le,O.style.minHeight=le,O.style.fontSize="18px",O.style.lineHeight="1",Ve?O.style.color=Ve:O.style.color="var(--persona-text, #111827)";let at=ne(G,se,Ve||"currentColor",1.5);at?O.appendChild(at):O.textContent="\u{1F3A4}",xe?O.style.backgroundColor=xe:O.style.backgroundColor="",i?.borderWidth&&(O.style.borderWidth=i.borderWidth,O.style.borderStyle="solid"),i?.borderColor&&(O.style.borderColor=i.borderColor),i?.paddingX&&(O.style.paddingLeft=i.paddingX,O.style.paddingRight=i.paddingX),i?.paddingY&&(O.style.paddingTop=i.paddingY,O.style.paddingBottom=i.paddingY),Q.appendChild(O);let jt=i?.tooltipText??"Start voice recognition";if((i?.showTooltip??!1)&&jt){let R=m("div","persona-send-button-tooltip");R.textContent=jt,Q.appendChild(R)}return{micButton:O,micButtonWrapper:Q}},Si=()=>{if(!K||wt)return;let i=o.voiceRecognition??{};wt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Ti=(i,g)=>{if(!K)return;let h=K.querySelector("svg");h&&h.remove();let b=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),S=ne(i,b,g,1.5);S&&K.appendChild(S)},zs=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ko=()=>{if(!K)return;Si();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,h=i.recordingIconColor,b=i.recordingBorderColor;if(zs(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let S=K.querySelector("svg");S&&S.setAttribute("stroke",h)}b&&(K.style.borderColor=b),K.setAttribute("aria-label","Stop voice recognition")},hf=()=>{if(!K)return;Si();let i=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),h=i.processingIconName??"loader",b=i.processingIconColor??wt?.color??"",S=i.processingBackgroundColor??wt?.backgroundColor??"",L=i.processingBorderColor??wt?.borderColor??"";zs(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=S,K.style.borderColor=L;let Q=b||"currentColor";K.style.color=Q,Ti(h,Q),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},yf=()=>{if(!K)return;Si();let i=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=i.speakingIconName??h,S=i.speakingIconColor??(g==="barge-in"?i.recordingIconColor??wt?.color??"":wt?.color??""),L=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),Q=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":wt?.borderColor??"");zs(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=L,K.style.borderColor=Q;let O=S||"currentColor";K.style.color=O,Ti(b,O);let G=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",G),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},Rn=()=>{K&&(zs(),wt&&(K.style.backgroundColor=wt.backgroundColor??"",K.style.color=wt.color??"",K.style.borderColor=wt.borderColor??"",Ti(wt.iconName,wt.color||"currentColor"),wt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},Us=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=_.getVoiceStatus(),g=_.getVoiceInterruptionMode();if(g==="none"&&(i==="processing"||i==="speaking"))return;if(g==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,bn(),Pn("user"),Rn()});return}_.toggleVoice().then(()=>{Xe.active=_.isVoiceActive(),Xe.manuallyDeactivated=!_.isVoiceActive(),bn(),Pn("user"),_.isVoiceActive()?Ko():Rn()});return}if(Sn){let i=he.value.trim();Xe.manuallyDeactivated=!0,bn(),Xn("user"),i&&(he.value="",he.style.height="auto",_.sendMessage(i))}else Xe.manuallyDeactivated=!1,bn(),$s("user")};_l=Us,K&&(K.addEventListener("click",Us),qe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Rn()):Xn("system"),K&&K.removeEventListener("click",Us)}));let bf=l.on("assistant:complete",()=>{Zl&&(Xe.active||Xe.manuallyDeactivated||Zl==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Xe.active=_.isVoiceActive(),Pn("auto"),_.isVoiceActive()&&Ko()}):$s("auto"))},600))});qe.push(bf);let vf=l.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});qe.push(vf);let xc=()=>{ft(!$,"user")},Ft=null,Ut=null;if(T&&!J()){let{instance:i,element:g}=il({config:o,plugins:r,onToggle:xc});Ft=i,i||(Ut=g)}Ft?t.appendChild(Ft.element):Ut&&t.appendChild(Ut),Br(),ri(),uc(),mi(_.isStreaming()),ic()||(Qt()==="follow"?Qn(!0):sc()),zu(),z&&(!T||J()?setTimeout(()=>hi(),0):$&&setTimeout(()=>hi(),200));let Nr=()=>{if(J()){Fo(),Br();return}let i=Nt(o),g=o.launcher?.sidebarMode??!1,h=i||g||(o.launcher?.fullHeight??!1),b=t.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640,Q=b.innerWidth<=L,O=S&&Q&&T;try{if(O){Cr(),Ar=Rs();return}let G=!1;q&&(q=!1,Cr(),G=!0);let re=Rs();if(!G&&re!==Ar&&(Cr(),G=!0),Ar=re,G&&ni(),!T&&!i){me.style.height="",me.style.width="";return}if(!g&&!i){let se=o?.launcher?.width??o?.launcherWidth??On;me.style.width=se,me.style.maxWidth=se}if(Is(),!h){let le=b.innerHeight,se=64,xe=o.launcher?.heightOffset??0,Ve=Math.max(200,le-se),gt=Math.min(640,Ve),at=Math.max(200,gt-xe);me.style.height=`${at}px`}}finally{if(Fo(),Br(),$&&T){let re=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),le=o.launcher?.sidebarMode??!1,se=o.launcher?.mobileFullscreen??!0,xe=Nt(o)&&se&&re,Ve=le||se&&re&&T||xe;if(Ve&&!An){let gt=t.getRootNode(),at=gt instanceof ShadowRoot?gt.host:t.closest(".persona-host");at&&!Cn&&(Cn=rl(at,o.launcher?.zIndex??zt)),An=sl(t.ownerDocument)}else Ve||(Cn?.(),Cn=null,An?.(),An=null)}}};Nr();let Cc=t.ownerDocument.defaultView??window;if(Cc.addEventListener("resize",Nr),qe.push(()=>Cc.removeEventListener("resize",Nr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Fo()});i.observe(U),qe.push(()=>i.disconnect())}an=ie.scrollTop;let Ac=En(ie),wf=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},Mi=()=>Sp(wf(),ie),Sc=()=>{let i=ie.scrollTop,g=En(ie),h=g<Ac;if(Ac=g,!$n()){an=i,en();return}let{action:b,nextLastScrollTop:S}=La({following:Zt.isFollowing(),currentScrollTop:i,lastScrollTop:an,nearBottom:io(ie,Fs),userScrollThreshold:_u,isAutoScrolling:ln||Ds||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(an=S,b==="resume"){Mi()||Gn();return}b==="pause"&&kr()};if(ie.addEventListener("scroll",Sc,{passive:!0}),qe.push(()=>ie.removeEventListener("scroll",Sc)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Ku()});i.observe(be),i.observe(ie),qe.push(()=>i.disconnect())}let Tc=()=>{$n()&&Zt.isFollowing()&&Mi()&&kr()},Mc=ie.ownerDocument;Mc.addEventListener("selectionchange",Tc),qe.push(()=>{Mc.removeEventListener("selectionchange",Tc)});let xf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Ec=i=>{Hl()&&$n()&&Zt.isFollowing()&&xf.has(i.key)&&kr()},kc=i=>{if(!Hl()||!$n()||!Zt.isFollowing())return;let g=i.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&kr()};ie.addEventListener("keydown",Ec),ie.addEventListener("focusin",kc),qe.push(()=>{ie.removeEventListener("keydown",Ec),ie.removeEventListener("focusin",kc)});let Lc=i=>{if(!$n())return;let g=Pa({following:Zt.isFollowing(),deltaY:i.deltaY,nearBottom:io(ie,Fs),resumeWhenNearBottom:!0});g==="pause"?kr():g==="resume"&&!Mi()&&Gn()};ie.addEventListener("wheel",Lc,{passive:!0}),qe.push(()=>ie.removeEventListener("wheel",Lc)),Lt.addEventListener("click",()=>{Lr(),ie.scrollTop=ie.scrollHeight,an=ie.scrollTop,Gn(),Qn(!0),en()}),qe.push(()=>Lt.remove()),qe.push(()=>{nc(),Lr()});let Pc=()=>{A&&(ho&&(A.removeEventListener("click",ho),ho=null),D()?(A.style.display="",ho=()=>{ft(!1,"user")},A.addEventListener("click",ho)):A.style.display="none")};Pc(),(()=>{let{clearChatButton:i}=Pe;i&&i.addEventListener("click",()=>{_.clearMessages(),yo.clear(),Gn(),tr(Pe.composerOverlay);try{localStorage.removeItem(hr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==hr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&pi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},E.syncFromMetadata(),Ae?.clear(),ze?.reset(),Ne?.update()})})(),X&&X.addEventListener("submit",bc);let Ic=[["keydown",ff],["input",uf],["paste",gf],["focus",Hu]],Rc=i=>{if(i)for(let[g,h]of Ic)i.addEventListener(g,h)},Wc=i=>{if(i)for(let[g,h]of Ic)i.removeEventListener(g,h)};Rc(he),Yt?.onComposerSwap((i,g)=>{Wc(g),he=i,Rc(i)});let Bc=t.ownerDocument??document;Bc.addEventListener("keydown",vc,!0);let Hc="persona-attachment-drop-active",Fr=0,Ei=()=>{Fr=0,pe.classList.remove(Hc)},Go=()=>o.attachments?.enabled===!0&&St!==null,Dc=i=>{!Ga(i.dataTransfer)||!Go()||(Fr++,Fr===1&&pe.classList.add(Hc))},Nc=i=>{!Ga(i.dataTransfer)||!Go()||(Fr--,Fr<=0&&Ei())},Fc=i=>{!Ga(i.dataTransfer)||!Go()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Oc=i=>{if(!Ga(i.dataTransfer)||!Go())return;i.preventDefault(),i.stopPropagation(),Ei();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&St.handleFiles(g)},Jn=!0;pe.addEventListener("dragenter",Dc,Jn),pe.addEventListener("dragleave",Nc,Jn),t.addEventListener("dragover",Fc,Jn),t.addEventListener("drop",Oc,Jn);let js=t.ownerDocument,_c=i=>{Go()&&i.preventDefault()},$c=i=>{Go()&&i.preventDefault()};js.addEventListener("dragover",_c),js.addEventListener("drop",$c),qe.push(()=>{X&&X.removeEventListener("submit",bc),Wc(he),Bc.removeEventListener("keydown",vc,!0),Yt?.destroy()}),qe.push(()=>{pe.removeEventListener("dragenter",Dc,Jn),pe.removeEventListener("dragleave",Nc,Jn),t.removeEventListener("dragover",Fc,Jn),t.removeEventListener("drop",Oc,Jn),js.removeEventListener("dragover",_c),js.removeEventListener("drop",$c),Ei()}),qe.push(()=>{_.cancel()}),Ft?qe.push(()=>{Ft?.destroy()}):Ut&&qe.push(()=>{Ut?.remove()});let Pt={update(i){let g=o.toolCall,h=o.messageActions,b=o.layout?.messages,S=o.colorScheme,L=o.loadingIndicator,Q=o.iterationDisplay,O=o.features?.showReasoning,G=o.features?.showToolCalls,re=o.features?.toolCallDisplay,le=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type;o=lu(o,i),Ws(),rs(t,o),ws(t,o),xs(t,o),Ln(),o.colorScheme!==S&&Yl();let xe=Cl.getForInstance(o.plugins);r.length=0,r.push(...xe),T=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,te=o.features?.showReasoning??!0,ge=o.features?.showToolCalls??!0,ae=o.features?.scrollToBottom??{};let Ve=Qt();Z=o.features?.scrollBehavior??{},Ve!==Qt()&&(Lr(),Gn()),Ol(),en();let gt=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!gt){if(Ae||(ue=new bs(we),Ae=new ys(Te,ue),ze=ze??new vs,ue.open().then(()=>Ae?.restore()).catch(()=>{}),_.setSSEEventCallback((ee,Ge)=>{o.onSSEEvent?.(ee,Ge),ze?.processEvent(ee,Ge),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!st&&B){let ee=o.features?.eventStream?.classNames,Ge="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");st=m("button",Ge),st.style.width="28px",st.style.height="28px",st.style.color=Kt.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let mt=ne("activity","18px","currentColor",1.5);mt&&st.appendChild(mt);let je=Pe.clearChatButtonWrapper,rt=Pe.closeButtonWrapper,$t=je||rt;$t&&$t.parentNode===B?B.insertBefore(st,$t):B.appendChild(st),st.addEventListener("click",()=>{it?wr():Ya()})}}else!Y&&gt&&(wr(),st&&(st.remove(),st=null),Ae?.clear(),ue?.destroy(),Ae=null,ue=null,ze?.reset(),ze=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Ut&&(Ut.remove(),Ut=null),o.launcher?.enabled!==!1&&!Ft&&!Ut){let{instance:ee,element:Ge}=il({config:o,plugins:r,onToggle:xc});Ft=ee,ee||(Ut=Ge),t.appendChild(Ge)}Ft&&Ft.update(o),W&&o.launcher?.title!==void 0&&(W.textContent=o.launcher.title),V&&o.launcher?.subtitle!==void 0&&(V.textContent=o.launcher.subtitle);let at=o.layout?.header;if(at?.layout!==j&&B){let ee=at?Na(o,at,{showClose:D(),onClose:()=>ft(!1,"user")}):Bo({config:o,showClose:D(),onClose:()=>ft(!1,"user")});yt.replaceHeader(ee),B=yt.header.element,k=yt.header.iconHolder,W=yt.header.headerTitle,V=yt.header.headerSubtitle,A=yt.header.closeButton,j=at?.layout}else if(at){if(k&&(k.style.display=at.showIcon===!1?"none":""),W&&(W.style.display=at.showTitle===!1?"none":""),V&&(V.style.display=at.showSubtitle===!1?"none":""),A){let ee=D()&&at.showCloseButton!==!1;A.style.display=ee?"":"none"}if(Pe.clearChatButtonWrapper){let ee=at.showClearChat;if(ee!==void 0){Pe.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Ge}=Pe;Ge&&!Ge.classList.contains("persona-absolute")&&(ee?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let Wt=o.layout?.showHeader!==!1;B&&(B.style.display=Wt?"":"none");let R=o.layout?.showFooter!==!1;U&&(U.style.display=R?"":"none"),Fo(),en(),T!==x?T?ft(I,"auto"):($=!0,Br()):I!==N&&ft(I,"auto"),N=I,x=T,Nr(),Pc();let Oe=JSON.stringify(o.toolCall)!==JSON.stringify(g),At=JSON.stringify(o.messageActions)!==JSON.stringify(h),dt=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),xt=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,ht=o.iterationDisplay!==Q,_t=(o.features?.showReasoning??!0)!==(O??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(le);(Oe||At||dt||xt||ht||_t)&&_&&(si++,Pr(be,_.getMessages(),Ce));let pt=o.features?.streamAnimation?.type;if(pt!==se&&pt&&pt!=="none"){let ee=ur(pt,o.features?.streamAnimation?.plugins);ee&&Ba(ee,t)}let ce=o.launcher??{},Ct=ce.headerIconHidden??!1,qt=o.layout?.header?.showIcon,Bt=Ct||qt===!1,ot=ce.headerIconName,Ue=ce.headerIconSize??"48px";if(k){let ee=pe.querySelector(".persona-border-b-persona-divider"),Ge=ee?.querySelector(".persona-flex-col");if(Bt)k.style.display="none",ee&&Ge&&!ee.contains(Ge)&&ee.insertBefore(Ge,ee.firstChild);else{if(k.style.display="",k.style.height=Ue,k.style.width=Ue,ee&&Ge&&(ee.contains(k)?k.nextSibling!==Ge&&(k.remove(),ee.insertBefore(k,Ge)):ee.insertBefore(k,Ge)),ot){let je=parseFloat(Ue)||24,rt=ne(ot,je*.6,"currentColor",1);rt?k.replaceChildren(rt):k.textContent=ce.agentIconText??"\u{1F4AC}"}else if(ce.iconUrl){let je=k.querySelector("img");if(je)je.src=ce.iconUrl,je.style.height=Ue,je.style.width=Ue;else{let rt=document.createElement("img");rt.src=ce.iconUrl,rt.alt="",rt.className="persona-rounded-xl persona-object-cover",rt.style.height=Ue,rt.style.width=Ue,k.replaceChildren(rt)}}else{let je=k.querySelector("svg"),rt=k.querySelector("img");(je||rt)&&k.replaceChildren(),k.textContent=ce.agentIconText??"\u{1F4AC}"}let mt=k.querySelector("img");mt&&(mt.style.height=Ue,mt.style.width=Ue)}}let tt=o.layout?.header?.showTitle,Et=o.layout?.header?.showSubtitle;if(W&&(W.style.display=tt===!1?"none":""),V&&(V.style.display=Et===!1?"none":""),A){let ee=D()&&o.layout?.header?.showCloseButton!==!1;A.style.display=ee?"":"none";let Ge=ce.closeButtonSize??"32px",mt=ce.closeButtonPlacement??"inline";A.style.height=Ge,A.style.width=Ge;let{closeButtonWrapper:je}=Pe,rt=mt==="top-right",$t=je?.classList.contains("persona-absolute");if(je&&rt!==$t)if(je.remove(),rt)je.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(je);else{let $e=ce.clearChat?.placement??"inline",Dt=ce.clearChat?.enabled??!0;je.className=Dt&&$e==="inline"?"":"persona-ml-auto";let Jt=pe.querySelector(".persona-border-b-persona-divider");Jt&&Jt.appendChild(je)}if(A.style.color=ce.closeButtonColor||Kt.actionIconColor,ce.closeButtonBackgroundColor?(A.style.backgroundColor=ce.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),ce.closeButtonBorderWidth||ce.closeButtonBorderColor){let $e=ce.closeButtonBorderWidth||"0px",Dt=ce.closeButtonBorderColor||"transparent";A.style.border=`${$e} solid ${Dt}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");ce.closeButtonBorderRadius?(A.style.borderRadius=ce.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),ce.closeButtonPaddingX?(A.style.paddingLeft=ce.closeButtonPaddingX,A.style.paddingRight=ce.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),ce.closeButtonPaddingY?(A.style.paddingTop=ce.closeButtonPaddingY,A.style.paddingBottom=ce.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom="");let nn=ce.closeButtonIconName??"x",vn=ce.closeButtonIconText??"\xD7";A.innerHTML="";let Ot=ne(nn,"28px","currentColor",1);Ot?(Ot.style.display="block",A.appendChild(Ot)):A.textContent=vn;let Tt=ce.closeButtonTooltipText??"Close chat",on=ce.closeButtonShowTooltip??!0;if(A.setAttribute("aria-label",Tt),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),on&&Tt)){let $e=null,Dt=()=>{if($e||!A)return;let Mo=A.ownerDocument,zr=Mo.body;if(!zr)return;$e=Tn(Mo,"div","persona-clear-chat-tooltip"),$e.textContent=Tt;let Ur=Tn(Mo,"div");Ur.className="persona-clear-chat-tooltip-arrow",$e.appendChild(Ur);let Eo=A.getBoundingClientRect();$e.style.position="fixed",$e.style.zIndex=String(so),$e.style.left=`${Eo.left+Eo.width/2}px`,$e.style.top=`${Eo.top-8}px`,$e.style.transform="translate(-50%, -100%)",zr.appendChild($e)},Jt=()=>{$e&&$e.parentNode&&($e.parentNode.removeChild($e),$e=null)};je.addEventListener("mouseenter",Dt),je.addEventListener("mouseleave",Jt),A.addEventListener("focus",Dt),A.addEventListener("blur",Jt),je._cleanupTooltip=()=>{Jt(),je&&(je.removeEventListener("mouseenter",Dt),je.removeEventListener("mouseleave",Jt)),A&&(A.removeEventListener("focus",Dt),A.removeEventListener("blur",Jt))}}}let{clearChatButton:He,clearChatButtonWrapper:nt}=Pe;if(He){let ee=ce.clearChat??{},Ge=ee.enabled??!0,mt=o.layout?.header?.showClearChat,je=mt!==void 0?mt:Ge,rt=ee.placement??"inline";if(nt){nt.style.display=je?"":"none";let{closeButtonWrapper:$t}=Pe;!J()&&$t&&!$t.classList.contains("persona-absolute")&&(je?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let nn=rt==="top-right",vn=nt.classList.contains("persona-absolute");if(!J()&&nn!==vn&&je){if(nt.remove(),nn)nt.className="persona-absolute persona-top-4 persona-z-50",nt.style.right="48px",pe.style.position="relative",pe.appendChild(nt);else{nt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",nt.style.right="";let Tt=pe.querySelector(".persona-border-b-persona-divider"),on=Pe.closeButtonWrapper;Tt&&on&&on.parentElement===Tt?Tt.insertBefore(nt,on):Tt&&Tt.appendChild(nt)}let Ot=Pe.closeButtonWrapper;Ot&&!Ot.classList.contains("persona-absolute")&&(nn?Ot.classList.add("persona-ml-auto"):Ot.classList.remove("persona-ml-auto"))}}if(je){if(!J()){let $e=ee.size??"32px";He.style.height=$e,He.style.width=$e}let $t=ee.iconName??"refresh-cw",nn=ee.iconColor??"";He.style.color=nn||Kt.actionIconColor,He.innerHTML="";let vn=J()?"14px":"20px",Ot=ne($t,vn,"currentColor",1);if(Ot&&(Ot.style.display="block",He.appendChild(Ot)),ee.backgroundColor?(He.style.backgroundColor=ee.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let $e=ee.borderWidth||"0px",Dt=ee.borderColor||"transparent";He.style.border=`${$e} solid ${Dt}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");ee.borderRadius?(He.style.borderRadius=ee.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),ee.paddingX?(He.style.paddingLeft=ee.paddingX,He.style.paddingRight=ee.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),ee.paddingY?(He.style.paddingTop=ee.paddingY,He.style.paddingBottom=ee.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Tt=ee.tooltipText??"Clear chat",on=ee.showTooltip??!0;if(He.setAttribute("aria-label",Tt),nt&&(nt._cleanupTooltip&&(nt._cleanupTooltip(),delete nt._cleanupTooltip),on&&Tt)){let $e=null,Dt=()=>{if($e||!He)return;let Mo=He.ownerDocument,zr=Mo.body;if(!zr)return;$e=Tn(Mo,"div","persona-clear-chat-tooltip"),$e.textContent=Tt;let Ur=Tn(Mo,"div");Ur.className="persona-clear-chat-tooltip-arrow",$e.appendChild(Ur);let Eo=He.getBoundingClientRect();$e.style.position="fixed",$e.style.zIndex=String(so),$e.style.left=`${Eo.left+Eo.width/2}px`,$e.style.top=`${Eo.top-8}px`,$e.style.transform="translate(-50%, -100%)",zr.appendChild($e)},Jt=()=>{$e&&$e.parentNode&&($e.parentNode.removeChild($e),$e=null)};nt.addEventListener("mouseenter",Dt),nt.addEventListener("mouseleave",Jt),He.addEventListener("focus",Dt),He.addEventListener("blur",Jt),nt._cleanupTooltip=()=>{Jt(),nt&&(nt.removeEventListener("mouseenter",Dt),nt.removeEventListener("mouseleave",Jt)),He&&(He.removeEventListener("focus",Dt),He.removeEventListener("blur",Jt))}}}}let tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sl],Ao=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Cs.message,Cs.messageAndClick];E=Tl({parsers:tn,handlers:Ao,getSessionMetadata:v,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),Ce=bu(o,E,Le),_.updateConfig(o),Pr(be,_.getMessages(),Ce),ri(),uc(),mi(_.isStreaming());let zc=o.voiceRecognition?.enabled===!0,qs=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kt=o.voiceRecognition?.provider?.type==="runtype";if(zc&&(qs||kt))if(!K||!_e){let ee=mf(o.voiceRecognition,o.sendButton);ee&&(K=ee.micButton,_e=ee.micButtonWrapper,Ke.insertBefore(_e,fn),K.addEventListener("click",Us),K.disabled=_.isStreaming())}else{let ee=o.voiceRecognition??{},Ge=o.sendButton??{},mt=ee.iconName??"mic",je=Ge.size??"40px",rt=ee.iconSize??je,$t=parseFloat(rt)||24;K.style.width=rt,K.style.height=rt,K.style.minWidth=rt,K.style.minHeight=rt;let nn=ee.iconColor??Ge.textColor;K.innerHTML="";let vn=ne(mt,$t,nn||"currentColor",1.5);vn?K.appendChild(vn):K.textContent="\u{1F3A4}";let Ot=ee.backgroundColor??Ge.backgroundColor;Ot?K.style.backgroundColor=Ot:K.style.backgroundColor="",nn?K.style.color=nn:K.style.color="var(--persona-text, #111827)",ee.borderWidth?(K.style.borderWidth=ee.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),ee.borderColor?K.style.borderColor=ee.borderColor:K.style.borderColor="",ee.paddingX?(K.style.paddingLeft=ee.paddingX,K.style.paddingRight=ee.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),ee.paddingY?(K.style.paddingTop=ee.paddingY,K.style.paddingBottom=ee.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Tt=_e?.querySelector(".persona-send-button-tooltip"),on=ee.tooltipText??"Start voice recognition";if((ee.showTooltip??!1)&&on)if(Tt)Tt.textContent=on,Tt.style.display="";else{let Dt=document.createElement("div");Dt.className="persona-send-button-tooltip",Dt.textContent=on,_e?.insertBefore(Dt,K)}else Tt&&(Tt.style.display="none");_e.style.display="",K.disabled=_.isStreaming()}else K&&_e&&(_e.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Sn&&Xn());if(o.attachments?.enabled===!0){if(!Be||!ke){let ee=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Ze||(Ze=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ze.style.display="none",X.insertBefore(Ze,he)),Ie||(Ie=document.createElement("input"),Ie.type="file",Ie.accept=(ee.allowedTypes??Fn).join(","),Ie.multiple=(ee.maxFiles??4)>1,Ie.style.display="none",Ie.setAttribute("aria-label","Attach files"),X.insertBefore(Ie,he)),Be=m("div","persona-send-button-wrapper"),ke=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ke.type="button",ke.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let je=ee.buttonIconName??"paperclip",rt=mt,$t=parseFloat(rt)||40,nn=Math.round($t*.6);ke.style.width=rt,ke.style.height=rt,ke.style.minWidth=rt,ke.style.minHeight=rt,ke.style.fontSize="18px",ke.style.lineHeight="1";let vn=ne(je,nn,"currentColor",1.5);vn?ke.appendChild(vn):ke.textContent="\u{1F4CE}",ke.addEventListener("click",on=>{on.preventDefault(),Ie?.click()}),Be.appendChild(ke);let Ot=ee.buttonTooltipText??"Attach file",Tt=m("div","persona-send-button-tooltip");Tt.textContent=Ot,Be.appendChild(Tt),Ee?Ee.append(Be):X.appendChild(Be),!St&&Ie&&Ze&&(St=ts.fromConfig(ee),St.setPreviewsContainer(Ze),Ie.addEventListener("change",async()=>{St&&Ie?.files&&(await St.handleFileSelect(Ie.files),Ie.value="")}))}else{Be.style.display="";let ee=o.attachments??{};Ie&&(Ie.accept=(ee.allowedTypes??Fn).join(","),Ie.multiple=(ee.maxFiles??4)>1),St&&St.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}if(pe.querySelector(".persona-attachment-drop-overlay")?.remove(),pe.appendChild(vu(o.attachments?.dropOverlay)),ke){let ee=o.attachments??{},Ge=ee.buttonTooltipText??"Attach file";ke.setAttribute("aria-label",Ge),ke.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,je=ne(ee.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);je?ke.appendChild(je):ke.textContent="\u{1F4CE}";let rt=Be?.querySelector(".persona-send-button-tooltip");rt&&(rt.textContent=Ge)}}else Be&&(Be.style.display="none"),St&&St.clearAttachments(),pe.querySelector(".persona-attachment-drop-overlay")?.remove();let Ht=o.sendButton??{},Or=Ht.useIcon??!1,Ks=Ht.iconText??"\u2191",Qo=Ht.iconName,_r=Ht.tooltipText??"Send message",ki=Ht.showTooltip??!1,So=Ht.size??"40px",Wn=Ht.backgroundColor,To=Ht.textColor;if(Or){if(de.style.width=So,de.style.height=So,de.style.minWidth=So,de.style.minHeight=So,de.style.fontSize="18px",de.style.lineHeight="1",To?de.style.color=To:de.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(de.innerHTML="",Qo){let ee=parseFloat(So)||24,Ge=To?.trim()||"currentColor",mt=ne(Qo,ee,Ge,2);mt?de.appendChild(mt):de.textContent=Ks}else de.textContent=Ks;de.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(de.style.backgroundColor=Wn,de.classList.remove("persona-bg-persona-primary")):(de.style.backgroundColor="",de.classList.add("persona-bg-persona-primary"))}else de.textContent=o.copy?.sendButtonLabel??"Send",de.style.width="",de.style.height="",de.style.minWidth="",de.style.minHeight="",de.style.fontSize="",de.style.lineHeight="",de.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",Wn?(de.style.backgroundColor=Wn,de.classList.remove("persona-bg-persona-accent")):de.classList.add("persona-bg-persona-accent"),To?de.style.color=To:de.classList.add("persona-text-white");Ht.borderWidth?(de.style.borderWidth=Ht.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),Ht.borderColor?de.style.borderColor=Ht.borderColor:de.style.borderColor="",Ht.paddingX?(de.style.paddingLeft=Ht.paddingX,de.style.paddingRight=Ht.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Ht.paddingY?(de.style.paddingTop=Ht.paddingY,de.style.paddingBottom=Ht.paddingY):(de.style.paddingTop="",de.style.paddingBottom="");let $r=fn?.querySelector(".persona-send-button-tooltip");if(ki&&_r)if($r)$r.textContent=_r,$r.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=_r,fn?.insertBefore(ee,de)}else $r&&($r.style.display="none");let Gs=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Gs?(be.style.maxWidth=Gs,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",X&&(X.style.maxWidth=Gs,X.style.marginLeft="auto",X.style.marginRight="auto"),bt&&(bt.style.maxWidth=Gs,bt.style.marginLeft="auto",bt.style.marginRight="auto")):(be.style.maxWidth="",be.style.marginLeft="",be.style.marginRight="",be.style.width="",X&&(X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight=""),bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""));let Yn=o.statusIndicator??{},Cf=Yn.visible??!0;if(M.style.display=Cf?"":"none",_){let ee=_.getStatus();Mt(M,(mt=>mt==="idle"?Yn.idleText??It.idle:mt==="connecting"?Yn.connectingText??It.connecting:mt==="connected"?Yn.connectedText??It.connected:mt==="error"?Yn.errorText??It.error:It[mt])(ee),Yn,ee)}M.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Af=Yn.align==="left"?"persona-text-left":Yn.align==="center"?"persona-text-center":"persona-text-right";M.classList.add(Af)},open(){D()&&ft(!0,"api")},close(){D()&&ft(!1,"api")},toggle(){D()&&ft(!$,"api")},reconnect(){_.reconnectNow()},clearChat(){kn=!1,_.clearMessages(),yo.clear(),Gn();try{localStorage.removeItem(hr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==hr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),d?.clear&&pi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},E.syncFromMetadata(),Ae?.clear(),ze?.reset(),Ne?.update()},setMessage(i){return!he||_.isStreaming()?!1:(!$&&D()&&ft(!0,"system"),he.value=i,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming())return!1;let g=i?.trim()||he.value.trim();return g?(!$&&D()&&ft(!0,"system"),he.value="",he.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!$&&D()&&ft(!0,"system"),Xe.manuallyDeactivated=!1,bn(),_.toggleVoice().then(()=>{Xe.active=_.isVoiceActive(),Pn("user"),_.isVoiceActive()&&Ko()})),!0):Sn?!0:wc()?(!$&&D()&&ft(!0,"system"),Xe.manuallyDeactivated=!1,bn(),$s("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,bn(),Pn("user"),Rn()}),!0):!1:Sn?(Xe.manuallyDeactivated=!0,bn(),Xn("user"),!0):!1},injectMessage(i){return!$&&D()&&ft(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!$&&D()&&ft(!0,"system");let g=_.injectAssistantMessage(i);return fe&&(fe=!1,ye&&(clearTimeout(ye),ye=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(i){return!$&&D()&&ft(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!$&&D()&&ft(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!$&&D()&&ft(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!$&&D()&&ft(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!$&&D()&&ft(!0,"system"),_.injectTestEvent(i)},async connectStream(i,g){return _.connectStream(i,g)},__pushEventStreamEvent(i){Ae&&(ze?.processEvent(i.type,i.payload),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!Y||!Ae||Ya()},hideEventStream(){it&&wr()},isEventStreamVisible(){return it},showArtifacts(){Gt(o)&&(kn=!1,Oo=!0,Ln(),et?.setMobileOpen(!0))},hideArtifacts(){Gt(o)&&(kn=!0,Ln())},upsertArtifact(i){return Gt(o)?(ko(o.features?.artifacts,i.artifactType)==="panel"&&(kn=!1,Oo=!0),_.upsertArtifact(i)):null},selectArtifact(i){Gt(o)&&_.selectArtifact(i)},clearArtifacts(){Gt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return T&&!$&&!J()||!he?!1:(he.focus(),!0)},async resolveApproval(i,g,h){let S=_.getMessages().find(L=>L.variant==="approval"&&L.approval?.id===i);if(!S?.approval)throw new Error(`Approval not found: ${i}`);if(S.approval.toolType==="webmcp"){_.resolveWebMcpApproval(S.id,g);return}return _.resolveApproval(S.approval,g,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(i){C(i)},on(i,g){return l.on(i,g)},off(i,g){l.off(i,g)},isOpen(){return D()&&$},isVoiceActive(){return Xe.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:D()&&$,launcherEnabled:T,voiceActive:Xe.active,streaming:_.isStreaming()}},showCSATFeedback(i){!$&&D()&&ft(!0,"system");let g=be.querySelector(".persona-feedback-container");g&&g.remove();let h=mu({onSubmit:async(b,S)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(b,S),i?.onSubmit?.(b,S)},onDismiss:i?.onDismiss,...i});be.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!$&&D()&&ft(!0,"system");let g=be.querySelector(".persona-feedback-container");g&&g.remove();let h=hu({onSubmit:async(b,S)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(b,S),i?.onSubmit?.(b,S)},onDismiss:i?.onDismiss,...i});be.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,g){return _.submitCSATFeedback(i,g)},async submitNPSFeedback(i,g){return _.submitNPSFeedback(i,g)},destroy(){vi(),wo!=null&&(clearInterval(wo),wo=null),qe.forEach(i=>i()),We.remove(),Qe?.remove(),Ft?.destroy(),Ut?.remove(),ho&&A.removeEventListener("click",ho)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:Pt,getMessages:Pt.getMessages,getStatus:Pt.getStatus,getMetadata:Pt.getPersistentMetadata,updateMetadata:Pt.updatePersistentMetadata,clearHistory:()=>Pt.clearChat(),setVoiceActive:h=>h?Pt.startVoiceRecognition():Pt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,qe.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Pt.focusInput()};if(window.addEventListener("persona:focusInput",g),qe.push(()=>{window.removeEventListener("persona:focusInput",g)}),Y){let O=re=>{let le=re.detail;(!le?.instanceId||le.instanceId===i)&&Pt.showEventStream()},G=re=>{let le=re.detail;(!le?.instanceId||le.instanceId===i)&&Pt.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",G),qe.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",G)})}let h=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Pt.showArtifacts()},b=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Pt.hideArtifacts()},S=O=>{let G=O.detail;G?.instanceId&&G.instanceId!==i||G?.artifact&&Pt.upsertArtifact(G.artifact)},L=O=>{let G=O.detail;G?.instanceId&&G.instanceId!==i||typeof G?.id=="string"&&Pt.selectArtifact(G.id)},Q=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Pt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",Q),qe.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",Q)})}let dn=hy(o.persistState);if(dn&&D()){let i=yy(dn.storage),g=`${dn.keyPrefix}widget-open`,h=`${dn.keyPrefix}widget-voice`,b=`${dn.keyPrefix}widget-voice-mode`;if(i){let S=dn.persist?.openState&&i.getItem(g)==="true",L=dn.persist?.voiceState&&i.getItem(h)==="true",Q=dn.persist?.voiceState&&i.getItem(b)==="true";if(S&&setTimeout(()=>{Pt.open(),setTimeout(()=>{if(L||Q)Pt.startVoiceRecognition();else if(dn.persist?.focusInput){let O=t.querySelector("textarea");O&&O.focus()}},100)},0),dn.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(g,"true")}),l.on("widget:closed",()=>{i.setItem(g,"false")})),dn.persist?.voiceState&&(l.on("voice:state",O=>{i.setItem(h,O.active?"true":"false")}),l.on("user:message",O=>{i.setItem(b,O.viaVoice?"true":"false")})),dn.clearOnChatClear){let O=()=>{i.removeItem(g),i.removeItem(h),i.removeItem(b)},G=()=>O();window.addEventListener("persona:clear-chat",G),qe.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(w&&D()&&setTimeout(()=>{Pt.open()},0),jo(),!Ou){let i=Xs(()=>{_&&(si++,yo.clear(),Pr(be,_.getMessages(),Ce))});qe.push(i)}return Pt};var xu=(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},wy=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},xy=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Cy=(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.")},Cu=(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"},Il=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=""},Au=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Il(t)},kl=t=>{t.style.transition=""},Ll=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=""},Pl=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Qa=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},Ay=(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))},Sy=(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)},Ty=t=>{let e=ir(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Vt(e,r)??r;return{inset:o(n?.inset,ya),canvasBackground:o(n?.canvasBackground,ba)}},Su=(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},My=(t,e,n,o,r,s,a,l)=>{let p=un(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";Ay(t,e,n,o,d),Sy(t,e,n,o,p.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.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 f=t.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,P=f!=null?f.innerWidth<=C:!1;if(v&&P&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Ll(e),kl(o),Au(o),Pl(n),Qa(r,o),Su(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??zt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(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"),Au(o),wy(o,p.maxHeight),Su(o,c&&a,u,w),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Ll(e),kl(o),Pl(n),Qa(r,o);let E=p.animate?"transform 180ms ease":"none",T=p.side==="right"?"translateX(100%)":"translateX(-100%)",I=a?"translateX(0)":T;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=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=E,o.style.transform=I,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",kl(o),Il(o),Qa(r,o);let E=xu(p.width,t.clientWidth),T=Math.max(0,t.clientWidth),I=p.animate?"margin-left 180ms ease":"none",z=p.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=`${T+E}px`,e.style.transition=I,e.style.marginLeft=`${z}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${T}px`,n.style.maxWidth=`${T}px`,n.style.minWidth=`${T}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.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="",Ll(e),Il(o),Pl(n),Qa(r,o);let E=p.reveal==="emerge";E?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let T=a?p.width:"0px",I=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",z=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${T}`,o.style.width=T,o.style.maxWidth=T,o.style.minWidth=T,o.style.minHeight="0",xy(o,p.maxHeight),o.style.overflow=E||z?"hidden":"visible",o.style.transition=I,E){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let N=c?`calc(${xu(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=N,r.style.minWidth=N,r.style.maxWidth=N,r.style.boxSizing="border-box"}}},Ey=(t,e)=>{let n=t.ownerDocument.createElement("div");return Cu(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Cu(n,o)},destroy(){n.remove()}}},ky=(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"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,t),p.appendChild(t);let w=null,f=()=>{w?.disconnect(),w=null},v=null,C=()=>{v=e?.launcher?.detachedPanel===!0?Ty(e):null};C();let P=()=>{My(a,l,p,d,c,e,u,v)},H=null,E=()=>{H?.(),H=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(H=va(()=>{C(),P()}))},T=()=>{f(),un(e).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{P()}),w.observe(a)))},I=!1,z=()=>{P(),T(),u&&!I&&a.dataset.personaDockMobileFullscreen!=="true"&&(I=!0,Cy(a,un(e)))},N=a.ownerDocument.defaultView,x=()=>{z()};return N?.addEventListener("resize",x),un(e).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),z(),E(),{mode:"docked",host:c,shell:a,syncWidgetState(j){let q=j.launcherEnabled?j.open:!0;u!==q&&(u=q,z())},updateConfig(j){e=j,(e?.launcher?.enabled??!0)===!1&&(u=!0),C(),z(),E()},destroy(){N?.removeEventListener("resize",x),H?.(),H=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},Tu=(t,e)=>Nt(e)?ky(t,e):Ey(t,e);var As={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Mu=.15,Eu=1.5,Rl="persona-preview-shell-theme",Ly={load:()=>null,save:()=>{},clear:()=>{}},Py=["How do I get started?","Pricing & plans","Talk to support"];function Wl(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Iy(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 ku(t){let e=Iy(t);return`* { box-sizing: border-box; }
139
+ ${st?"background: transparent !important;":""}
140
+ `}if(!b&&!i){let Mt="max-height: -moz-available !important; max-height: stretch !important;",Xt=g?"":"padding-top: 1.25em !important;",$s=g?"":`z-index: ${o.launcher?.zIndex??$t} !important;`;Re.style.cssText+=Mt+Xt+$s}cn()};Es(),Yr(t,o),gs(t,o),ms(t,o),br=()=>{Es(),Yr(t,o),gs(t,o),ms(t,o),ws?t.style.setProperty("--persona-artifact-welded-outer-radius",ws):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let ze=[];ze.push(()=>{document.removeEventListener("keydown",Xl)}),ze.push(()=>{mr!==null&&clearTimeout(mr)});let xn=null,Cn=null;ze.push(()=>{xn?.(),xn=null,Cn?.(),Cn=null}),yr&&ze.push(()=>{yr?.disconnect(),yr=null}),ze.push(()=>{xr?.(),xr=null,ei(),vt&&(vt.remove(),vt=null),Je?.element.style.removeProperty("width"),Je?.element.style.removeProperty("maxWidth")}),Y&&ze.push(()=>{Ge!==null&&(cancelAnimationFrame(Ge),Ge=null),Fe?.destroy(),Fe=null,Ae?.destroy(),Ae=null,pe=null});let go=null,Zl=()=>{go&&(go(),go=null),o.colorScheme==="auto"&&(go=ha(()=>{Yr(t,o)}))};Zl(),ze.push(()=>{go&&(go(),go=null)}),ze.push(a);let ks=o.features?.streamAnimation;if(ks?.type&&ks.type!=="none"){let i=lr(ks.type,ks.plugins);i&&(Ia(i,t),ze.push(()=>Bp(t)))}let Ls=eu(bt),mo=null,_,ti=i=>{if(!_)return;let g=i??_.getMessages(),m=o.features?.suggestReplies?.enabled!==!1?Sd(g):null;m?Ls.render(m,_,ve,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(b=>b.role==="user")?Ls.render([],_,ve,g):Ls.render(o.suggestionChips,_,ve,g,o.suggestionChipsConfig)},mn=!1,ho=Mp(),No=new Map,yo=new Map,jn=new Map,ni=0,qu=Hn()!==null,Yt=Ta(),rn=0,qn=null,sn=!1,Ps=!1,Vn=0,hn=null,bo=null,oi=!1,Is=!1,ri=null,Cr=!0,si=!1,ai=null,Vu=4,Rs=24,Ku=80,ii=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ec=o.voiceRecognition?.autoResume??!1,kn=i=>{l.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},yn=()=>{C(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Gu=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=kl(c.voiceState),g=!!i.active,m=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-m<xy&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),kn("restore"),_.isVoiceActive()&&Uo()}):Ds("restore"))},1e3)},Qu=()=>_?Au(_.getMessages()).filter(i=>!i.__skipPersist):[],Ws=null,tc=(i,g)=>{typeof console<"u"&&console.error(i,g)},li=(i,g)=>{let m=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(N=>{tc(g,N)})}catch(Q){return tc(g,Q),null}},b=Ws,A=b?b.then(()=>m()??void 0):m();if(!A)return;let L=A.finally(()=>{Ws===L&&(Ws=null)});Ws=L};function ci(i){if(!d?.save)return;let m={messages:i?Au(i):_?Qu():[],metadata:c,artifacts:fn.artifacts,selectedArtifactId:fn.selectedId};li(()=>d.save(m),"[AgentWidget] Failed to persist state:")}let Oo=null,nc=()=>Re.querySelector("#persona-scroll-container")||le,Ar=()=>{Oo!==null&&(cancelAnimationFrame(Oo),Oo=null),sn=!1},oc=()=>{qn!==null&&(cancelAnimationFrame(qn),qn=null),Ps=!1,Ar()},Xu=()=>mn&&pi()&&(Gt()!=="anchor-top"||Fl()),di=()=>{let i=co()||"Jump to latest",g=Xu();Et.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Vn>0?(po.textContent=String(Vn),po.style.display="",Et.setAttribute("aria-label",`${i} (${Vn} new)`)):(po.textContent="",po.style.display="none",Et.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},rc=()=>{Vn!==0&&(Vn=0,di())},pi=()=>_n()?!Yt.isFollowing():!ao(le,Rs),Zt=()=>{if(!bs()||ot){Et.parentNode&&Et.remove(),Et.style.display="none";return}Et.parentNode!==ue&&ue.appendChild(Et),Ho();let g=Tn(le)>0&&pi();g?di():rc(),Et.style.display=g?"":"none"},Sr=()=>{Yt.pause()&&(oc(),Zt())},Kn=()=>{Yt.resume(),rc(),Zt()},Gn=(i=!1)=>{_n()&&Yt.isFollowing()&&(!i&&!mn||(qn!==null&&(cancelAnimationFrame(qn),qn=null),Ps=!0,qn=requestAnimationFrame(()=>{qn=null,Ps=!1,Yt.isFollowing()&&Ju(nc(),i?220:140)})))},sc=(i,g,m,b=()=>!0)=>{let A=i.scrollTop,L=g(),Q=L-A;if(Ar(),Math.abs(Q)<1){sn=!0,i.scrollTop=L,rn=i.scrollTop,sn=!1;return}let N=performance.now();sn=!0;let G=fe=>1-Math.pow(1-fe,3),oe=fe=>{if(!b()){Ar();return}let ne=g();ne!==L&&(L=ne,Q=L-A);let xe=fe-N,Ue=Math.min(xe/m,1),pt=G(Ue),tt=A+Q*pt;i.scrollTop=tt,rn=i.scrollTop,Ue<1?Oo=requestAnimationFrame(oe):(i.scrollTop=L,rn=i.scrollTop,Oo=null,sn=!1)};Oo=requestAnimationFrame(oe)},Ju=(i,g=500)=>{let m=Tn(i)-i.scrollTop;if(Math.abs(m)<1){rn=i.scrollTop;return}if(Math.abs(m)>=Ku){Ar(),sn=!0,i.scrollTop=Tn(i),rn=i.scrollTop,sn=!1;return}sc(i,()=>Tn(i),g,()=>Yt.isFollowing())},ac=()=>{let i=nc();sn=!0,i.scrollTop=Tn(i),rn=i.scrollTop,sn=!1,Zt()},ic=i=>{let g=0,m=i;for(;m&&m!==le;)g+=m.offsetTop,m=m.offsetParent;return g},lc=()=>{if(Nu()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let g=[...i].reverse().find(L=>L.role==="user");if(!g)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=le.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let A=Math.min(Math.max(0,ic(b)-Bl()),Tn(le));return sn=!0,le.scrollTop=A,rn=le.scrollTop,sn=!1,Gt()==="follow"&&!ao(le,Rs)&&Yt.pause(),Zt(),!0},cc=i=>{$n.style.height=`${Math.max(0,Math.round(i))}px`,hn&&(hn.spacerHeight=Math.max(0,i))},Tr=()=>{bo!==null&&(cancelAnimationFrame(bo),bo=null),Ar(),hn=null,$n.style.height="0px"},Yu=i=>{bo!==null&&cancelAnimationFrame(bo),bo=requestAnimationFrame(()=>{bo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=le.querySelector(`[data-message-id="${g}"]`);if(!m)return;let b=ic(m),A=hn?.spacerHeight??0,L=le.scrollHeight-A,{targetScrollTop:Q,spacerHeight:N}=Ip({anchorOffsetTop:b,topOffset:Bl(),viewportHeight:le.clientHeight,contentHeight:L});hn={initialSpacerHeight:N,contentHeightAtAnchor:L,spacerHeight:N},cc(N),sc(le,()=>Q,220)})},Zu=()=>{if(_n()){if(!Yt.isFollowing()||ao(le,1))return;Gn(!mn);return}if(hn&&hn.initialSpacerHeight>0){let i=le.scrollHeight-hn.spacerHeight,g=Rp({initialSpacerHeight:hn.initialSpacerHeight,contentHeightAtAnchor:hn.contentHeightAtAnchor,currentContentHeight:i});g!==hn.spacerHeight&&cc(g)}Zt()},ef=i=>{let g=Gt();g==="follow"?(Kn(),Gn(!0)):g==="anchor-top"&&(Cr=!1,si=!0,Yu(i))},tf=()=>{if(Gt()==="anchor-top"){if(si){Cr=!1;return}Cr=!0,Tr(),Kn(),Gn(!0)}},nf=i=>{let g=new Map;i.forEach(m=>{let b=ii.get(m.id);g.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(l.emit("assistant:message",m),!Is&&(Gt()!=="anchor-top"||Fl())&&pi()&&(Vn+=1,di(),Zt(),Ol(Vn===1?"1 new message below.":`${Vn} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&l.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&l.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):l.emit("approval:requested",{approval:m.approval,message:m}))}),ii.clear(),g.forEach((m,b)=>{ii.set(b,m)})},Hs=(i,g)=>{let m=g==="user"?"user":"assistant",b=o.layout?.messages?.[m],A=b?.width??"content",L=b?.maxWidth??(A==="full"?"100%":"85%");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-${g}`,`persona-message-width-${A}`),i.classList.toggle("persona-justify-end",g==="user"),i.setAttribute("data-message-role",g),i.setAttribute("data-message-width",A),i.style.setProperty("--persona-message-row-max-width",L)},vo=(i,g)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),Hs(m,g),m},of=(i,g,m)=>{let b=document.createElement("div"),L=(()=>{let R=r.find(We=>We.renderLoadingIndicator);if(R?.renderLoadingIndicator)return R.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(R,We)=>We==null?!1:typeof We=="string"?(R.textContent=We,!0):(R.appendChild(We),!0),N=new Set,G=new Map,oe=new Set,fe=r.some(R=>R.renderAskUserQuestion),ne=[],xe=[],Ue=o.enableComponentStreaming!==!1,pt=o.approval!==!1,tt=[];if(g.forEach(R=>{N.add(R.id),G.set(R.id,R.role);let We=fe&&To(R),He=pt&&R.variant==="approval"&&!!R.approval,_e=!We&&R.role==="assistant"&&!R.variant&&Ue&&El(R);!He&&jn.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),jn.delete(R.id)),!_e&&yo.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),yo.delete(R.id));let St=To(R)?`:${R.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${R.agentMetadata?.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=Tp(R,ni)+St,Ut=We||He||_e?null:Ep(ho,R.id,ut);if(Ut){b.appendChild(Ut.cloneNode(!0)),To(R)&&R.toolCall?.id&&R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(oe.add(R.toolCall.id),Zs(R,o,ke.composerOverlay));return}let ft=null,Qt=r.find(Ze=>!!(R.variant==="reasoning"&&Ze.renderReasoning||R.variant==="tool"&&Ze.renderToolCall||!R.variant&&Ze.renderMessage)),Pt=o.layout?.messages;if(To(R)&&R.agentMetadata?.askUserQuestionAnswered===!0){No.delete(R.id),i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ni(R)&&o.features?.suggestReplies?.enabled!==!1)return;if(To(R)&&o.features?.askUserQuestion?.enabled!==!1){let Ze=r.find(xt=>typeof xt.renderAskUserQuestion=="function");if(Ze&&lt.current){let xt=No.get(R.id),jt=xt!==ut,st=null;if(jt){let{payload:Ye,complete:De}=Qo(R),ht=R.id,Nt=()=>lt.current?.getMessages().find(cn=>cn.id===ht);st=Ze.renderAskUserQuestion({message:R,payload:Ye,complete:De,resolve:cn=>{let Br=Nt();Br&&lt.current?.resolveAskUserQuestion(Br,cn)},dismiss:()=>{let cn=Nt();cn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(cn),lt.current?.resolveAskUserQuestion(cn,"(dismissed)"))},config:o})}let ct=xt!=null;if(jt&&st===null&&!ct){R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(oe.add(R.toolCall.id),Zs(R,o,ke.composerOverlay));return}let gt=vo(R.id,R.role);gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),ne.push({messageId:R.id,fingerprint:ut,bubble:st});return}else{R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(oe.add(R.toolCall.id),Zs(R,o,ke.composerOverlay));return}}else if(He){let Ze=r.find(ct=>typeof ct.renderApproval=="function")??s,jt=jn.get(R.id)!==ut,st=null;if(jt&&Ze?.renderApproval){let ct=R.id,gt=(Ye,De)=>{let ht=lt.current?.getMessages().find(Nt=>Nt.id===ct);ht?.approval&&(ht.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(ht.id,Ye):lt.current?.resolveApproval(ht.approval,Ye,De))};st=Ze.renderApproval({message:R,defaultRenderer:()=>Ua(R,o),config:o,approve:Ye=>gt("approved",Ye),deny:Ye=>gt("denied",Ye)})}if(jt&&st===null)i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),jn.delete(R.id),ft=Ua(R,o);else{let ct=vo(R.id,R.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),b.appendChild(ct),tt.push({messageId:R.id,fingerprint:ut,bubble:st});return}}else if(Qt)if(R.variant==="reasoning"&&R.reasoning&&Qt.renderReasoning){if(!ee)return;ft=Qt.renderReasoning({message:R,defaultRenderer:()=>ul(R,o),config:o})}else if(R.variant==="tool"&&R.toolCall&&Qt.renderToolCall){if(!ce)return;ft=Qt.renderToolCall({message:R,defaultRenderer:()=>gl(R,o),config:o})}else Qt.renderMessage&&(ft=Qt.renderMessage({message:R,defaultRenderer:()=>{let Ze=pl(R,m,Pt,o.messageActions,Me,{loadingIndicatorRenderer:L,widgetConfig:o});return R.role!=="user"&&xl(Ze,R,o,_),Ze},config:o}));if(!ft&&_e){let Ze=wu(R);if(Ze){let xt=yo.get(R.id),jt=xt!==ut,st=o.wrapComponentDirectiveInBubble!==!1&&On.getOptions(Ze.component)?.bubbleChrome!==!1,ct=null;if(jt){let gt=bu(Ze,{config:o,message:R,transform:m});if(gt&&Ze.component==="PersonaArtifactInline"){let Ye=gt.hasAttribute("data-artifact-inline")?gt:gt.querySelector("[data-artifact-inline]"),De=Ye?.getAttribute("data-artifact-inline")??"",ht=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(De):De,Nt=De?i.querySelector(`#wrapper-${R.id}`)?.querySelector(`[data-artifact-inline="${ht}"]`)??null:null;Ye&&Nt&&Nt!==Ye&&wp(Nt)&&(Ye===gt?gt=Nt:Ye.replaceWith(Nt))}if(gt)if(st){let Ye=document.createElement("div");if(Ye.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ye.id=`bubble-${R.id}`,Ye.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let De=document.createElement("div");De.className="persona-mb-3 persona-text-sm persona-leading-relaxed",De.innerHTML=m({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ye.appendChild(De)}Ye.appendChild(gt),ct=Ye}else{let Ye=document.createElement("div");if(Ye.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ye.id=`bubble-${R.id}`,Ye.setAttribute("data-message-id",R.id),Ye.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let De=document.createElement("div");De.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",De.innerHTML=m({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ye.appendChild(De)}Ye.appendChild(gt),ct=Ye}}if(ct||xt!=null){let gt=vo(R.id,R.role);gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),xe.push({messageId:R.id,fingerprint:ut,bubble:ct});return}}}if(!ft)if(R.variant==="reasoning"&&R.reasoning){if(!ee)return;ft=ul(R,o)}else if(R.variant==="tool"&&R.toolCall){if(!ce)return;ft=gl(R,o)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;ft=Ua(R,o)}else{let Ze=o.layout?.messages;Ze?.renderUserMessage&&R.role==="user"?ft=Ze.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):Ze?.renderAssistantMessage&&R.role==="assistant"?ft=Ze.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):ft=pl(R,m,Ze,o.messageActions,Me,{loadingIndicatorRenderer:L,widgetConfig:o}),R.role!=="user"&&ft&&xl(ft,R,o,_)}let Be=vo(R.id,R.role);Be.appendChild(ft),kp(ho,R.id,ut,Be),b.appendChild(Be)}),ke.composerOverlay&&ke.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let He=We.getAttribute("data-persona-ask-sheet-for");He&&!oe.has(He)&&Jo(ke.composerOverlay,He)}),o.features?.toolCallDisplay?.grouped){let R=[],We=[];g.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&ce){We.push(He);return}He.variant==="reasoning"&&!ee||(We.length>1&&R.push(We),We=[])}),We.length>1&&R.push(We),R.forEach((He,_e)=>{let St=He.map(xt=>Array.from(b.children).find(jt=>jt instanceof HTMLElement&&jt.getAttribute("data-wrapper-id")===xt.id)).filter(xt=>!!xt);if(St.length<2)return;let ut=vo(`tool-group-${_e}-${He[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let Ut=document.createElement("div");Ut.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ut.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Qt=`Called ${He.length} tools`,Pt=o.toolCall?.renderGroupedSummary?.({messages:He,toolCalls:He.map(xt=>xt.toolCall).filter(xt=>!!xt),defaultSummary:Qt,config:o});Q(ft,Pt)||(ft.textContent=Qt);let Be=document.createElement("div");Be.className="persona-tool-group-stack persona-flex persona-flex-col";let Ze=o.features?.toolCallDisplay?.groupedMode==="summary";Ut.appendChild(ft),Ze||Ut.appendChild(Be),ut.appendChild(Ut),St[0].before(ut),St.forEach((xt,jt)=>{if(Ze){xt.remove();return}xt.style.setProperty("--persona-message-row-max-width","100%");let st=document.createElement("div");st.className="persona-tool-group-item persona-relative",st.setAttribute("data-persona-tool-group-item","true"),jt<St.length-1&&st.setAttribute("data-persona-tool-group-connector","true"),st.appendChild(xt),Be.appendChild(st)})})}Lp(ho,N);let en=g.some(R=>R.role==="assistant"&&R.streaming),At=g[g.length-1],Lt=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(mn&&g.some(R=>R.role==="user")&&!en&&!Lt){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:ds},We=r.find(_e=>_e.renderLoadingIndicator),He=null;if(We?.renderLoadingIndicator&&(He=We.renderLoadingIndicator(R)),He===null&&o.loadingIndicator?.render&&(He=o.loadingIndicator.render(R)),He===null&&(He=ds()),He){let _e=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1;_e.className=St?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_e.setAttribute("data-typing-indicator","true"),_e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",_e.appendChild(He);let ut=vo("typing-indicator","assistant");ut.appendChild(_e),b.appendChild(ut)}}if(!mn&&g.length>0){let R=g[g.length-1],We={config:o,lastMessage:R,messageCount:g.length},He=r.find(St=>St.renderIdleIndicator),_e=null;if(He?.renderIdleIndicator&&(_e=He.renderIdleIndicator(We)),_e===null&&o.loadingIndicator?.renderIdle&&(_e=o.loadingIndicator.renderIdle(We)),_e){let St=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;St.className=ut?["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(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(_e);let Ut=vo("idle-indicator","assistant");Ut.appendChild(St),b.appendChild(Ut)}}if(rd(b),Sa(i,b),ki(i),ne.length>0)for(let{messageId:R,fingerprint:We,bubble:He}of ne){let _e=i.querySelector(`#wrapper-${R}`);_e&&(Hs(_e,G.get(R)??"assistant"),He!==null&&(_e.replaceChildren(He),_e.setAttribute("data-bubble-fp",We),No.set(R,We)))}if(No.size>0)for(let R of No.keys())N.has(R)||No.delete(R);if(xe.length>0)for(let{messageId:R,fingerprint:We,bubble:He}of xe){let _e=i.querySelector(`#wrapper-${R}`);_e&&(Hs(_e,G.get(R)??"assistant"),He!==null&&(_e.replaceChildren(He),_e.setAttribute("data-bubble-fp",We),yo.set(R,We)))}if(yo.size>0)for(let R of yo.keys())N.has(R)||yo.delete(R);if(tt.length>0)for(let{messageId:R,fingerprint:We,bubble:He}of tt){let _e=i.querySelector(`#wrapper-${R}`);_e&&(Hs(_e,G.get(R)??"assistant"),He!==null&&(_e.replaceChildren(He),_e.setAttribute("data-bubble-fp",We),jn.set(R,We)))}if(jn.size>0)for(let R of jn.keys())N.has(R)||jn.delete(R)},Mr=(i,g,m)=>{of(i,g,m),Kl()},Er=null,rf=()=>{if(Er)return;let i=m=>{let b=m.composedPath();b.includes(Re)||Ve&&b.includes(Ve)||dt(!1,"user")};Er=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},dc=()=>{if(!Er)return;(t.ownerDocument??document).removeEventListener("pointerdown",Er,!0),Er=null};ze.push(()=>dc());let kr=null,sf=()=>{if(kr)return;let i=m=>{m.key==="Escape"&&(m.isComposing||dt(!1,"user"))};kr=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},pc=()=>{if(!kr)return;(t.ownerDocument??document).removeEventListener("keydown",kr,!0),kr=null};ze.push(()=>pc());let Lr=!1,uc=new Set,af=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},_o=()=>{if(!J())return;let i=ke.peekBanner,g=ke.peekTextNode;if(!i||!g)return;if(F){i.classList.remove("persona-pill-peek--visible");return}let m=_?.getMessages()??[],b;for(let At=m.length-1;At>=0;At--){let Lt=m[At];if(Lt.role==="assistant"&&Lt.content){b=Lt;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let A=b.content,L=!!b.streaming,Q=af(),N=ka(Q),G=N.type!=="none"?lr(N.type,Q?.plugins):null,oe=G?.isAnimating?.(b)===!0,fe=G!==null&&(L||oe);fe&&G&&!uc.has(G.name)&&(Ia(G,t),uc.add(G.name));let ne=fe&&G?.containerClass?G.containerClass:null,xe=g.dataset.personaPeekStreamClass??null;xe&&xe!==ne&&(g.classList.remove(xe),delete g.dataset.personaPeekStreamClass),ne&&xe!==ne&&(g.classList.add(ne),g.dataset.personaPeekStreamClass=ne),fe?(g.style.setProperty("--persona-stream-step",`${N.speed}ms`),g.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ue=fe?La(A,N.buffer,G,b,L):A;if(fe&&N.placeholder==="skeleton"&&L&&(!Ue||!Ue.trim())){let At=document.createElement("div"),Lt=ss();Lt.classList.add("persona-pill-peek__skeleton"),At.appendChild(Lt),Sa(g,At)}else{let At=Math.max(0,Ue.length-100),Lt=Ue.length>100?Ue.slice(-100):Ue,R=Zn(Lt);if(!fe||!G){let We=Ue.length>100?`\u2026${Lt}`:Lt;g.textContent!==We&&(g.textContent=We)}else{let We=R;(G.wrap==="char"||G.wrap==="word")&&(We=rs(R,G.wrap,`peek-${b.id}`,{skipTags:G.skipTags,startIndex:At}));let He=document.createElement("div");if(He.innerHTML=We,G.useCaret&&Lt.length>0){let _e=Pa(),St=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=St[St.length-1];ut?.parentNode?ut.parentNode.insertBefore(_e,ut.nextSibling):He.appendChild(_e)}Sa(g,He),G.onAfterRender?.({container:g,bubble:i,messageId:b.id,message:b,speed:N.speed,duration:N.duration})}}let en=mn||Lr;i.classList.toggle("persona-pill-peek--visible",en)};if(J()){let i=ke.peekBanner;if(i){let b=A=>{A.preventDefault(),A.stopPropagation(),dt(!0,"user")};i.addEventListener("pointerdown",b),ze.push(()=>{i.removeEventListener("pointerdown",b)})}let g=()=>{Lr||(Lr=!0,_o())},m=()=>{Lr&&(Lr=!1,_o())};me.addEventListener("pointerenter",g),me.addEventListener("pointerleave",m),ze.push(()=>{me.removeEventListener("pointerenter",g),me.removeEventListener("pointerleave",m)}),Ve&&(Ve.addEventListener("pointerenter",g),Ve.addEventListener("pointerleave",m),ze.push(()=>{Ve.removeEventListener("pointerenter",g),Ve.removeEventListener("pointerleave",m)}))}let lf=i=>{let g=o.launcher?.composerBar??{},m=g.expandedSize??"anchored",b=g.bottomOffset??"16px",A=g.collapsedMaxWidth,L=g.expandedMaxWidth??"880px",Q=g.expandedTopOffset??"5vh",N=g.modalMaxWidth??"880px",G=g.modalMaxHeight??"min(90vh, 800px)",oe="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",ne=Re.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",Ve){let xe=Ve.style;xe.bottom=b,xe.width=A??""}if(i&&m!=="fullscreen"){if(m==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=N,ne.maxWidth=oe,ne.maxHeight=G,ne.height=G;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${b} + ${fe})`,ne.top=Q,ne.width=L,ne.maxWidth=oe}},Pr=()=>{if(!D())return;if(J()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=F?"expanded":"collapsed";Re.dataset.state=fe,Re.dataset.expandedSize=oe,Ve&&(Ve.dataset.state=fe,Ve.dataset.expandedSize=oe),Re.style.removeProperty("display"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),lf(F),ue.style.display=F?"flex":"none",Es(),F?(rf(),sf()):(dc(),pc()),_o();return}let i=Ht(o),g=t.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,A=g.innerWidth<=m,L=b&&A&&M,Q=pn(o).reveal;F?(Re.style.removeProperty("display"),Re.style.display=i?"flex":"",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0"),me.classList.add("persona-scale-100","persona-opacity-100"),Bt?Bt.element.style.display="none":zt&&(zt.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!L?(Re.style.removeProperty("display"),Re.style.display="flex",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.setProperty("display","none","important"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.display="",Re.classList.add("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100"),me.classList.add("persona-scale-95","persona-opacity-0")),Bt?Bt.element.style.display=i?"none":"":zt&&(zt.style.display=i?"none":""))},dt=(i,g="user")=>{if(!D()||F===i)return;let m=F;F=i,Pr();let b=(()=>{let L=o.launcher?.sidebarMode??!1,Q=t.ownerDocument.defaultView??window,N=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,oe=Q.innerWidth<=G,fe=Ht(o)&&N&&oe,ne=J()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return L||N&&oe&&M||fe||ne})();if(F&&b){if(!xn){let L=t.getRootNode(),Q=L instanceof ShadowRoot?L.host:t.closest(".persona-host");Q&&(xn=sl(Q,o.launcher?.zIndex??$t))}Cn||(Cn=al(t.ownerDocument))}else F||(xn?.(),xn=null,Cn?.(),Cn=null);F&&(Wr(),lc()||(Gt()==="follow"?Gn(!0):ac()));let A={open:F,source:g,timestamp:Date.now()};F&&!m?l.emit("widget:opened",A):!F&&m&&l.emit("widget:closed",A),l.emit("widget:state",{open:F,launcherEnabled:M,voiceActive:Ke.active,streaming:_.isStreaming()})},ui=i=>{rt(i?"stop":"send"),V&&(V.disabled=i),Ls.buttons.forEach(g=>{g.disabled=i}),$.dataset.personaComposerStreaming=i?"true":"false",$.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=i)})},fi=()=>{Ke.active||ve&&ve.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>fi(),200)});let fc=()=>{O.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",y.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",ve.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=le.querySelector("[data-persona-intro-card]");if(i){let m=o.copy?.showWelcomeCard!==!1;i.style.display=m?"":"none",m?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(de.textContent=o.copy?.sendButtonLabel??"Send"),ve.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ve.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=c.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{C(g=>({...g,sessionId:i}))}});let wo=null,cf=()=>{wo==null&&(wo=setInterval(()=>{let i=be.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(wo),wo=null;return}let g=Date.now();i.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=na(g-b))})},100))},gi=(i,g)=>{if(Object.is(i,g))return!0;if(i===null||g===null||typeof i!="object"||typeof g!="object")return!1;if(Array.isArray(i)||Array.isArray(g))return!Array.isArray(i)||!Array.isArray(g)||i.length!==g.length?!1:i.every((Q,N)=>gi(Q,g[N]));let m=i,b=g,A=Object.keys(m),L=Object.keys(b);return A.length===L.length&&A.every(Q=>Object.prototype.hasOwnProperty.call(b,Q)&&gi(m[Q],b[Q]))},gc=i=>{let{content:g,rawContent:m,llmContent:b,...A}=i;return A},mi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!El(i),df=(i,g,m)=>{if(i.length!==g.length)return!1;let b=i[m.index],A=g[m.index];return!b||!A||b.id!==m.id||A.id!==m.id?!1:(!Object.is(b.content,A.content)||!Object.is(b.rawContent,A.rawContent)||!Object.is(b.llmContent,A.llmContent))&&mi(b)&&mi(A)&&gi(gc(b),gc(A))},mc=null,$o=null,xo=null,Ln=null,Bs=i=>{mc=i;let g,m;$o=null;for(let A=i.length-1;A>=0;A-=1){let L=i[A];if(!g&&L.role==="user"&&(g=L),!m&&L.role==="assistant"&&(m=L),!$o&&mi(L)&&($o={index:A,id:L.id}),g&&m&&$o)break}Mr(be,i,we),Zi(be,fn.artifacts,{suppressTransition:mn}),cf(),ti(i),Gn(!mn),nf(i),i.length===0&&(Tr(),Cr=!0,si=!1),!oi||Is?(oi=!0,ri=g?.id??null,ai=m?.id??null):g&&g.id!==ri?(ri=g.id,ef(g.id)):m&&m.id!==ai&&tf(),m&&(ai=m.id);let b=Ke.lastUserMessageId;g&&g.id!==b&&(Ke.lastUserMessageId=g.id,l.emit("user:message",g)),Ke.lastUserMessageWasVoice=!!g?.viaVoice,ci(i),_o()},hi=()=>{Ln!==null&&(cancelAnimationFrame(Ln),Ln=null);let i=xo;xo=null,i&&Bs(i)},hc=()=>{Ln!==null&&cancelAnimationFrame(Ln),Ln=null,xo=null},pf=i=>{let g=xo??mc;if(mn&&g&&$o&&df(g,i,$o)){xo=i,Ln===null&&(Ln=requestAnimationFrame(()=>{Ln=null;let m=xo;xo=null,m&&Bs(m)}));return}if(i.length===0){hc(),Bs(i);return}hi(),Bs(i)};_=new da(o,{onMessagesChanged(i){pf(i)},onStatusChanged(i){let g=o.statusIndicator??{};Tt(T,(b=>b==="idle"?g.idleText??It.idle:b==="connecting"?g.connectingText??It.connecting:b==="connected"?g.connectedText??It.connected:b==="error"?g.errorText??It.error:b==="paused"?g.pausedText??It.paused:b==="resuming"?g.resumingText??It.resuming:It[b])(i),g,i)},onStreamingChanged(i){i||(_?.getMessages().length===0?hc():hi()),mn=i,ui(i),_&&Mr(be,_.getMessages(),we),i||Gn(!0),Zt(),Ol(i?"Responding\u2026":"Response complete."),_o()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Pn(),Uo();break;case"processing":Pn(),Cf();break;case"speaking":Pn(),Af();break;default:i==="idle"&&_.isBargeInActive()?(Pn(),Uo(),V?.setAttribute("aria-label","End voice session")):(Ke.active=!1,Pn(),kn("system"),yn());break}},onArtifactsState(i){fn=i,i.artifacts.length===0&&(Bo=!1),Zi(be,i.artifacts,{suppressTransition:mn}),En(),ci()},onReconnect(i){let{executionId:g,lastEventId:m}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:g,after:m}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:g,after:m,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:g,after:m})}}),lt.current=_,ze.push(()=>_.cancel());let yi=null;if(_.onReadAloudChange((i,g)=>{ql=i,Vl=g,Kl();let m=i??yi;i&&(yi=i);let b=m?_.getMessages().find(A=>A.id===m)??null:null;l.emit("message:read-aloud",{messageId:m,message:b,state:g,timestamp:Date.now()}),g==="idle"&&(yi=null)}),oi=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&_.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ae||o.onSSEEvent)&&_.setSSEEventCallback((i,g)=>{o.onSSEEvent?.(i,g),Oe?.processEvent(i,g),Ae?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(g)})});let yc=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=kl(i.metadata),k.syncFromMetadata()),i.messages?.length){Is=!0;try{_.hydrateMessages(i.messages)}finally{Is=!1}}i.artifacts?.length&&_.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>yc()):yc();let bc=()=>{!J()||F||!(o.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},uf=(i,g)=>i?g?{refs:[...i.refs,...g.refs],finalize:async()=>{let[m,b]=await Promise.allSettled([i.finalize(),g.finalize()]),A=[];return m.status==="fulfilled"?A.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),b.status==="fulfilled"?A.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),ky(A)}}:i:g,ff=()=>{let g=ve.getInlineMessageFields?.();return g&&g.contentSegments.some(b=>b.kind==="mention")?g.contentSegments:void 0},Ir=!1,gf=async i=>{let g=ve.value.trim(),m=Ct?.hasAttachments()??!1,b=g?await(Jt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(b?.kind==="action"){ve.value="",ve.style.height="auto",Rr(),Jt?.clear();return}let A=Jt?.collectForSubmit()??null,L=b?.kind==="server"?b.mentions:null,Q=uf(A,L),N=b?.kind==="prompt"?b.sendText:g,G=!!A&&A.refs.length>0;if(!N&&!m&&!G&&!L)return;bc();let oe;m&&(oe=[],oe.push(...Ct.getContentParts()),N&&oe.push(Zo(N)));let fe=b?.kind==="prompt"?void 0:ff();ve.value="",ve.style.height="auto",Rr(),_.sendMessage(N,{contentParts:oe,mentions:Q??void 0,contentSegments:fe,viaVoice:i?.viaVoice}),m&&Ct.clearAttachments(),A&&Jt?.clear()},bi=async i=>{if(!Ir){Ir=!0;try{await gf(i)}finally{Ir=!1}}},vc=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),Oe?.reset(),Fe?.update();return}Ir||bi()},mf=()=>o.features?.composerHistory!==!1,vi={...nl},wi=!1,Rr=()=>{vi={...nl}},hf=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),yf=i=>{if(!ve)return;wi=!0,ve.value=i,ve.dispatchEvent(new Event("input",{bubbles:!0})),wi=!1;let g=ve.value.length;ve.setSelectionRange(g,g)},bf=i=>{wi||(i.isComposing||Jt?.handleInput(i.inputType??void 0),Rr())},vf=i=>{if(ve&&!(!i.isComposing&&Jt?.handleKeydown(i))){if(mf()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let g=ve.selectionStart===0&&ve.selectionEnd===0,m=Sp({direction:i.key==="ArrowUp"?"up":"down",history:hf(),currentValue:ve.value,atStart:g,state:vi});if(vi=m.state,m.handled){i.preventDefault(),m.value!==void 0&&yf(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(_.isStreaming()){i.preventDefault();return}if(Ir){i.preventDefault();return}Rr(),i.preventDefault(),de.click()}}},wc=i=>{i.key!=="Escape"||i.isComposing||_.isStreaming()&&i.composedPath().includes(ue)&&(_.cancel(),Oe?.reset(),Fe?.update(),Rr(),i.preventDefault(),i.stopImmediatePropagation())},wf=async i=>{if(o.attachments?.enabled!==!0||!Ct)return;let g=Sy(i.clipboardData);g.length!==0&&(i.preventDefault(),await Ct.handleFiles(g))},an=null,An=!1,zo=null,wt=null,xc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ds=(i="user")=>{if(An||_.isStreaming())return;let g=xc();if(!g)return;an=new g;let b=(o.voiceRecognition??{}).pauseDuration??2e3;an.continuous=!0,an.interimResults=!0,an.lang="en-US";let A=ve.value;an.onresult=L=>{let Q="",N="";for(let oe=0;oe<L.results.length;oe++){let fe=L.results[oe],ne=fe[0].transcript;fe.isFinal?Q+=ne+" ":N=ne}let G=A+Q+N;ve.value=G,zo&&clearTimeout(zo),(Q||N)&&(zo=window.setTimeout(()=>{ve.value.trim()&&an&&An&&(Qn(),bi({viaVoice:!0}))},b))},an.onerror=L=>{L.error!=="no-speech"&&Qn()},an.onend=()=>{if(An){let L=ve.value.trim();L&&L!==A.trim()&&bi({viaVoice:!0}),Qn()}};try{if(an.start(),An=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),kn(i),yn(),V){let L=o.voiceRecognition??{};wt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:L.iconName??"mic",iconSize:parseFloat(L.iconSize??o.sendButton?.size??"40")||24};let Q=L.recordingBackgroundColor,N=L.recordingIconColor,G=L.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=N??"var(--persona-voice-recording-indicator, #ffffff)",N){let oe=V.querySelector("svg");oe&&oe.setAttribute("stroke",N)}G&&(V.style.borderColor=G),V.setAttribute("aria-label","Stop voice recognition")}}catch{Qn("system")}},Qn=(i="user")=>{if(An){if(An=!1,zo&&(clearTimeout(zo),zo=null),an){try{an.stop()}catch{}an=null}if(Ke.active=!1,kn(i),yn(),V){if(V.classList.remove("persona-voice-recording"),wt){V.style.backgroundColor=wt.backgroundColor,V.style.color=wt.color,V.style.borderColor=wt.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",wt.color||"currentColor"),wt=null}V.setAttribute("aria-label","Start voice recognition")}}},xf=(i,g)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),b=i?.provider?.type==="runtype",A=i?.provider?.type==="custom";if(!(m||b||A))return null;let Q=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button";let G=i?.tooltipText??"Start voice recognition";N.setAttribute("aria-label",G);let oe=i?.iconName??"mic",fe=g?.size??"40px",ne=i?.iconSize??fe,xe=parseFloat(ne)||24,Ue=i?.backgroundColor??g?.backgroundColor,pt=i?.iconColor??g?.textColor;N.style.width=ne,N.style.height=ne,N.style.minWidth=ne,N.style.minHeight=ne,N.style.fontSize="18px",N.style.lineHeight="1",pt?N.style.color=pt:N.style.color="var(--persona-text, #111827)";let en=re(oe,xe,pt||"currentColor",1.5);en?N.appendChild(en):N.textContent="\u{1F3A4}",Ue?N.style.backgroundColor=Ue:N.style.backgroundColor="",i?.borderWidth&&(N.style.borderWidth=i.borderWidth,N.style.borderStyle="solid"),i?.borderColor&&(N.style.borderColor=i.borderColor),i?.paddingX&&(N.style.paddingLeft=i.paddingX,N.style.paddingRight=i.paddingX),i?.paddingY&&(N.style.paddingTop=i.paddingY,N.style.paddingBottom=i.paddingY),Q.appendChild(N);let At=i?.showTooltip??!1;return Ft({anchor:N,trigger:Q,text:()=>N.getAttribute("aria-label")??G,enabled:At}),{micButton:N,micButtonWrapper:Q}},xi=()=>{if(!V||wt)return;let i=o.voiceRecognition??{};wt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Ci=(i,g)=>{if(!V)return;let m=V.querySelector("svg");m&&m.remove();let b=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=re(i,b,g,1.5);A&&V.appendChild(A)},Fs=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Uo=()=>{if(!V)return;xi();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,m=i.recordingIconColor,b=i.recordingBorderColor;if(Fs(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let A=V.querySelector("svg");A&&A.setAttribute("stroke",m)}b&&(V.style.borderColor=b),V.setAttribute("aria-label","Stop voice recognition")},Cf=()=>{if(!V)return;xi();let i=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),m=i.processingIconName??"loader",b=i.processingIconColor??wt?.color??"",A=i.processingBackgroundColor??wt?.backgroundColor??"",L=i.processingBorderColor??wt?.borderColor??"";Fs(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=A,V.style.borderColor=L;let Q=b||"currentColor";V.style.color=Q,Ci(m,Q),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},Af=()=>{if(!V)return;xi();let i=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),m=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=i.speakingIconName??m,A=i.speakingIconColor??(g==="barge-in"?i.recordingIconColor??wt?.color??"":wt?.color??""),L=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),Q=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":wt?.borderColor??"");Fs(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=L,V.style.borderColor=Q;let N=A||"currentColor";V.style.color=N,Ci(b,N);let G=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",G),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},Pn=()=>{V&&(Fs(),wt&&(V.style.backgroundColor=wt.backgroundColor??"",V.style.color=wt.color??"",V.style.borderColor=wt.borderColor??"",Ci(wt.iconName,wt.color||"currentColor"),wt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},Ns=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=_.getVoiceStatus(),g=_.getVoiceInterruptionMode();if(g==="none"&&(i==="processing"||i==="speaking"))return;if(g==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,yn(),kn("user"),Pn()});return}_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),Ke.manuallyDeactivated=!_.isVoiceActive(),yn(),kn("user"),_.isVoiceActive()?Uo():Pn()});return}if(An){let i=ve.value.trim();Ke.manuallyDeactivated=!0,yn(),Qn("user"),i&&(ve.value="",ve.style.height="auto",_.sendMessage(i))}else Ke.manuallyDeactivated=!1,yn(),Ds("user")};$l=Ns,V&&(V.addEventListener("click",Ns),ze.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Pn()):Qn("system"),V&&V.removeEventListener("click",Ns)}));let Sf=l.on("assistant:complete",()=>{ec&&(Ke.active||Ke.manuallyDeactivated||ec==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),kn("auto"),_.isVoiceActive()&&Uo()}):Ds("auto"))},600))});ze.push(Sf);let Tf=l.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});ze.push(Tf);let Cc=()=>{dt(!F,"user")},Bt=null,zt=null;if(M&&!J()){let{instance:i,element:g}=ll({config:o,plugins:r,onToggle:Cc});Bt=i,i||(zt=g)}Bt?t.appendChild(Bt.element):zt&&t.appendChild(zt),Pr(),ti(),fc(),ui(_.isStreaming()),lc()||(Gt()==="follow"?Gn(!0):ac()),Gu(),z&&(!M||J()?setTimeout(()=>fi(),0):F&&setTimeout(()=>fi(),200));let Wr=()=>{if(J()){Ho(),Pr();return}let i=Ht(o),g=o.launcher?.sidebarMode??!1,m=i||g||(o.launcher?.fullHeight??!1),b=t.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640,Q=b.innerWidth<=L,N=A&&Q&&M;try{if(N){br(),vr=Ms();return}let G=!1;j&&(j=!1,br(),G=!0);let oe=Ms();if(!G&&oe!==vr&&(br(),G=!0),vr=oe,G&&Za(),!M&&!i){me.style.height="",me.style.width="";return}if(!g&&!i){let ne=o?.launcher?.width??o?.launcherWidth??Nn;me.style.width=ne,me.style.maxWidth=ne}if(Ts(),!m){let fe=b.innerHeight,ne=64,xe=o.launcher?.heightOffset??0,Ue=Math.max(200,fe-ne),pt=Math.min(640,Ue),tt=Math.max(200,pt-xe);me.style.height=`${tt}px`}}finally{if(Ho(),Pr(),F&&M){let oe=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),fe=o.launcher?.sidebarMode??!1,ne=o.launcher?.mobileFullscreen??!0,xe=Ht(o)&&ne&&oe,Ue=fe||ne&&oe&&M||xe;if(Ue&&!Cn){let pt=t.getRootNode(),tt=pt instanceof ShadowRoot?pt.host:t.closest(".persona-host");tt&&!xn&&(xn=sl(tt,o.launcher?.zIndex??$t)),Cn=al(t.ownerDocument)}else Ue||(xn?.(),xn=null,Cn?.(),Cn=null)}}};Wr();let Ac=t.ownerDocument.defaultView??window;if(Ac.addEventListener("resize",Wr),ze.push(()=>Ac.removeEventListener("resize",Wr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Ho()});i.observe($),ze.push(()=>i.disconnect())}rn=le.scrollTop;let Sc=Tn(le),Mf=()=>{let i=le.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??le.ownerDocument.getSelection()},Ai=()=>Pp(Mf(),le),Tc=()=>{let i=le.scrollTop,g=Tn(le),m=g<Sc;if(Sc=g,!_n()){rn=i,Zt();return}let{action:b,nextLastScrollTop:A}=Ma({following:Yt.isFollowing(),currentScrollTop:i,lastScrollTop:rn,nearBottom:ao(le,Rs),userScrollThreshold:Vu,isAutoScrolling:sn||Ps||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rn=A,b==="resume"){Ai()||Kn();return}b==="pause"&&Sr()};if(le.addEventListener("scroll",Tc,{passive:!0}),ze.push(()=>le.removeEventListener("scroll",Tc)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Zu(),ki(be)});i.observe(be),i.observe(le),ze.push(()=>i.disconnect())}let Mc=()=>{_n()&&Yt.isFollowing()&&Ai()&&Sr()},Ec=le.ownerDocument;Ec.addEventListener("selectionchange",Mc),ze.push(()=>{Ec.removeEventListener("selectionchange",Mc)});let Ef=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),kc=i=>{Dl()&&_n()&&Yt.isFollowing()&&Ef.has(i.key)&&Sr()},Lc=i=>{if(!Dl()||!_n()||!Yt.isFollowing())return;let g=i.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&Sr()};le.addEventListener("keydown",kc),le.addEventListener("focusin",Lc),ze.push(()=>{le.removeEventListener("keydown",kc),le.removeEventListener("focusin",Lc)});let Pc=i=>{if(!_n())return;let g=Ea({following:Yt.isFollowing(),deltaY:i.deltaY,nearBottom:ao(le,Rs),resumeWhenNearBottom:!0});g==="pause"?Sr():g==="resume"&&!Ai()&&Kn()};le.addEventListener("wheel",Pc,{passive:!0}),ze.push(()=>le.removeEventListener("wheel",Pc)),Et.addEventListener("click",()=>{Tr(),le.scrollTop=le.scrollHeight,rn=le.scrollTop,Kn(),Gn(!0),Zt()}),ze.push(()=>Et.remove()),ze.push(()=>{oc(),Tr()});let Ic=()=>{S&&(mo&&(S.removeEventListener("click",mo),mo=null),D()?(S.style.display="",mo=()=>{dt(!1,"user")},S.addEventListener("click",mo)):S.style.display="none")};Ic(),(()=>{let{clearChatButton:i}=ke;i&&i.addEventListener("click",()=>{_.clearMessages(),ho.clear(),Kn(),Jo(ke.composerOverlay);try{localStorage.removeItem(ur),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ur}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ur)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&li(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},k.syncFromMetadata(),Ae?.clear(),Oe?.reset(),Fe?.update()})})(),X&&X.addEventListener("submit",vc);let Rc=[["keydown",vf],["input",bf],["paste",wf],["focus",$u]],Wc=i=>{if(i)for(let[g,m]of Rc)i.addEventListener(g,m)},Hc=i=>{if(i)for(let[g,m]of Rc)i.removeEventListener(g,m)};Wc(ve),Jt?.onComposerSwap((i,g)=>{Hc(g),ve=i,Wc(i)});let Bc=t.ownerDocument??document;Bc.addEventListener("keydown",wc,!0);let Dc="persona-attachment-drop-active",Hr=0,Si=()=>{Hr=0,ue.classList.remove(Dc)},jo=()=>o.attachments?.enabled===!0&&Ct!==null,Fc=i=>{!qa(i.dataTransfer)||!jo()||(Hr++,Hr===1&&ue.classList.add(Dc))},Nc=i=>{!qa(i.dataTransfer)||!jo()||(Hr--,Hr<=0&&Si())},Oc=i=>{!qa(i.dataTransfer)||!jo()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},_c=i=>{if(!qa(i.dataTransfer)||!jo())return;i.preventDefault(),i.stopPropagation(),Si();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&Ct.handleFiles(g)},Xn=!0;ue.addEventListener("dragenter",Fc,Xn),ue.addEventListener("dragleave",Nc,Xn),t.addEventListener("dragover",Oc,Xn),t.addEventListener("drop",_c,Xn);let Os=t.ownerDocument,$c=i=>{jo()&&i.preventDefault()},zc=i=>{jo()&&i.preventDefault()};Os.addEventListener("dragover",$c),Os.addEventListener("drop",zc),ze.push(()=>{X&&X.removeEventListener("submit",vc),Hc(ve),Bc.removeEventListener("keydown",wc,!0),Jt?.destroy()}),ze.push(()=>{ue.removeEventListener("dragenter",Fc,Xn),ue.removeEventListener("dragleave",Nc,Xn),t.removeEventListener("dragover",Oc,Xn),t.removeEventListener("drop",_c,Xn),Os.removeEventListener("dragover",$c),Os.removeEventListener("drop",zc),Si()}),ze.push(()=>{_.cancel()}),Bt?ze.push(()=>{Bt?.destroy()}):zt&&ze.push(()=>{zt?.remove()});let kt={update(i){let g=o.toolCall,m=o.messageActions,b=o.layout?.messages,A=o.colorScheme,L=o.loadingIndicator,Q=o.iterationDisplay,N=o.features?.showReasoning,G=o.features?.showToolCalls,oe=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,ne=o.features?.streamAnimation?.type;o=gu(o,i),Es(),Yr(t,o),gs(t,o),ms(t,o),En(),o.colorScheme!==A&&Zl();let xe=Al.getForInstance(o.plugins);r.length=0,r.push(...xe),M=o.launcher?.enabled??!0,P=o.launcher?.autoExpand??!1,ee=o.features?.showReasoning??!0,ce=o.features?.showToolCalls??!0,ae=o.features?.scrollToBottom??{};let Ue=Gt();Z=o.features?.scrollBehavior??{},Ue!==Gt()&&(Tr(),Kn()),_l(),Zt();let pt=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!pt){if(Ae||(pe=new us(ye),Ae=new ps(Te,pe),Oe=Oe??new fs,pe.open().then(()=>Ae?.restore()).catch(()=>{}),_.setSSEEventCallback((te,qe)=>{o.onSSEEvent?.(te,qe),Oe?.processEvent(te,qe),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(qe)})})),!et&&H){let te=o.features?.eventStream?.classNames,qe="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"+(te?.toggleButton?" "+te.toggleButton:"");et=h("button",qe),et.style.width="28px",et.style.height="28px",et.style.color=Vt.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let mt=re("activity","18px","currentColor",1.5);mt&&et.appendChild(mt);let nt=ke.clearChatButtonWrapper,at=ke.closeButtonWrapper,Ot=nt||at;Ot&&Ot.parentNode===H?H.insertBefore(et,Ot):H.appendChild(et),et.addEventListener("click",()=>{ot?hr():Qa()})}}else!Y&&pt&&(hr(),et&&(et.remove(),et=null),Ae?.clear(),pe?.destroy(),Ae=null,pe=null,Oe?.reset(),Oe=null);if(o.launcher?.enabled===!1&&Bt&&(Bt.destroy(),Bt=null),o.launcher?.enabled===!1&&zt&&(zt.remove(),zt=null),o.launcher?.enabled!==!1&&!Bt&&!zt){let{instance:te,element:qe}=ll({config:o,plugins:r,onToggle:Cc});Bt=te,te||(zt=qe),t.appendChild(qe)}Bt&&Bt.update(o),W&&o.launcher?.title!==void 0&&(W.textContent=o.launcher.title),q&&o.launcher?.subtitle!==void 0&&(q.textContent=o.launcher.subtitle);let tt=o.layout?.header;if(tt?.layout!==U&&H){let te=tt?Ha(o,tt,{showClose:D(),onClose:()=>dt(!1,"user")}):Po({config:o,showClose:D(),onClose:()=>dt(!1,"user")});yt.replaceHeader(te),H=yt.header.element,E=yt.header.iconHolder,W=yt.header.headerTitle,q=yt.header.headerSubtitle,S=yt.header.closeButton,U=tt?.layout}else if(tt){if(E&&(E.style.display=tt.showIcon===!1?"none":""),W&&(W.style.display=tt.showTitle===!1?"none":""),q&&(q.style.display=tt.showSubtitle===!1?"none":""),S){let te=D()&&tt.showCloseButton!==!1;S.style.display=te?"":"none"}if(ke.clearChatButtonWrapper){let te=tt.showClearChat;if(te!==void 0){ke.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:qe}=ke;qe&&!qe.classList.contains("persona-absolute")&&(te?qe.classList.remove("persona-ml-auto"):qe.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;H&&(H.style.display=At?"":"none");let Lt=o.layout?.showFooter!==!1;$&&($.style.display=Lt?"":"none"),Ho(),Zt(),M!==x?M?dt(P,"auto"):(F=!0,Pr()):P!==K&&dt(P,"auto"),K=P,x=M,Wr(),Ic();let He=JSON.stringify(o.toolCall)!==JSON.stringify(g),_e=JSON.stringify(o.messageActions)!==JSON.stringify(m),St=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),ut=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,Ut=o.iterationDisplay!==Q,ft=(o.features?.showReasoning??!0)!==(N??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(He||_e||St||ut||Ut||ft)&&_&&(ni++,Mr(be,_.getMessages(),we));let Pt=o.features?.streamAnimation?.type;if(Pt!==ne&&Pt&&Pt!=="none"){let te=lr(Pt,o.features?.streamAnimation?.plugins);te&&Ia(te,t)}let Be=o.launcher??{},Ze=Be.headerIconHidden??!1,xt=o.layout?.header?.showIcon,jt=Ze||xt===!1,st=Be.headerIconName,ct=Be.headerIconSize??"48px";if(E){let te=ue.querySelector(".persona-border-b-persona-divider"),qe=te?.querySelector(".persona-flex-col");if(jt)E.style.display="none",te&&qe&&!te.contains(qe)&&te.insertBefore(qe,te.firstChild);else{if(E.style.display="",E.style.height=ct,E.style.width=ct,te&&qe&&(te.contains(E)?E.nextSibling!==qe&&(E.remove(),te.insertBefore(E,qe)):te.insertBefore(E,qe)),st){let nt=parseFloat(ct)||24,at=re(st,nt*.6,"currentColor",1);at?E.replaceChildren(at):E.textContent=Be.agentIconText??"\u{1F4AC}"}else if(Be.iconUrl){let nt=E.querySelector("img");if(nt)nt.src=Be.iconUrl,nt.style.height=ct,nt.style.width=ct;else{let at=document.createElement("img");at.src=Be.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=ct,at.style.width=ct,E.replaceChildren(at)}}else{let nt=E.querySelector("svg"),at=E.querySelector("img");(nt||at)&&E.replaceChildren(),E.textContent=Be.agentIconText??"\u{1F4AC}"}let mt=E.querySelector("img");mt&&(mt.style.height=ct,mt.style.width=ct)}}let gt=o.layout?.header?.showTitle,Ye=o.layout?.header?.showSubtitle;if(W&&(W.style.display=gt===!1?"none":""),q&&(q.style.display=Ye===!1?"none":""),S){let te=D()&&o.layout?.header?.showCloseButton!==!1;S.style.display=te?"":"none";let qe=Be.closeButtonSize??"32px",mt=Be.closeButtonPlacement??"inline";S.style.height=qe,S.style.width=qe;let{closeButtonWrapper:nt}=ke,at=mt==="top-right",Ot=nt?.classList.contains("persona-absolute");if(nt&&at!==Ot)if(nt.remove(),at)nt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(nt);else{let Yn=Be.clearChat?.placement??"inline",Fr=Be.clearChat?.enabled??!0;nt.className=Fr&&Yn==="inline"?"":"persona-ml-auto";let Uc=ue.querySelector(".persona-border-b-persona-divider");Uc&&Uc.appendChild(nt)}if(S.style.color=Be.closeButtonColor||Vt.actionIconColor,Be.closeButtonBackgroundColor?(S.style.backgroundColor=Be.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),Be.closeButtonBorderWidth||Be.closeButtonBorderColor){let Yn=Be.closeButtonBorderWidth||"0px",Fr=Be.closeButtonBorderColor||"transparent";S.style.border=`${Yn} solid ${Fr}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");Be.closeButtonBorderRadius?(S.style.borderRadius=Be.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),Be.closeButtonPaddingX?(S.style.paddingLeft=Be.closeButtonPaddingX,S.style.paddingRight=Be.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),Be.closeButtonPaddingY?(S.style.paddingTop=Be.closeButtonPaddingY,S.style.paddingBottom=Be.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let tn=Be.closeButtonIconName??"x",bn=Be.closeButtonIconText??"\xD7";S.innerHTML="";let Dt=re(tn,"28px","currentColor",1);Dt?(Dt.style.display="block",S.appendChild(Dt)):S.textContent=bn;let _t=Be.closeButtonTooltipText??"Close chat",Rn=Be.closeButtonShowTooltip??!0;S.setAttribute("aria-label",_t),nt&&Ft({anchor:S,trigger:nt,text:()=>S?.getAttribute("aria-label")??_t,enabled:Rn})}let{clearChatButton:De,clearChatButtonWrapper:ht}=ke;if(De){let te=Be.clearChat??{},qe=te.enabled??!0,mt=o.layout?.header?.showClearChat,nt=mt!==void 0?mt:qe,at=te.placement??"inline";if(ht){ht.style.display=nt?"":"none";let{closeButtonWrapper:Ot}=ke;!J()&&Ot&&!Ot.classList.contains("persona-absolute")&&(nt?Ot.classList.remove("persona-ml-auto"):Ot.classList.add("persona-ml-auto"));let tn=at==="top-right",bn=ht.classList.contains("persona-absolute");if(!J()&&tn!==bn&&nt){if(ht.remove(),tn)ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px",ue.style.position="relative",ue.appendChild(ht);else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let _t=ue.querySelector(".persona-border-b-persona-divider"),Rn=ke.closeButtonWrapper;_t&&Rn&&Rn.parentElement===_t?_t.insertBefore(ht,Rn):_t&&_t.appendChild(ht)}let Dt=ke.closeButtonWrapper;Dt&&!Dt.classList.contains("persona-absolute")&&(tn?Dt.classList.add("persona-ml-auto"):Dt.classList.remove("persona-ml-auto"))}}if(nt){if(!J()){let Yn=te.size??"32px";De.style.height=Yn,De.style.width=Yn}let Ot=te.iconName??"refresh-cw",tn=te.iconColor??"";De.style.color=tn||Vt.actionIconColor,De.innerHTML="";let bn=J()?"14px":"20px",Dt=re(Ot,bn,"currentColor",1);if(Dt&&(Dt.style.display="block",De.appendChild(Dt)),te.backgroundColor?(De.style.backgroundColor=te.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let Yn=te.borderWidth||"0px",Fr=te.borderColor||"transparent";De.style.border=`${Yn} solid ${Fr}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");te.borderRadius?(De.style.borderRadius=te.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),te.paddingX?(De.style.paddingLeft=te.paddingX,De.style.paddingRight=te.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),te.paddingY?(De.style.paddingTop=te.paddingY,De.style.paddingBottom=te.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let _t=te.tooltipText??"Clear chat",Rn=te.showTooltip??!0;De.setAttribute("aria-label",_t),ht&&Ft({anchor:De,trigger:ht,text:()=>De?.getAttribute("aria-label")??_t,enabled:Rn})}}let Nt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Tl],cn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[hs.message,hs.messageAndClick];k=Ml({parsers:Nt,handlers:cn,getSessionMetadata:v,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),we=Su(o,k,Ce),_.updateConfig(o),Mr(be,_.getMessages(),we),ti(),fc(),ui(_.isStreaming());let Br=o.voiceRecognition?.enabled===!0,_s=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mt=o.voiceRecognition?.provider?.type==="runtype";if(Br&&(_s||Mt))if(!V||!$e){let te=xf(o.voiceRecognition,o.sendButton);te&&(V=te.micButton,$e=te.micButtonWrapper,je.insertBefore($e,un),V.addEventListener("click",Ns),V.disabled=_.isStreaming())}else{let te=o.voiceRecognition??{},qe=o.sendButton??{},mt=te.iconName??"mic",nt=qe.size??"40px",at=te.iconSize??nt,Ot=parseFloat(at)||24;V.style.width=at,V.style.height=at,V.style.minWidth=at,V.style.minHeight=at;let tn=te.iconColor??qe.textColor;V.innerHTML="";let bn=re(mt,Ot,tn||"currentColor",1.5);bn?V.appendChild(bn):V.textContent="\u{1F3A4}";let Dt=te.backgroundColor??qe.backgroundColor;Dt?V.style.backgroundColor=Dt:V.style.backgroundColor="",tn?V.style.color=tn:V.style.color="var(--persona-text, #111827)",te.borderWidth?(V.style.borderWidth=te.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),te.borderColor?V.style.borderColor=te.borderColor:V.style.borderColor="",te.paddingX?(V.style.paddingLeft=te.paddingX,V.style.paddingRight=te.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),te.paddingY?(V.style.paddingTop=te.paddingY,V.style.paddingBottom=te.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let _t=te.tooltipText??"Start voice recognition",Rn=te.showTooltip??!1;V.setAttribute("aria-label",_t),$e&&Ft({anchor:V,trigger:$e,text:()=>V?.getAttribute("aria-label")??_t,enabled:Rn}),$e.style.display="",V.disabled=_.isStreaming()}else V&&$e&&($e.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():An&&Qn());if(o.attachments?.enabled===!0){if(!Pe||!Se){let te=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Xe||(Xe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Xe.style.display="none",X.insertBefore(Xe,ve)),Le||(Le=document.createElement("input"),Le.type="file",Le.accept=(te.allowedTypes??Fn).join(","),Le.multiple=(te.maxFiles??4)>1,Le.style.display="none",Le.setAttribute("aria-label","Attach files"),X.insertBefore(Le,ve)),Pe=h("div","persona-send-button-wrapper"),Se=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Se.type="button",Se.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let nt=te.buttonIconName??"paperclip",at=mt,Ot=parseFloat(at)||40,tn=Math.round(Ot*.6);Se.style.width=at,Se.style.height=at,Se.style.minWidth=at,Se.style.minHeight=at,Se.style.fontSize="18px",Se.style.lineHeight="1";let bn=re(nt,tn,"currentColor",1.5);bn?Se.appendChild(bn):Se.textContent="\u{1F4CE}",Se.addEventListener("click",_t=>{_t.preventDefault(),Le?.click()}),Pe.appendChild(Se);let Dt=te.buttonTooltipText??"Attach file";Ft({anchor:Se,trigger:Pe,text:()=>Se?.getAttribute("aria-label")??Dt}),Ee?Ee.append(Pe):X.appendChild(Pe),!Ct&&Le&&Xe&&(Ct=Qr.fromConfig(te),Ct.setPreviewsContainer(Xe),Le.addEventListener("change",async()=>{Ct&&Le?.files&&(await Ct.handleFileSelect(Le.files),Le.value="")}))}else{Pe.style.display="";let te=o.attachments??{};Le&&(Le.accept=(te.allowedTypes??Fn).join(","),Le.multiple=(te.maxFiles??4)>1),Ct&&Ct.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Tu(o.attachments?.dropOverlay)),Se){let te=o.attachments??{},qe=te.buttonTooltipText??"Attach file";Se.setAttribute("aria-label",qe),Se.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,nt=re(te.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);nt?Se.appendChild(nt):Se.textContent="\u{1F4CE}",Pe&&Ft({anchor:Se,trigger:Pe,text:()=>Se?.getAttribute("aria-label")??qe})}}else Pe&&(Pe.style.display="none"),Ct&&Ct.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Wt=o.sendButton??{},Dr=Wt.useIcon??!1,zs=Wt.iconText??"\u2191",qo=Wt.iconName,Us=Wt.tooltipText??"Send message",Ti=Wt.showTooltip??!1,Co=Wt.size??"40px",In=Wt.backgroundColor,Ao=Wt.textColor;if(Dr){if(de.style.width=Co,de.style.height=Co,de.style.minWidth=Co,de.style.minHeight=Co,de.style.fontSize="18px",de.style.lineHeight="1",Ao?de.style.color=Ao:de.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(de.innerHTML="",qo){let te=parseFloat(Co)||24,qe=Ao?.trim()||"currentColor",mt=re(qo,te,qe,2);mt?de.appendChild(mt):de.textContent=zs}else de.textContent=zs;de.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",In?(de.style.backgroundColor=In,de.classList.remove("persona-bg-persona-primary")):(de.style.backgroundColor="",de.classList.add("persona-bg-persona-primary"))}else de.textContent=o.copy?.sendButtonLabel??"Send",de.style.width="",de.style.height="",de.style.minWidth="",de.style.minHeight="",de.style.fontSize="",de.style.lineHeight="",de.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",In?(de.style.backgroundColor=In,de.classList.remove("persona-bg-persona-accent")):de.classList.add("persona-bg-persona-accent"),Ao?de.style.color=Ao:de.classList.add("persona-text-white");Wt.borderWidth?(de.style.borderWidth=Wt.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),Wt.borderColor?de.style.borderColor=Wt.borderColor:de.style.borderColor="",Wt.paddingX?(de.style.paddingLeft=Wt.paddingX,de.style.paddingRight=Wt.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Wt.paddingY?(de.style.paddingTop=Wt.paddingY,de.style.paddingBottom=Wt.paddingY):(de.style.paddingTop="",de.style.paddingBottom=""),_.isStreaming()||de.setAttribute("aria-label",Us),un&&Ft({anchor:de,trigger:un,text:()=>de.getAttribute("aria-label")??Us,enabled:Ti});let js=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);js?(be.style.maxWidth=js,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",X&&(X.style.maxWidth=js,X.style.marginLeft="auto",X.style.marginRight="auto"),bt&&(bt.style.maxWidth=js,bt.style.marginLeft="auto",bt.style.marginRight="auto")):(be.style.maxWidth="",be.style.marginLeft="",be.style.marginRight="",be.style.width="",X&&(X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight=""),bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""));let Jn=o.statusIndicator??{},kf=Jn.visible??!0;if(T.style.display=kf?"":"none",_){let te=_.getStatus();Tt(T,(mt=>mt==="idle"?Jn.idleText??It.idle:mt==="connecting"?Jn.connectingText??It.connecting:mt==="connected"?Jn.connectedText??It.connected:mt==="error"?Jn.errorText??It.error:It[mt])(te),Jn,te)}T.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Lf=Jn.align==="left"?"persona-text-left":Jn.align==="center"?"persona-text-center":"persona-text-right";T.classList.add(Lf)},open(){D()&&dt(!0,"api")},close(){D()&&dt(!1,"api")},toggle(){D()&&dt(!F,"api")},reconnect(){_.reconnectNow()},clearChat(){Mn=!1,_.clearMessages(),ho.clear(),Kn();try{localStorage.removeItem(ur),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ur}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ur)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),d?.clear&&li(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},k.syncFromMetadata(),Ae?.clear(),Oe?.reset(),Fe?.update()},setMessage(i){return!ve||_.isStreaming()?!1:(!F&&D()&&dt(!0,"system"),ve.value=i,ve.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming())return!1;let g=i?.trim()||ve.value.trim();return g?(!F&&D()&&dt(!0,"system"),ve.value="",ve.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!F&&D()&&dt(!0,"system"),Ke.manuallyDeactivated=!1,yn(),_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),kn("user"),_.isVoiceActive()&&Uo()})),!0):An?!0:xc()?(!F&&D()&&dt(!0,"system"),Ke.manuallyDeactivated=!1,yn(),Ds("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,yn(),kn("user"),Pn()}),!0):!1:An?(Ke.manuallyDeactivated=!0,yn(),Qn("user"),!0):!1},injectMessage(i){return!F&&D()&&dt(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!F&&D()&&dt(!0,"system");let g=_.injectAssistantMessage(i);return ie&&(ie=!1,ge&&(clearTimeout(ge),ge=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(i){return!F&&D()&&dt(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!F&&D()&&dt(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!F&&D()&&dt(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!F&&D()&&dt(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!F&&D()&&dt(!0,"system"),_.injectTestEvent(i)},async connectStream(i,g){return _.connectStream(i,g)},__pushEventStreamEvent(i){Ae&&(Oe?.processEvent(i.type,i.payload),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!Y||!Ae||Qa()},hideEventStream(){ot&&hr()},isEventStreamVisible(){return ot},showArtifacts(){Kt(o)&&(Mn=!1,Bo=!0,En(),Je?.setMobileOpen(!0))},hideArtifacts(){Kt(o)&&(Mn=!0,En())},upsertArtifact(i){return Kt(o)?(So(o.features?.artifacts,i.artifactType)==="panel"&&(Mn=!1,Bo=!0),_.upsertArtifact(i)):null},selectArtifact(i){Kt(o)&&_.selectArtifact(i)},clearArtifacts(){Kt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return M&&!F&&!J()||!ve?!1:(ve.focus(),!0)},async resolveApproval(i,g,m){let A=_.getMessages().find(L=>L.variant==="approval"&&L.approval?.id===i);if(!A?.approval)throw new Error(`Approval not found: ${i}`);if(A.approval.toolType==="webmcp"){_.resolveWebMcpApproval(A.id,g);return}return _.resolveApproval(A.approval,g,m)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(i){C(i)},on(i,g){return l.on(i,g)},off(i,g){l.off(i,g)},isOpen(){return D()&&F},isVoiceActive(){return Ke.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:D()&&F,launcherEnabled:M,voiceActive:Ke.active,streaming:_.isStreaming()}},showCSATFeedback(i){!F&&D()&&dt(!0,"system");let g=be.querySelector(".persona-feedback-container");g&&g.remove();let m=xu({onSubmit:async(b,A)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(b,A),i?.onSubmit?.(b,A)},onDismiss:i?.onDismiss,...i});be.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!F&&D()&&dt(!0,"system");let g=be.querySelector(".persona-feedback-container");g&&g.remove();let m=Cu({onSubmit:async(b,A)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(b,A),i?.onSubmit?.(b,A)},onDismiss:i?.onDismiss,...i});be.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,g){return _.submitCSATFeedback(i,g)},async submitNPSFeedback(i,g){return _.submitNPSFeedback(i,g)},destroy(){hi(),wo!=null&&(clearInterval(wo),wo=null),ze.forEach(i=>i()),Re.remove(),Ve?.remove(),Bt?.destroy(),zt?.remove(),mo&&S.removeEventListener("click",mo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:kt,getMessages:kt.getMessages,getStatus:kt.getStatus,getMetadata:kt.getPersistentMetadata,updateMetadata:kt.updatePersistentMetadata,clearHistory:()=>kt.clearChat(),setVoiceActive:m=>m?kt.startVoiceRecognition():kt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ze.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===i)&&kt.focusInput()};if(window.addEventListener("persona:focusInput",g),ze.push(()=>{window.removeEventListener("persona:focusInput",g)}),Y){let N=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&kt.showEventStream()},G=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&kt.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",G),ze.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",G)})}let m=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===i)&&kt.showArtifacts()},b=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===i)&&kt.hideArtifacts()},A=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==i||G?.artifact&&kt.upsertArtifact(G.artifact)},L=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==i||typeof G?.id=="string"&&kt.selectArtifact(G.id)},Q=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===i)&&kt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",Q),ze.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",Q)})}let ln=Ty(o.persistState);if(ln&&D()){let i=My(ln.storage),g=`${ln.keyPrefix}widget-open`,m=`${ln.keyPrefix}widget-voice`,b=`${ln.keyPrefix}widget-voice-mode`;if(i){let A=ln.persist?.openState&&i.getItem(g)==="true",L=ln.persist?.voiceState&&i.getItem(m)==="true",Q=ln.persist?.voiceState&&i.getItem(b)==="true";if(A&&setTimeout(()=>{kt.open(),setTimeout(()=>{if(L||Q)kt.startVoiceRecognition();else if(ln.persist?.focusInput){let N=t.querySelector("textarea");N&&N.focus()}},100)},0),ln.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(g,"true")}),l.on("widget:closed",()=>{i.setItem(g,"false")})),ln.persist?.voiceState&&(l.on("voice:state",N=>{i.setItem(m,N.active?"true":"false")}),l.on("user:message",N=>{i.setItem(b,N.viaVoice?"true":"false")})),ln.clearOnChatClear){let N=()=>{i.removeItem(g),i.removeItem(m),i.removeItem(b)},G=()=>N();window.addEventListener("persona:clear-chat",G),ze.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(w&&D()&&setTimeout(()=>{kt.open()},0),_o(),!qu){let i=Vs(()=>{_&&(ni++,ho.clear(),Mr(be,_.getMessages(),we))});ze.push(i)}return kt};var Eu=(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},Ly=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Py=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Iy=(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.")},ku=(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"},Rl=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=""},Lu=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Rl(t)},Ll=t=>{t.style.transition=""},Pl=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=""},Il=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Va=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},Ry=(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))},Wy=(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)},Hy=t=>{let e=or(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:qt(e,r)??r;return{inset:o(n?.inset,ga),canvasBackground:o(n?.canvasBackground,ma)}},Pu=(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},By=(t,e,n,o,r,s,a,l)=>{let p=pn(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";Ry(t,e,n,o,d),Wy(t,e,n,o,p.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.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 f=t.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,I=f!=null?f.innerWidth<=C:!1;if(v&&I&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Pl(e),Ll(o),Lu(o),Il(n),Va(r,o),Pu(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??$t),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(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"),Lu(o),Ly(o,p.maxHeight),Pu(o,c&&a,u,w),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Pl(e),Ll(o),Il(n),Va(r,o);let k=p.animate?"transform 180ms ease":"none",M=p.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":M;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=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=k,o.style.transform=P,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Ll(o),Rl(o),Va(r,o);let k=Eu(p.width,t.clientWidth),M=Math.max(0,t.clientWidth),P=p.animate?"margin-left 180ms ease":"none",z=p.side==="right"?a?-k:0:a?0:-k;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=`${M+k}px`,e.style.transition=P,e.style.marginLeft=`${z}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${M}px`,n.style.maxWidth=`${M}px`,n.style.minWidth=`${M}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.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="",Pl(e),Rl(o),Il(n),Va(r,o);let k=p.reveal==="emerge";k?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let M=a?p.width:"0px",P=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",z=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${M}`,o.style.width=M,o.style.maxWidth=M,o.style.minWidth=M,o.style.minHeight="0",Py(o,p.maxHeight),o.style.overflow=k||z?"hidden":"visible",o.style.transition=P,k){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let K=c?`calc(${Eu(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=K,r.style.minWidth=K,r.style.maxWidth=K,r.style.boxSizing="border-box"}}},Dy=(t,e)=>{let n=t.ownerDocument.createElement("div");return ku(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){ku(n,o)},destroy(){n.remove()}}},Fy=(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"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,t),p.appendChild(t);let w=null,f=()=>{w?.disconnect(),w=null},v=null,C=()=>{v=e?.launcher?.detachedPanel===!0?Hy(e):null};C();let I=()=>{By(a,l,p,d,c,e,u,v)},B=null,k=()=>{B?.(),B=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(B=ha(()=>{C(),I()}))},M=()=>{f(),pn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{I()}),w.observe(a)))},P=!1,z=()=>{I(),M(),u&&!P&&a.dataset.personaDockMobileFullscreen!=="true"&&(P=!0,Iy(a,pn(e)))},K=a.ownerDocument.defaultView,x=()=>{z()};return K?.addEventListener("resize",x),pn(e).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),z(),k(),{mode:"docked",host:c,shell:a,syncWidgetState(U){let j=U.launcherEnabled?U.open:!0;u!==j&&(u=j,z())},updateConfig(U){e=U,(e?.launcher?.enabled??!0)===!1&&(u=!0),C(),z(),k()},destroy(){K?.removeEventListener("resize",x),B?.(),B=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},Iu=(t,e)=>Ht(e)?Fy(t,e):Dy(t,e);var ys={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Ru=.15,Wu=1.5,Wl="persona-preview-shell-theme",Ny={load:()=>null,save:()=>{},clear:()=>{}},Oy=["How do I get started?","Pricing & plans","Talk to support"];function Hl(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function _y(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 Hu(t){let e=_y(t);return`* { box-sizing: border-box; }
141
141
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
142
142
  html { color-scheme: ${t}; }
143
143
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
@@ -161,7 +161,7 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
161
161
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
162
162
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
163
163
  .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}; }
164
- .preview-workspace-card.short { height: 96px; }`}function Lu(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Rl);o||(o=n.createElement("style"),o.id=Rl,n.head.appendChild(o)),o.textContent=ku(e)}var Ry=`
164
+ .preview-workspace-card.short { height: 96px; }`}function Bu(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Wl);o||(o=n.createElement("style"),o.id=Wl,n.head.appendChild(o)),o.textContent=Hu(e)}var $y=`
165
165
  <div class="preview-iframe-mock" aria-hidden="true">
166
166
  <div class="preview-iframe-chrome">
167
167
  <span class="preview-iframe-dot"></span>
@@ -180,7 +180,7 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
180
180
  <div class="preview-iframe-line body"></div>
181
181
  <div class="preview-iframe-line body"></div>
182
182
  </div>
183
- </div>`,Wy=`
183
+ </div>`,zy=`
184
184
  <div class="preview-workspace-content-shell" aria-hidden="true">
185
185
  <div class="preview-iframe-line hero"></div>
186
186
  <div class="preview-iframe-line body"></div>
@@ -193,8 +193,8 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
193
193
  <div class="preview-workspace-card short"></div>
194
194
  <div class="preview-workspace-card short"></div>
195
195
  </div>
196
- </div>`;function Pu(t,e,n,o){let r=`
197
- ${Ry}
196
+ </div>`;function Du(t,e,n,o){let r=`
197
+ ${$y}
198
198
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
199
199
  <div class="preview-workspace-shell">
200
200
  <div class="preview-workspace-topbar">
@@ -206,7 +206,7 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
206
206
  </div>
207
207
  <div class="preview-workspace-body">
208
208
  <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
209
- ${Wy}
209
+ ${zy}
210
210
  </div>
211
211
  </div>
212
212
  </div>`;return`<!DOCTYPE html>
@@ -214,16 +214,16 @@ _Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]
214
214
  <head>
215
215
  <meta charset="UTF-8">
216
216
  <meta name="viewport" content="width=device-width, initial-scale=1">
217
- <link rel="stylesheet" href="${Wl(o)}">
218
- <style id="${Rl}">${ku(e)}</style>
217
+ <link rel="stylesheet" href="${Hl(o)}">
218
+ <style id="${Wl}">${Hu(e)}</style>
219
219
  </head>
220
220
  <body>
221
221
  ${n?s:r}
222
222
  </body>
223
- </html>`}var By=()=>[{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()}],Hy=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function Dy(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]: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"&&Hy(e)?[...By(),...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 Ny(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:Py:t.suggestionChips,initialMessages:Dy(e,t,n),storageAdapter:Ly};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Fy(t,e){let n=t.theme?ar(t.theme,{validate:!1}):ar();return{...ct,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function yr(t,e){let n=t.scene??"conversation";return Ny(Fy(t,e),n,t.appendedMessages??[])}function Iu(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:yr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:yr(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:yr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:yr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:yr(t,n),shellMode:n}]}function Oy(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,p=1,d=0;function c(){return n.device??"desktop"}function u(){return n.zoom??l}function w(){let E=getComputedStyle(t),T=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),I=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),z=40,N=(n.compareMode??"off")!=="off",x=(t.clientWidth-T-z)/(N?2:1),j=t.clientHeight-I-z;if(x<=0||j<=0)return 1;let q=As[c()]??As.desktop;return Math.min(x/q.w,j/q.h,1)}function f(){l=w();let E=Math.max(Mu,Math.min(Eu,u()));p=E;let T=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let I of T){let z=I.dataset.device??"desktop",N=As[z]??As.desktop;I.style.width=`${N.w*E}px`,I.style.height=`${N.h*E}px`,z==="mobile"&&(I.style.borderRadius=`${32*E}px`);let x=I.querySelector("iframe");x&&(x.style.width=`${N.w}px`,x.style.height=`${N.h}px`,x.style.transformOrigin="top left",x.style.transition="none",x.style.transform=`scale(${E})`)}n.onScaleChange?.(E)}function v(){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 P(){if(a)return;v();let E=++d,T=Iu(n),I=c(),z=(n.compareMode??"off")!=="off",N=(n.scene??"conversation")==="minimized",x=n.widgetCssPath??"/widget-dist/widget.css",j=n.buildSrcdoc??Pu,q=I==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",J=Ce=>`<div class="${q}" data-mount-id="${Ce.mountId}" data-device="${I}" data-shell-mode="${Ce.shellMode}">
224
- ${z?`<div class="preview-frame-meta"><span class="preview-frame-label">${Wl(Ce.label)}</span></div>`:""}
225
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Ce.mountId}"></iframe>
226
- </div>`,D=z?`<div class="preview-compare-grid">${T.map(Ce=>`<div class="preview-compare-cell">${J(Ce)}</div>`).join("")}</div>`:`<div class="preview-single">${J(T[0])}</div>`;n.morphContainer?n.morphContainer(t,D):t.innerHTML=D,f();let $=C(),fe=0,ye=$.length,Le=()=>{if(a||E!==d)return;for(let te of $){let ge=te.dataset.mountId;if(!ge||!te.contentDocument)continue;let Y=T.find(ue=>ue.mountId===ge);if(!Y)continue;let ae=()=>{},Z=Nt(Y.config),ve=Z?(()=>{let ue=te.contentDocument?.getElementById(`preview-content-${ge}`);if(!ue)return null;let Te=Tu(ue,Y.config),Ae=te.contentDocument.createElement("div");Ae.id=ge,Ae.style.height="100%",Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1",Ae.style.minHeight="0",Te.host.appendChild(Ae);let ze=()=>Te.syncWidgetState(we.getState()),Ne=ae;return ae=()=>{Te.destroy(),Ne()},Ae.__syncDock=ze,Ae.__hostLayout=Te,Ae})():te.contentDocument.getElementById(ge);if(!ve)continue;let we=wu(ve,Y.config);if(o.push(we),Z&&ve.__syncDock){let ue=ve.__syncDock,Te=we.on("widget:opened",ue),Ae=we.on("widget:closed",ue),ze=ae;ae=()=>{Te(),Ae(),ze()},ue()}r.push(ae),N&&we.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let te of o)te.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
223
+ </html>`}var Uy=()=>[{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()}],jy=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function qy(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]: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"&&jy(e)?[...Uy(),...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 Vy(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:Oy:t.suggestionChips,initialMessages:qy(e,t,n),storageAdapter:Ny};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Ky(t,e){let n=t.theme?nr(t.theme,{validate:!1}):nr();return{...it,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function fr(t,e){let n=t.scene??"conversation";return Vy(Ky(t,e),n,t.appendedMessages??[])}function Fu(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:fr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:fr(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:fr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:fr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:fr(t,n),shellMode:n}]}function Gy(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,p=1,d=0;function c(){return n.device??"desktop"}function u(){return n.zoom??l}function w(){let k=getComputedStyle(t),M=parseFloat(k.paddingLeft)+parseFloat(k.paddingRight),P=parseFloat(k.paddingTop)+parseFloat(k.paddingBottom),z=40,K=(n.compareMode??"off")!=="off",x=(t.clientWidth-M-z)/(K?2:1),U=t.clientHeight-P-z;if(x<=0||U<=0)return 1;let j=ys[c()]??ys.desktop;return Math.min(x/j.w,U/j.h,1)}function f(){l=w();let k=Math.max(Ru,Math.min(Wu,u()));p=k;let M=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let P of M){let z=P.dataset.device??"desktop",K=ys[z]??ys.desktop;P.style.width=`${K.w*k}px`,P.style.height=`${K.h*k}px`,z==="mobile"&&(P.style.borderRadius=`${32*k}px`);let x=P.querySelector("iframe");x&&(x.style.width=`${K.w}px`,x.style.height=`${K.h}px`,x.style.transformOrigin="top left",x.style.transition="none",x.style.transform=`scale(${k})`)}n.onScaleChange?.(k)}function v(){n.onBeforeDestroy?.();for(let k of o)k.destroy();for(let k of r)k();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function I(){if(a)return;v();let k=++d,M=Fu(n),P=c(),z=(n.compareMode??"off")!=="off",K=(n.scene??"conversation")==="minimized",x=n.widgetCssPath??"/widget-dist/widget.css",U=n.buildSrcdoc??Du,j=P==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",J=we=>`<div class="${j}" data-mount-id="${we.mountId}" data-device="${P}" data-shell-mode="${we.shellMode}">
224
+ ${z?`<div class="preview-frame-meta"><span class="preview-frame-label">${Hl(we.label)}</span></div>`:""}
225
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${we.mountId}"></iframe>
226
+ </div>`,D=z?`<div class="preview-compare-grid">${M.map(we=>`<div class="preview-compare-cell">${J(we)}</div>`).join("")}</div>`:`<div class="preview-single">${J(M[0])}</div>`;n.morphContainer?n.morphContainer(t,D):t.innerHTML=D,f();let F=C(),ie=0,ge=F.length,Ce=()=>{if(a||k!==d)return;for(let ee of F){let ce=ee.dataset.mountId;if(!ce||!ee.contentDocument)continue;let Y=M.find(pe=>pe.mountId===ce);if(!Y)continue;let ae=()=>{},Z=Ht(Y.config),he=Z?(()=>{let pe=ee.contentDocument?.getElementById(`preview-content-${ce}`);if(!pe)return null;let Te=Iu(pe,Y.config),Ae=ee.contentDocument.createElement("div");Ae.id=ce,Ae.style.height="100%",Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1",Ae.style.minHeight="0",Te.host.appendChild(Ae);let Oe=()=>Te.syncWidgetState(ye.getState()),Fe=ae;return ae=()=>{Te.destroy(),Fe()},Ae.__syncDock=Oe,Ae.__hostLayout=Te,Ae})():ee.contentDocument.getElementById(ce);if(!he)continue;let ye=Mu(he,Y.config);if(o.push(ye),Z&&he.__syncDock){let pe=he.__syncDock,Te=ye.on("widget:opened",pe),Ae=ye.on("widget:closed",pe),Oe=ae;ae=()=>{Te(),Ae(),Oe()},pe()}r.push(ae),K&&ye.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let ee of o)ee.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
227
227
 
228
228
  This is a preview of the artifact sidebar.
229
229
 
@@ -231,4 +231,4 @@ This is a preview of the artifact sidebar.
231
231
 
232
232
  - Markdown rendering
233
233
  - Document toolbar
234
- - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:$,controllers:[...o]})};for(let Ce of $){let te=Ce.dataset.mountId;if(!te)continue;let ge=T.find(Y=>Y.mountId===te);ge&&(Ce.addEventListener("load",()=>{fe++,fe>=ye&&Le()},{once:!0}),Ce.srcdoc=j(te,ge.shellMode,Nt(ge.config),x))}ye===0&&Le()}function H(){if(a)return;let E=Iu(n);if(o.length!==E.length){P();return}if(E.some(I=>{let z=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${I.mountId}"]`);return!z||z.dataset.shellMode!==I.shellMode})){P();return}o.forEach((I,z)=>{I.update(E[z].config),(n.scene??"conversation")==="minimized"&&I.close()});for(let I of E){let z=t.querySelector(`iframe[data-mount-id="${I.mountId}"]`);z&&Lu(z,I.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||f()}),s.observe(t)),P(),{update(E){if(a)return;let T=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},T?P():H()},destroy(){a||(a=!0,v(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},f())},getIframes(){return C()},getScale(){return p},setZoom(E){a||(n={...n,zoom:E},f())}}}export{Oy as createThemePreview};
234
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:F,controllers:[...o]})};for(let we of F){let ee=we.dataset.mountId;if(!ee)continue;let ce=M.find(Y=>Y.mountId===ee);ce&&(we.addEventListener("load",()=>{ie++,ie>=ge&&Ce()},{once:!0}),we.srcdoc=U(ee,ce.shellMode,Ht(ce.config),x))}ge===0&&Ce()}function B(){if(a)return;let k=Fu(n);if(o.length!==k.length){I();return}if(k.some(P=>{let z=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${P.mountId}"]`);return!z||z.dataset.shellMode!==P.shellMode})){I();return}o.forEach((P,z)=>{P.update(k[z].config),(n.scene??"conversation")==="minimized"&&P.close()});for(let P of k){let z=t.querySelector(`iframe[data-mount-id="${P.mountId}"]`);z&&Bu(z,P.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||f()}),s.observe(t)),I(),{update(k){if(a)return;let M=k.device!==void 0&&k.device!==n.device||k.scene!==void 0&&k.scene!==n.scene||k.compareMode!==void 0&&k.compareMode!==n.compareMode||k.widgetCssPath!==void 0&&k.widgetCssPath!==n.widgetCssPath;n={...n,...k},M?I():B()},destroy(){a||(a=!0,v(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},f())},getIframes(){return C()},getScale(){return p},setZoom(k){a||(n={...n,zoom:k},f())}}}export{Gy as createThemePreview};