@runtypelabs/persona 4.13.0 → 4.14.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 (64) hide show
  1. package/dist/codegen.cjs +1 -1
  2. package/dist/codegen.js +1 -1
  3. package/dist/context-mentions.d.cts +98 -6
  4. package/dist/context-mentions.d.ts +98 -6
  5. package/dist/index.cjs +64 -64
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +183 -8
  8. package/dist/index.d.ts +183 -8
  9. package/dist/index.global.js +54 -54
  10. package/dist/index.global.js.map +1 -1
  11. package/dist/index.js +67 -67
  12. package/dist/index.js.map +1 -1
  13. package/dist/launcher.global.js +1 -1
  14. package/dist/launcher.global.js.map +1 -1
  15. package/dist/smart-dom-reader.d.cts +98 -6
  16. package/dist/smart-dom-reader.d.ts +98 -6
  17. package/dist/theme-editor-preview.cjs +66 -66
  18. package/dist/theme-editor-preview.d.cts +100 -6
  19. package/dist/theme-editor-preview.d.ts +100 -6
  20. package/dist/theme-editor-preview.js +75 -75
  21. package/dist/theme-editor.cjs +10 -10
  22. package/dist/theme-editor.d.cts +134 -7
  23. package/dist/theme-editor.d.ts +134 -7
  24. package/dist/theme-editor.js +10 -10
  25. package/dist/theme-reference.cjs +1 -1
  26. package/dist/widget.css +1 -1
  27. package/package.json +1 -1
  28. package/src/artifacts-session.test.ts +106 -0
  29. package/src/client.test.ts +2 -2
  30. package/src/client.ts +4 -1
  31. package/src/components/artifact-card.ts +13 -2
  32. package/src/components/artifact-inline.ts +11 -2
  33. package/src/components/composer-builder.test.ts +2 -0
  34. package/src/components/composer-builder.ts +1 -1
  35. package/src/components/composer-parts.test.ts +2 -0
  36. package/src/components/composer-parts.ts +1 -1
  37. package/src/components/message-bubble.test.ts +7 -1
  38. package/src/components/message-bubble.ts +11 -8
  39. package/src/index-core.ts +34 -0
  40. package/src/session.ts +45 -4
  41. package/src/styles/widget.css +10 -1
  42. package/src/theme-editor/index.ts +5 -0
  43. package/src/theme-editor/presets.test.ts +43 -0
  44. package/src/theme-editor/presets.ts +101 -87
  45. package/src/theme-editor/sections.test.ts +39 -7
  46. package/src/theme-editor/sections.ts +60 -8
  47. package/src/theme-editor/state-preferences.test.ts +15 -0
  48. package/src/theme-editor/state.ts +46 -0
  49. package/src/theme-editor/types.ts +15 -1
  50. package/src/theme-editor/webmcp/tools.test.ts +13 -0
  51. package/src/theme-editor/webmcp/tools.ts +5 -0
  52. package/src/types.ts +139 -9
  53. package/src/ui.artifact-pane-gating.test.ts +5 -5
  54. package/src/ui.config-preferences.test.ts +166 -0
  55. package/src/ui.ts +43 -25
  56. package/src/ui.typing-indicator.test.ts +135 -0
  57. package/src/utils/artifact-display.test.ts +180 -16
  58. package/src/utils/artifact-display.ts +155 -14
  59. package/src/utils/config-merge.test.ts +60 -0
  60. package/src/utils/config-merge.ts +6 -1
  61. package/src/utils/feature-preferences.test.ts +326 -0
  62. package/src/utils/feature-preferences.ts +498 -0
  63. package/src/utils/theme.test.ts +92 -0
  64. package/src/utils/tokens.ts +7 -7
@@ -1,34 +1,34 @@
1
- import{a as Qc}from"./chunk-5EIIHQLQ.js";import{a as h,b as Gc,c as Ne,d as Wn,e as re,f as Yc,h as Zc,i as ed}from"./chunk-MMUPR2JW.js";import{a as Xc,b as Jc}from"./chunk-IO5VVUKP.js";var Ko=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:sb,load:Bf,provide:ab,getSync:Li}=Ko({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),Js=new Set,Df=()=>{let t=[...Js];Js.clear();for(let e of t)try{e()}catch{}};var Ff=()=>{let t=Li();return t?Promise.resolve(t):Bf().then(e=>(Df(),e))},Ys=t=>Li()?()=>{}:(Js.add(t),Ff().catch(()=>{}),()=>{Js.delete(t)});var Hn=Li;var Nf=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=Nf(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Zs=t=>t?Pi({markedOptions:t.options,renderer:t.renderer}):Pi(),cb=Pi();var Zn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Of={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"]},_f=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,$f=()=>{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:")&&!_f.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Of)}},ea=t=>t===!1?null:typeof t=="function"?t:$f();var td=/^\s*\|?[\s:|-]*-[\s:|-]*$/,nd=t=>t.includes("|"),od=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())},zf=t=>`| ${t.join(" | ")} |`,Uf=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,jf=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),rd=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(!nd(r)||td.test(r)||!td.test(s))continue;let a=od(r).length;if(a<1)continue;let l=Uf(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()===""||!nd(d))break;let c=zf(jf(od(d),a));e[p]!==c&&(e[p]=c,n=!0)}o=p-1}return n?e.join(`
3
- `):t};var sd="var(--persona-md-table-scroll-fade, 24px)",ad=new WeakSet;function ld(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 id(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":sd),t.style.setProperty("--persona-fade-r",r<=1?"0px":sd)}function Ii(t){ad.has(t)||(ad.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&id(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(id)}var Bn="webmcp:",Ri=new Map,cd=t=>{Ri.clear();for(let e of t){let n=e.title?.trim();n&&Ri.set(e.name,n)}},_r=t=>Ri.get(fd(t)),ta={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},dd=null;function ud(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}:${qf(e.join(""))}`}function pd(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 qf(t){let e=pd(t,0).toString(36),n=pd(t,2654435761).toString(36);return`${e}.${n}`}var na=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 ta.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}cd(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=Kf(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=fd(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}`)}cd(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=_r(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,Jf(n),{signal:c.signal});return Gf(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}(dd?await dd():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ta.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,ta.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??Qf;try{return await n(e)}catch(o){return ta.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=>Vf(e,o))}},fd=t=>t.startsWith(Bn)?t.slice(Bn.length):t,Go=t=>t.startsWith(Bn),Vf=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Kf=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Gf=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:Yf(e)}]}},vn=t=>({isError:!0,content:[{type:"text",text:t}]}),Qf=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=Xf(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
1
+ import{a as cd}from"./chunk-5EIIHQLQ.js";import{a as h,b as ld,c as Be,d as Dn,e as ie,f as ud,h as fd,i as gd}from"./chunk-MMUPR2JW.js";import{a as dd,b as pd}from"./chunk-IO5VVUKP.js";var Yo=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:Fb,load:eg,provide:Nb,getSync:_i}=Yo({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),ia=new Set,tg=()=>{let e=[...ia];ia.clear();for(let t of e)try{t()}catch{}};var ng=()=>{let e=_i();return e?Promise.resolve(e):eg().then(t=>(tg(),t))},la=e=>_i()?()=>{}:(ia.add(e),ng().catch(()=>{}),()=>{ia.delete(e)});var Fn=_i;var og=e=>{if(e)return e},$i=e=>{let t=null;return n=>{let o=Fn();if(!o)return oo(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=og(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},ca=e=>e?$i({markedOptions:e.options,renderer:e.renderer}):$i(),$b=$i();var oo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var rg={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"]},sg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ag=()=>{let e=null;return t=>{let n=Fn();if(!n)return oo(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!sg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,rg)}},da=e=>e===!1?null:typeof e=="function"?e:ag();var md=/^\s*\|?[\s:|-]*-[\s:|-]*$/,hd=e=>e.includes("|"),yd=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},ig=e=>`| ${e.join(" | ")} |`,lg=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,cg=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),bd=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!hd(r)||md.test(r)||!md.test(s))continue;let a=yd(r).length;if(a<1)continue;let l=lg(a);t[o+1]!==l&&(t[o+1]=l,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!hd(d))break;let c=ig(cg(yd(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
+ `):e};var vd="var(--persona-md-table-scroll-fade, 24px)",wd=new WeakSet;function Cd(e){e.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 xd(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":vd),e.style.setProperty("--persona-fade-r",r<=1?"0px":vd)}function zi(e){wd.has(e)||(wd.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&xd(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(xd)}var Nn="webmcp:",ji=new Map,Ad=e=>{ji.clear();for(let t of e){let n=t.title?.trim();n&&ji.set(t.name,n)}},Gr=e=>ji.get(Ed(e)),pa={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Sd=null;function Md(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${dg(t.join(""))}`}function Td(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.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 dg(e){let t=Td(e,0).toString(36),n=Td(e,2654435761).toString(36);return`${t}.${n}`}var ua=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return pa.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Ad(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=ug(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return xn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return xn(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=Ed(t),a;try{a=await r.getTools()}catch(v){let C=v instanceof Error?v.message:String(v);return xn(`Failed to read WebMCP registry: ${C}`)}Ad(a);let l=a.find(v=>v.name===s);if(!l)return xn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return xn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return xn("Aborted by cancel()");let p=Gr(s),d={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return xn("User declined the tool call.");if(o?.aborted)return xn("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,hg(n),{signal:c.signal});return fg(v)}catch(v){if(u)return xn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return xn("Aborted by cancel()");let C=v instanceof Error?v.message:String(v);return xn(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}(Sd?await Sd():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){pa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,pa.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):t}async requestConfirm(t){let n=this.confirmHandler??gg;try{return await n(t)}catch(o){return pa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>pg(t,o))}},Ed=e=>e.startsWith(Nn)?e.slice(Nn.length):e,Zo=e=>e.startsWith(Nn),pg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},ug=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},fg=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:yg(t)}]}},xn=e=>({isError:!0,content:[{type:"text",text:e}]}),gg=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=mg(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
4
4
 
5
5
  Arguments:
6
- ${e}`:"")+(t.description?`
6
+ ${t}`:"")+(e.description?`
7
7
 
8
- ${t.description}`:"");return window.confirm(n)},Xf=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)}},Jf=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Yf=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function To(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function oa(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_",eg="flow_";function gd(t){return t.startsWith(Zf)?{kind:"agentId",agentId:t}:t.startsWith(eg)?{kind:"flowId",flowId:t}:null}function md(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=gd(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=gd(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 tg,ARR as ng,OBJ as og,STR as rg}from"partial-json";var Wi="ask_user_question",$r=8,Qo="data-persona-ask-sheet-for",sg="Other",ag="Other\u2026",yd="Type your own answer here",bd="Send",ig="Next",lg="Back",cg="Submit all",dg="Skip",pg=3,Hi="data-ask-current-index",Bi="data-ask-question-count",vd="data-ask-answers",Di="data-ask-grouped",wd="data-ask-layout",ug=t=>t.layout==="pills"?"pills":"rows",fg=t=>t.getAttribute(wd)==="pills"?"pills":"rows",hd=!1,xd=t=>t.replace(/["\\]/g,"\\$&"),Mo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Wi,Fi=t=>t?.features?.askUserQuestion??{},Xo=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=tg(r,rg|og|ng);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},zr=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>$r&&!hd&&(hd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${$r}.`)),e.slice(0,$r)},gg=t=>zr(t)[0]??null,mg=(t,e)=>zr(t)[e]??null,hg=(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))},Cd=(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},yg=(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=Cd(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},bg=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},vg=(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<pg;c++)s.appendChild(bg(o));return s}if(p.forEach((c,u)=>{s.appendChild(yg(c,u,o,a))}),t?.allowFreeText!==!1){let c=o==="rows"?sg:ag;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??yd,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let v=Cd(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},Ad=(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??yd,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??bd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},wg=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??bd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},xg=(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??lg,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??dg,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??cg:n.nextLabel??ig,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Eo=t=>{let e=t.getAttribute(vd);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},Sd=(t,e)=>{t.setAttribute(vd,JSON.stringify(e))},dn=t=>{let e=Number(t.getAttribute(Hi)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Cg=(t,e)=>{t.setAttribute(Hi,String(Math.max(0,Math.floor(e))))},Jo=t=>{let e=Number(t.getAttribute(Bi)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},eo=t=>t.getAttribute(Di)==="true",Ag=(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},Sg=(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)))},ra=(t,e)=>{let{payload:n}=Xo(e),o=zr(n),r=Eo(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},Td=t=>{let e=Eo(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="")},Md=t=>{if(!eo(t))return;let e=Eo(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}},Ni=(t,e,n)=>{let o=Fi(n),r=fg(t),{payload:s,complete:a}=Xo(e),l=eo(t),p=dn(t),d=Jo(t),c=l?mg(s,p):gg(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=vg(c,o,a,r);C.replaceWith(k)}if(r!=="rows"){let k=t.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(Ad(o,r))}let I=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!I?t.appendChild(wg(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=xg(p,d,o);B?B.replaceWith(k):t.appendChild(k)}else B&&B.remove();Td(t),Md(t)},Tg=(t,e,n)=>{let o=Fi(e),r=ug(o),s=t.toolCall.id,a=zr(n),l=Math.max(1,a.length),p=l>1,d=Ag(t,a),c=p?Sg(t,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Qo,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(Bi,String(l)),u.setAttribute(Hi,String(c)),u.setAttribute(Di,p?"true":"false"),u.setAttribute(wd,r),Sd(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`),hg(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(Ad(o,r)),Ni(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Mg=(t,e,n)=>{let{payload:o}=Xo(e),r=Math.max(1,zr(o).length);r>Jo(t)&&(t.setAttribute(Bi,String(r)),r>1&&!eo(t)&&t.setAttribute(Di,"true")),Ni(t,e,n)};var sa=(t,e,n)=>{if(!n||!Mo(t)||Fi(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Qo}]`).forEach(d=>{d.getAttribute(Qo)!==r&&d.remove()});let a=n.querySelector(`[${Qo}="${xd(r)}"]`);if(a){Mg(a,t,e);return}let{payload:l}=Xo(t),p=Tg(t,e,l);n.appendChild(p)},Yo=(t,e)=>{if(!t)return;let n=e?`[${Qo}="${xd(e)}"]`:`[${Qo}]`;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)})},Oi=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=Eo(t),o=dn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,Sd(t,n),Td(t),Md(t)},aa=(t,e,n,o)=>{let r=Jo(t),s=Math.max(0,Math.min(r-1,o));Cg(t,s),Ni(t,e,n)};var Dn="suggest_replies";var Eg={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},Ed={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:Eg,origin:"sdk",annotations:{readOnlyHint:!0}},_i=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),$i=t=>t.variant==="tool"&&t.toolCall?.name===Dn,kg=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},kd=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=kg(n.toolCall?.args);return o.length>0?o:null}return null},Ld=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var Lg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:$r,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},Pg={name:Wi,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:Lg,origin:"sdk",annotations:{readOnlyHint:!0}},ia=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Pg),Ld(t)&&e.push(Ed),e};import{parse as Ig,STR as Rg,OBJ as Wg}from"partial-json";var Pd=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)}},Hg=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`},Id=t=>t.status==="complete"?Hg(t):t.status==="pending"?"Waiting":"",Bg=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 Rd=t=>t.status==="complete"?Bg(t):"Using tool...",la=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},jr=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 la(e)},ca=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return la(e)},zi=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=jr(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},da=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ur(o,n.slice(s,a.index),[]),a[1]!==void 0?Ur(o,a[1],["bold"]):a[2]!==void 0?Ur(o,a[2],["italic"]):a[3]!==void 0&&Ur(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ur(o,n.slice(s),[]),o},Ur=(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})},Dg=()=>{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
+ ${e.description}`:"");return window.confirm(n)},mg=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},hg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},yg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function un(e){return e==="card"?"collapsed":e}function er(e){return e.split(";",1)[0].trim().toLowerCase()}function bg(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(er(r)===t)return{mode:un(s),selector:er(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(er(r)===o)return{mode:un(s),selector:o}}function vg(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:un(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?er(t.file.mimeType):void 0,p=l?bg(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:un(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:un(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:un(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:un(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:un(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ro(e,t){return vg(e,t).mode}function Qr(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var wg="agent_",xg="flow_";function kd(e){return e.startsWith(wg)?{kind:"agentId",agentId:e}:e.startsWith(xg)?{kind:"flowId",flowId:e}:null}function Ld(e,t){let n=e.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=kd(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[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=kd(n);if(r)return r;let s=t?.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 Cg,ARR as Ag,OBJ as Sg,STR as Tg}from"partial-json";var Ui="ask_user_question",Xr=8,tr="data-persona-ask-sheet-for",Mg="Other",Eg="Other\u2026",Id="Type your own answer here",Rd="Send",kg="Next",Lg="Back",Pg="Submit all",Ig="Skip",Rg=3,Vi="data-ask-current-index",qi="data-ask-question-count",Wd="data-ask-answers",Ki="data-ask-grouped",Hd="data-ask-layout",Wg=e=>e.layout==="pills"?"pills":"rows",Hg=e=>e.getAttribute(Hd)==="pills"?"pills":"rows",Pd=!1,Bd=e=>e.replace(/["\\]/g,"\\$&"),Lo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ui,Gi=e=>e?.features?.askUserQuestion??{},nr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=Cg(r,Tg|Sg|Ag);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Jr=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Xr&&!Pd&&(Pd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Xr}.`)),t.slice(0,Xr)},Bg=e=>Jr(e)[0]??null,Dg=(e,t)=>Jr(e)[t]??null,Fg=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Dd=(e,t,n)=>{if(e!=="rows")return null;let o=h("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){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},Ng=(e,t,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(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),l=h("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=h("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Dd(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Og=e=>{let n=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},_g=(e,t,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=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Rg;c++)s.appendChild(Og(o));return s}if(p.forEach((c,u)=>{s.appendChild(Ng(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Mg:Eg;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=t.freeTextPlaceholder??Id,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let v=Dd(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=t.freeTextLabel??c,s.appendChild(u)}}return s},Fd=(e,t)=>{let o=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");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=e.freeTextPlaceholder??Id,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=h("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Rd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},$g=e=>{let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Rd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},zg=(e,t,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??Lg,r.setAttribute("data-ask-user-action","back"),r.disabled=e===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??Ig,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=e===t-1;return l.textContent=p?n.submitAllLabel??Pg:n.nextLabel??kg,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Po=e=>{let t=e.getAttribute(Wd);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Nd=(e,t)=>{e.setAttribute(Wd,JSON.stringify(t))},fn=e=>{let t=Number(e.getAttribute(Vi)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},jg=(e,t)=>{e.setAttribute(Vi,String(Math.max(0,Math.floor(t))))},or=e=>{let t=Number(e.getAttribute(qi)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},so=e=>e.getAttribute(Ki)==="true",Ug=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.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=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},fa=(e,t)=>{let{payload:n}=nr(t),o=Jr(n),r=Po(e),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},Od=e=>{let t=Po(e),n=fn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.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=e.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="")},_d=e=>{if(!so(e))return;let t=Po(e),n=fn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Qi=(e,t,n)=>{let o=Gi(n),r=Hg(e),{payload:s,complete:a}=nr(t),l=so(e),p=fn(e),d=or(e),c=l?Dg(s,p):Bg(s),u=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof c?.question=="string"?c.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let L=_g(c,o,a,r);C.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Fd(o,r))}let R=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!R?e.appendChild($g(o)):(!u||l)&&R&&R.remove(),e.setAttribute("data-multi-select",u?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(l){let L=zg(p,d,o);B?B.replaceWith(L):e.appendChild(L)}else B&&B.remove();Od(e),_d(e)},qg=(e,t,n)=>{let o=Gi(t),r=Wg(o),s=e.toolCall.id,a=Jr(n),l=Math.max(1,a.length),p=l>1,d=Ug(e,a),c=p?Vg(e,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(tr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(qi,String(l)),u.setAttribute(Vi,String(c)),u.setAttribute(Ki,p?"true":"false"),u.setAttribute(Hd,r),Nd(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`),Fg(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 R=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 R.setAttribute("data-ask-pill-list","true"),R.setAttribute("role","group"),u.appendChild(R),r!=="rows"&&u.appendChild(Fd(o,r)),Qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Kg=(e,t,n)=>{let{payload:o}=nr(t),r=Math.max(1,Jr(o).length);r>or(e)&&(e.setAttribute(qi,String(r)),r>1&&!so(e)&&e.setAttribute(Ki,"true")),Qi(e,t,n)};var ga=(e,t,n)=>{if(!n||!Lo(e)||Gi(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${tr}]`).forEach(d=>{d.getAttribute(tr)!==r&&d.remove()});let a=n.querySelector(`[${tr}="${Bd(r)}"]`);if(a){Kg(a,e,t);return}let{payload:l}=nr(e),p=qg(e,t,l);n.appendChild(p)},rr=(e,t)=>{if(!e)return;let n=t?`[${tr}="${Bd(t)}"]`:`[${tr}]`;e.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)})},Xi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ao=(e,t)=>{let n=Po(e),o=fn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Nd(e,n),Od(e),_d(e)},ma=(e,t,n,o)=>{let r=or(e),s=Math.max(0,Math.min(r-1,o));jg(e,s),Qi(e,t,n)};var On="suggest_replies";var Gg={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},$d={name:On,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:Gg,origin:"sdk",annotations:{readOnlyHint:!0}},Ji=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Yi=e=>e.variant==="tool"&&e.toolCall?.name===On,Qg=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.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},zd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Yi(n))continue;let o=Qg(n.toolCall?.args);return o.length>0?o:null}return null},jd=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var Xg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Xr,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},Jg={name:Ui,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:Xg,origin:"sdk",annotations:{readOnlyHint:!0}},ha=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Jg),jd(e)&&t.push($d),t};import{parse as Yg,STR as Zg,OBJ as em}from"partial-json";var Ud=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),io=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},tm=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Vd=e=>e.status==="complete"?tm(e):e.status==="pending"?"Waiting":"",nm=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var qd=e=>e.status==="complete"?nm(e):"Using tool...",ya=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Zr=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return ya(t)},ba=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return ya(t)},Zi=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Zr(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},va=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Yr(o,n.slice(s,a.index),[]),a[1]!==void 0?Yr(o,a[1],["bold"]):a[2]!==void 0?Yr(o,a[2],["italic"]):a[3]!==void 0&&Yr(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Yr(o,n.slice(s),[]),o},Yr=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},om=()=>{let e=null,t=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},Wd=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Hd=()=>{let t=Dg();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)}},Bd=()=>{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=Ig(n,Rg|Wg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?Pd(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=Pd(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Dd=()=>{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 Fd="4.13.0";var Vr=Fd;var Ng="https://api.runtype.com/v1/dispatch",pa="https://api.runtype.com";function Og(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 Ui=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 _g(t){switch(t){case"json":return Bd;case"regex-json":return Hd;case"xml":return Dd;default:return Wd}}var Nd=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function $g(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=Nd(n);if(!Nd(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 Kr=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??Ng,this.headers={"Content-Type":"application/json","X-Persona-Version":Vr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??_g(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 na(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=md(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$/,"")||pa}/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":Vr},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$/,"")||pa}/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":Vr},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(Ui).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":Vr},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$/,"")||pa}/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?ud(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(/\/+$/,"")||pa}/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=[...ia(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(Ui).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=[...ia(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(Ui).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=[...ia(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),le=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},ie=(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=le(T);if(y){let W=String(y);return ie(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 ie(S,E),E},$e=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)}},Qe=new Map,He=new Map,Ee=new Map,Xe=(T,O,y)=>{let S=Ee.get(T);S||(S=[],Ee.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=He.get(T.id),E=$g(S,y);T.rawContent=E;let W=Qe.get(T.id),q=ke=>{let rt=T.content??"";ke.trim()!==""&&(rt.trim().length===0||ke.startsWith(rt)||ke.trimStart().startsWith(rt.trim()))&&(T.content=ke)},H=()=>{if(W){let ke=W.close?.();ke instanceof Promise&&ke.catch(()=>{})}Qe.delete(T.id),He.delete(T.id),T.streaming=!1,f(T)};if(!W){q(y),H();return}let $=qr(E);if($!==null&&$.trim()!==""){q($),H();return}let se=ke=>{let rt=typeof ke=="string"?ke:ke?.text??null;if(rt!==null&&rt.trim()!=="")return rt;let V=W.getExtractedText();return V!==null&&V.trim()!==""?V:y},qe;try{qe=W.processChunk(E)}catch{q(y),H();return}if(qe instanceof Promise){qe.then(ke=>{q(se(ke)),H()}).catch(()=>{q(y),H()});return}q(se(qe)),H()},St=null,ht=(T,O,y,S)=>{T.rawContent=O,Qe.has(T.id)||Qe.set(T.id,this.createStreamParser());let E=Qe.get(T.id),W=O.trim().startsWith("{")||O.trim().startsWith("[");if(W&&He.set(T.id,O),E.__isPlainTextParser===!0){T.content=S!==void 0?O:T.content+y,He.delete(T.id),Qe.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,He.delete(T.id),Qe.delete(T.id),T.rawContent=void 0,f(T))}).catch(()=>{T.content=S!==void 0?O:T.content+y,He.delete(T.id),Qe.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,He.delete(T.id),Qe.delete(T.id),T.rawContent=void 0,f(T))}},Be=(T,O)=>{let y=O??T.content;if(y==null||y===""){T.streaming=!1,f(T);return}let E=He.get(T.id)??ot(y);T.rawContent=E;let W=Qe.get(T.id),q=null,H=!1;if(W&&(q=W.getExtractedText(),q===null&&(q=qr(E)),q===null)){let $=W.processChunk(E);$ instanceof Promise?(H=!0,$.then(se=>{let qe=typeof se=="string"?se:se?.text??null;qe!==null&&(T.content=qe,T.streaming=!1,Qe.delete(T.id),He.delete(T.id),f(T))}).catch(()=>{})):q=typeof $=="string"?$:$?.text??null}if(!H){q!==null&&q.trim()!==""?T.content=q:He.has(T.id)||(T.content=ot(y));let $=Qe.get(T.id);if($){let se=$.close?.();se instanceof Promise&&se.catch(()=>{}),Qe.delete(T.id)}He.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},Ke=[],Le,ue=new Map,ae=0,be="agent",yt=!1,ve=null,de=null,un=new Map,X=this.config.iterationDisplay??"separate";for(Le=()=>{for(let T=0;T<Ke.length;T++){let O=Ke[T].payloadType,y=Ke[T].payload;if(!yt&&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 $=Xe(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"&&(ae=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}ie(le(y),S);let W=$e(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=$e(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=$e(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 $=le(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=$e(E),q=y.toolName,H=y.origin==="webmcp"&&!Go(q)?`webmcp:${q}`:q,$=Go(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"?(Be(W),St=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},ht($,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},ht(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&&Be(W),P.delete(S),K.delete(S),z.delete(S);continue}let E=v;E&&(be==="flow"?(Be(E),St=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=St;St=null;let q=y.stopReason,H=y.result?.response;if(W)q&&(W.stopReason=q),H!=null?on(W,H):W.streaming!==!1&&(Qe.delete(W.id),He.delete(W.id),W.streaming=!1,f(W));else{let $=H!=null&&H!=="";if($||q){let se=we();q&&(se.stopReason=q),$?Be(se,H):(se.streaming=!1,f(se))}}continue}}else if(O==="execution_start")be=y.kind==="flow"?"flow":"agent",yt=!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:ae;if(S!==ae){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)}ae=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,qe=$?[$]:[],ke=[];for(let rt of qe){if(!rt||typeof rt!="object")continue;let V=rt,ze=typeof V.type=="string"?V.type:void 0,Se=typeof V.mediaType=="string"?V.mediaType.toLowerCase():"",We=null,Pe="";if(ze==="media"){let Je=typeof V.data=="string"?V.data:void 0;if(!Je)continue;Pe=Se.length>0?Se:"application/octet-stream",We=`data:${Pe};base64,${Je}`}else if(ze==="image-url"){let Je=typeof V.url=="string"?V.url:void 0;if(!Je)continue;Pe=Se,We=Je}else if(ze==="file-url"){let Je=typeof V.url=="string"?V.url:void 0;if(!Je)continue;Pe=Se,We=Je}else continue;if(We)if(ze==="image-url"||Pe.startsWith("image/"))ke.push({type:"image",image:We,...Pe.includes("/")?{mimeType:Pe}:{}});else if(Pe.startsWith("audio/"))ke.push({type:"audio",audio:We,mimeType:Pe});else if(Pe.startsWith("video/"))ke.push({type:"video",video:We,mimeType:Pe});else{let Je=Pe||"application/octet-stream";ke.push({type:"file",data:We,mimeType:Je,filename:Og(Je)})}}if(ke.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:ke,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:ae}};f(Se);let We=v;We&&(We.streaming=!1,f(We)),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?Be(E):(E.streaming=!1,f(E)),v=null),k=null,M="",St=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=To(this.config.features?.artifacts,S),qe=typeof y.component=="string"?y.component:void 0,ke={id:`artifact-ref-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:oa(se,{artifactId:E,title:W,artifactType:S,status:"streaming",...H?{file:H}:{},...qe?{component:qe}:{}})};he.set(E,ke),f(ke)}}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,Qe.delete(E),He.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"})}}}}}Ke.length=0};;){let{done:T,value:O}=await s.read();if(T)break;l+=a.decode(O,{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:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Kd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Gd=()=>{let e=om();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Qd=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Yg(n,Zg|em);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Ud(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ud(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Xd=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Jd="4.14.0";var ts=Jd;var sm="https://api.runtype.com/v1/dispatch",wa="https://api.runtype.com";function am(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var el=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function im(e){switch(e){case"json":return Qd;case"regex-json":return Gd;case"xml":return Xd;default:return Kd}}var Yd=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function lm(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Yd(n);if(!Yd(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=es(e);return es(t)!==null&&a===null?t:e}var ns=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??sm,this.headers={"Content-Type":"application/json","X-Persona-Version":ts,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??im(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new ua(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Ld(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(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||wa}/v1/client/${t}`}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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ts},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$/,"")||wa}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ts},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(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,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:t,comment:n})}async submitNPSFeedback(t,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:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,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(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(el).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.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":ts},body:JSON.stringify(c),signal:t.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,t.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(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.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:t.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:t.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(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.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:t.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:t.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,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||wa}/v1/agents/${t.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:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Md(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,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=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||wa}/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:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ha(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(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,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(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(el).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=[...ha(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(el).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=[...ha(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);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(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);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(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=S=>{let D=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,y=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,P=S.tools?S.tools.map(T=>({...T,chunks:T.chunks?[...T.chunks]:void 0})):void 0;return{...S,reasoning:D,toolCall:y,tools:P}},w=S=>{if(S.role!=="assistant"||S.variant)return!0;let D=Array.isArray(S.contentParts)&&S.contentParts.length>0,y=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||D||y||!!S.stopReason},f=S=>{w(S)&&n({type:"message",message:u(S)})},v=null,C=null,R={current:null},B={current:null},L=null,E="",M=new Map,_=new Map,G=new Map,x=new Map,j=new Map,U={lastId:null,byStep:new Map},oe={lastId:null,byCall:new Map},F=S=>{if(S==null)return null;try{return String(S)}catch{return null}},$=S=>F(S.stepId??S.step_id??S.step??S.parentId??S.flowStepId??S.flow_step_id),X=S=>F(S.callId??S.call_id??S.requestId??S.request_id??S.toolCallId??S.tool_call_id??S.stepId??S.step_id),me=o,he=!1,Ae=()=>{if(v)return v;let S,D="",y=L;return!he&&me?(S=me,he=!0,D=r??""):me&&y?S=`${me}_${y}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:S,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(v),v},Z=(S,D)=>{U.lastId=D,S&&U.byStep.set(S,D)},ce=(S,D)=>{let y=S.reasoningId??S.id,P=$(S);if(y){let I=String(y);return Z(P,I),I}if(P){let I=U.byStep.get(P);if(I)return U.lastId=I,I}if(U.lastId&&!D)return U.lastId;if(!D)return null;let T=`reason-${c()}`;return Z(P,T),T},ee=S=>{let D=x.get(S);if(D)return D;let y={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:S,status:"streaming",chunks:[]}};return x.set(S,y),f(y),y},le=(S,D)=>{oe.lastId=D,S&&oe.byCall.set(S,D)},Y=new Set,pe=new Map,xe=new Set,ye=new Map,ve=S=>{if(!S)return!1;let D=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return D==="emit_artifact_markdown"||D==="emit_artifact_component"},je=(S,D)=>{let y=S.toolId??S.id,P=X(S);if(y){let I=String(y);return le(P,I),I}if(P){let I=oe.byCall.get(P);if(I)return oe.lastId=I,I}if(oe.lastId&&!D)return oe.lastId;if(!D)return null;let T=`tool-${c()}`;return le(P,T),T},Me=S=>{let D=j.get(S);if(D)return D;let y={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:S,status:"pending"}};return j.set(S,y),f(y),y},De=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let D=Number(S);if(!Number.isNaN(D)&&Number.isFinite(D))return D;let y=Date.parse(S);if(!Number.isNaN(y))return y}return Date.now()},Qe=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},Ve=new Map,Te=new Map,Le=new Map,Xe=(S,D,y)=>{let P=Le.get(S);P||(P=[],Le.set(S,P));let T=0,I=P.length;for(;T<I;){let H=T+I>>>1;P[H].seq<D?T=H+1:I=H}P[T]?.seq===D?P[T]={seq:D,text:y}:P.splice(T,0,{seq:D,text:y});let q="";for(let H=0;H<P.length;H++)q+=P[H].text;return q},Ht=(S,D)=>{let y=Qe(D),P=Te.get(S.id),T=lm(P,y);S.rawContent=T;let I=Ve.get(S.id),q=Re=>{let Je=S.content??"";Re.trim()!==""&&(Je.trim().length===0||Re.startsWith(Je)||Re.trimStart().startsWith(Je.trim()))&&(S.content=Re)},H=()=>{if(I){let Re=I.close?.();Re instanceof Promise&&Re.catch(()=>{})}Ve.delete(S.id),Te.delete(S.id),S.streaming=!1,f(S)};if(!I){q(y),H();return}let z=es(T);if(z!==null&&z.trim()!==""){q(z),H();return}let J=Re=>{let Je=typeof Re=="string"?Re:Re?.text??null;if(Je!==null&&Je.trim()!=="")return Je;let rt=I.getExtractedText();return rt!==null&&rt.trim()!==""?rt:y},qe;try{qe=I.processChunk(T)}catch{q(y),H();return}if(qe instanceof Promise){qe.then(Re=>{q(J(Re)),H()}).catch(()=>{q(y),H()});return}q(J(qe)),H()},It=null,qt=(S,D,y,P)=>{S.rawContent=D,Ve.has(S.id)||Ve.set(S.id,this.createStreamParser());let T=Ve.get(S.id),I=D.trim().startsWith("{")||D.trim().startsWith("[");if(I&&Te.set(S.id,D),T.__isPlainTextParser===!0){S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S);return}let H=T.processChunk(D);if(H instanceof Promise)H.then(z=>{let J=typeof z=="string"?z:z?.text??null;J!==null&&J.trim()!==""?(S.content=J,f(S)):!I&&!D.trim().startsWith("<")&&(S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S))}).catch(()=>{S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S)});else{let z=typeof H=="string"?H:H?.text??null;z!==null&&z.trim()!==""?(S.content=z,f(S)):!I&&!D.trim().startsWith("<")&&(S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S))}},xt=(S,D)=>{let y=D??S.content;if(y==null||y===""){S.streaming=!1,f(S);return}let T=Te.get(S.id)??Qe(y);S.rawContent=T;let I=Ve.get(S.id),q=null,H=!1;if(I&&(q=I.getExtractedText(),q===null&&(q=es(T)),q===null)){let z=I.processChunk(T);z instanceof Promise?(H=!0,z.then(J=>{let qe=typeof J=="string"?J:J?.text??null;qe!==null&&(S.content=qe,S.streaming=!1,Ve.delete(S.id),Te.delete(S.id),f(S))}).catch(()=>{})):q=typeof z=="string"?z:z?.text??null}if(!H){q!==null&&q.trim()!==""?S.content=q:Te.has(S.id)||(S.content=Qe(y));let z=Ve.get(S.id);if(z){let J=z.close?.();J instanceof Promise&&J.catch(()=>{}),Ve.delete(S.id)}Te.delete(S.id),S.streaming=!1,f(S)}},He=(S,D,y)=>{let P=_.get(S);if(P)return P;let T={id:`nested-${D}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:D}};return _.set(S,T),f(T),T},de=[],et,Ie=new Map,fe=0,se="agent",Pe=!1,it=null,ue=null,Ce=new Map,te=this.config.iterationDisplay??"separate";for(et=()=>{for(let S=0;S<de.length;S++){let D=de[S].payloadType,y=de[S].payload;if(!Pe&&se!=="flow"&&typeof y.stepType=="string"&&(se="flow"),D==="reasoning_start"){let P=typeof y.id=="string"?y.id:null,T=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(P&&T){M.set(P,T),He(P,T,"reasoning");continue}let I=ce(y,!0)??`reason-${c()}`,q=ee(I);q.reasoning=q.reasoning??{id:I,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??De(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(D==="reasoning_delta"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)&&_.has(P)){let H=_.get(P),z=y.reasoningText??y.text??y.delta??"";z&&y.hidden!==!0&&H.reasoning&&(H.reasoning.chunks.push(String(z)),f(H));continue}let T=ce(y,!1)??ce(y,!0)??`reason-${c()}`,I=ee(T);I.reasoning=I.reasoning??{id:T,status:"streaming",chunks:[]},I.reasoning.startedAt=I.reasoning.startedAt??De(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 z=Xe(T,H,String(q));I.reasoning.chunks=[z]}else I.reasoning.chunks.push(String(q))}if(I.reasoning.status=y.done?"complete":"streaming",y.done){I.reasoning.completedAt=De(y.completedAt??y.timestamp);let H=I.reasoning.startedAt??Date.now();I.reasoning.durationMs=Math.max(0,(I.reasoning.completedAt??Date.now())-H)}I.streaming=I.reasoning.status!=="complete",f(I)}else if(D==="reasoning_complete"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)&&_.has(P)){let z=_.get(P);if(z.reasoning){let J=typeof y.text=="string"?y.text:"";J&&z.reasoning.chunks.length===0&&z.reasoning.chunks.push(J),z.reasoning.status="complete",z.streaming=!1,f(z)}M.delete(P),_.delete(P);continue}let T=ce(y,!1)??ce(y,!0)??`reason-${c()}`,I=typeof y.text=="string"?y.text:"";!x.get(T)&&(I||y.scope==="loop")&&ee(T);let q=x.get(T);if(q?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(q.reasoning.scope=y.scope),I&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(I),q.reasoning.status="complete",q.reasoning.completedAt=De(y.completedAt??y.timestamp);let z=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-z),q.streaming=!1,f(q)}let H=$(y);H&&U.byStep.delete(H)}else if(D==="tool_start"){v&&(v.streaming=!1,f(v),v=null),typeof y.iteration=="number"&&(fe=y.iteration);let P=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??je(y,!0)??`tool-${c()}`,T=y.toolName??y.name;if(ve(T)){Y.add(P);continue}le(X(y),P);let I=Me(P),q=I.toolCall??{id:P,status:"pending"};q.name=T??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??De(y.startedAt??y.timestamp),q.completedAt=void 0,q.durationMs=void 0,I.toolCall=q,I.streaming=!0,y.executionId&&(I.agentMetadata={executionId:y.executionId,iteration:y.iteration}),f(I)}else if(D==="tool_output_delta"){let P=je(y,!1)??je(y,!0)??`tool-${c()}`;if(Y.has(P))continue;let T=Me(P),I=T.toolCall??{id:P,status:"running"};I.startedAt=I.startedAt??De(y.startedAt??y.timestamp);let q=y.text??y.delta??y.message??"";q&&(I.chunks=I.chunks??[],I.chunks.push(String(q))),I.status="running",T.toolCall=I,T.streaming=!0;let H=y.agentContext;(H||y.executionId)&&(T.agentMetadata=T.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(T)}else if(D==="tool_complete"){let P=je(y,!1)??je(y,!0)??`tool-${c()}`;if(Y.has(P)){Y.delete(P);continue}let T=Me(P),I=T.toolCall??{id:P,status:"running"};I.status="complete",y.result!==void 0&&(I.result=y.result),typeof y.duration=="number"&&(I.duration=y.duration),I.completedAt=De(y.completedAt??y.timestamp);let q=y.duration??y.executionTime;if(typeof q=="number")I.durationMs=q;else{let J=I.startedAt??Date.now();I.durationMs=Math.max(0,(I.completedAt??Date.now())-J)}T.toolCall=I,T.streaming=!1;let H=y.agentContext;(H||y.executionId)&&(T.agentMetadata=T.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(T);let z=X(y);z&&oe.byCall.delete(z)}else if(D==="await"&&y.toolName){let P=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,T=P??y.toolId??`local-${c()}`,I=Me(T),q=y.toolName,H=y.origin==="webmcp"&&!Zo(q)?`webmcp:${q}`:q,z=Zo(H),J=I.toolCall??{id:T,status:"pending"};J.name=H,J.args=y.parameters,J.status=z?"running":"complete",J.chunks=J.chunks??[],J.startedAt=J.startedAt??De(y.startedAt??y.timestamp??y.awaitedAt),z?(J.completedAt=void 0,J.duration=void 0,J.durationMs=void 0):J.completedAt=J.completedAt??J.startedAt,I.toolCall=J,I.streaming=!1,I.agentMetadata={...I.agentMetadata,executionId:y.executionId??I.agentMetadata?.executionId,awaitingLocalTool:!0,...P?{webMcpToolCallId:P}:{}},f(I)}else if(D==="text_start"){let P=typeof y.id=="string"?y.id:null,T=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(P&&T){M.set(P,T);continue}let I=v;I&&(se==="flow"?(xt(I),It=I):(I.streaming=!1,f(I)),v=null),L=typeof y.id=="string"?y.id:L,E=""}else if(D==="text_delta"){let P=typeof y.id=="string"?y.id:null,T=P?M.get(P):void 0;if(P&&T){let q=typeof y.delta=="string"?y.delta:"",H=(G.get(P)??"")+q;if(G.set(P,H),H.trim()==="")continue;let z=He(P,T);z.agentMetadata={...z.agentMetadata,executionId:y.executionId,parentToolId:T},qt(z,H,q,void 0);continue}if(L=typeof y.id=="string"?y.id:L,se==="flow"){let q=typeof y.delta=="string"?y.delta:"";if(E+=q,E.trim()==="")continue;let H=Ae();H.agentMetadata={executionId:y.executionId,iteration:y.iteration},qt(H,E,q,void 0),C=H;continue}let I=Ae();I.content+=y.delta??"",I.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:it??void 0,agentName:ue?.agentName},C=I,f(I)}else if(D==="text_complete"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)){let I=_.get(P);I&&xt(I),M.delete(P),G.delete(P),_.delete(P);continue}let T=v;T&&(se==="flow"?(xt(T),It=T):((T.content??"")===""&&typeof y.text=="string"&&(T.content=y.text),T.streaming=!1,f(T)),v=null),L=null,E=""}else if(D==="step_complete"){let P=y.stepType,T=y.executionType;if(P==="tool"||T==="context")continue;if(y.success===!1){let I=y.error,q=typeof I=="string"&&I!==""?I:I!=null&&typeof I=="object"&&Reflect.has(I,"message")?String(I.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 I=It;It=null;let q=y.stopReason,H=y.result?.response;if(I)q&&(I.stopReason=q),H!=null?Ht(I,H):I.streaming!==!1&&(Ve.delete(I.id),Te.delete(I.id),I.streaming=!1,f(I));else{let z=H!=null&&H!=="";if(z||q){let J=Ae();q&&(J.stopReason=q),z?xt(J,H):(J.streaming=!1,f(J))}}continue}}else if(D==="execution_start")se=y.kind==="flow"?"flow":"agent",Pe=!0,se==="agent"&&(ue={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:De(y.startedAt)});else if(D==="turn_start"){let P=typeof y.iteration=="number"?y.iteration:fe;if(P!==fe){if(ue&&(ue.currentIteration=P),te==="separate"&&P>1){let T=v;T&&(T.streaming=!1,f(T),Ce.set(P-1,T),v=null)}fe=P}it=typeof y.id=="string"?y.id:null,C=null}else if(D==="tool_input_delta"){let P=y.toolCallId??oe.lastId;if(P){let T=j.get(P);T?.toolCall&&(T.toolCall.chunks=T.toolCall.chunks??[],T.toolCall.chunks.push(y.delta??""),f(T))}}else{if(D==="tool_input_complete")continue;if(D==="turn_complete"){let P=y.stopReason,T=v??C;if(P&&T!==null){let I=y.id;(!I||T.agentMetadata?.turnId===I)&&(T.stopReason=P,f(T))}it===y.id&&(it=null)}else if(D==="media_start"){let P=String(y.id);Ie.set(P,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(D==="media_delta"){let P=Ie.get(String(y.id));P&&typeof y.delta=="string"&&P.parts.push(y.delta)}else if(D==="media_complete"){let P=String(y.id),T=Ie.get(P);Ie.delete(P);let I=(typeof y.mediaType=="string"?y.mediaType:void 0)??T?.mediaType??"application/octet-stream",q=typeof y.data=="string"?y.data:void 0,H=typeof y.url=="string"?y.url:T&&T.parts.length>0?T.parts.join(""):void 0,z=null;if(q)z={type:"media",data:q,mediaType:I};else if(H){let Je=I.toLowerCase();z={type:Je==="image"||Je.startsWith("image/")?"image-url":"file-url",url:H,mediaType:I}}let J=y.toolCallId??T?.toolCallId,qe=z?[z]:[],Re=[];for(let Je of qe){if(!Je||typeof Je!="object")continue;let rt=Je,V=typeof rt.type=="string"?rt.type:void 0,_e=typeof rt.mediaType=="string"?rt.mediaType.toLowerCase():"",be=null,$e="";if(V==="media"){let Fe=typeof rt.data=="string"?rt.data:void 0;if(!Fe)continue;$e=_e.length>0?_e:"application/octet-stream",be=`data:${$e};base64,${Fe}`}else if(V==="image-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;$e=_e,be=Fe}else if(V==="file-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;$e=_e,be=Fe}else continue;if(be)if(V==="image-url"||$e.startsWith("image/"))Re.push({type:"image",image:be,...$e.includes("/")?{mimeType:$e}:{}});else if($e.startsWith("audio/"))Re.push({type:"audio",audio:be,mimeType:$e});else if($e.startsWith("video/"))Re.push({type:"video",video:be,mimeType:$e});else{let Fe=$e||"application/octet-stream";Re.push({type:"file",data:be,mimeType:Fe,filename:am(Fe)})}}if(Re.length>0){let Je=c(),rt=J,_e={id:`agent-media-${typeof rt=="string"&&rt.length>0?`${rt}-${Je}`:String(Je)}`,role:"assistant",content:"",contentParts:Re,createdAt:new Date().toISOString(),streaming:!1,sequence:Je,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:fe}};f(_e);let be=v;be&&(be.streaming=!1,f(be)),v=null,R.current=null}}else if(D==="execution_complete"){let P=y.kind??se;P==="agent"&&ue&&(ue.status=y.success?"complete":"error",ue.completedAt=De(y.completedAt),ue.stopReason=y.stopReason);let T=v;T&&(P==="flow"&&T.streaming!==!1?xt(T):(T.streaming=!1,f(T)),v=null),L=null,E="",It=null,n({type:"status",status:"idle",terminal:!0})}else if(D==="execution_error"){let P=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(P)})}else if(D!=="ping"){if(D==="approval_start"){let P=y.approvalId??`approval-${c()}`,T={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.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(T)}else if(D==="step_await"&&y.awaitReason==="approval_required"){let P=y.approvalId??`approval-${c()}`,T={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.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(T)}else if(D==="approval_complete"){let P=y.approvalId;if(P){let I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:y.decision??"approved",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};f(I)}}else if(D==="artifact_start"||D==="artifact_delta"||D==="artifact_update"||D==="artifact_complete"){if(D==="artifact_start"){let P=y.artifactType,T=String(y.id),I=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:T,artifactType:P,title:I,component:typeof y.component=="string"?y.component:void 0,...H?{file:H}:{}});let z=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(ye.set(T,{markdown:"",title:I,file:H,...z?{props:z}:{}}),!xe.has(T)){xe.add(T);let J=ro(this.config.features?.artifacts,{artifactType:P,...H?{file:H}:{}}),qe=typeof y.component=="string"?y.component:void 0,Re={id:`artifact-ref-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Qr(J,{artifactId:T,title:I,artifactType:P,status:"streaming",...H?{file:H}:{},...qe?{component:qe}:{}})};pe.set(T,Re),f(Re)}}else if(D==="artifact_delta"){let P=String(y.id),T=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:P,artDelta:T});let I=ye.get(P);I&&(I.markdown+=T)}else if(D==="artifact_update"){let P=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:P,component:typeof y.component=="string"?y.component:void 0});let T=ye.get(String(y.id));T&&(T.props={...T.props??{},...P})}else if(D==="artifact_complete"){let P=String(y.id);n({type:"artifact_complete",id:P});let T=pe.get(P);if(T){T.streaming=!1;try{let I=JSON.parse(T.rawContent??"{}");if(I.props){I.props.status="complete";let q=ye.get(P);q?.markdown&&(I.props.markdown=q.markdown),q?.file&&(I.props.file=q.file),I.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(I.props.componentProps=q.props)}T.rawContent=JSON.stringify(I)}catch{}ye.delete(P),f(T),pe.delete(P)}}}else if(D==="transcript_insert"){let P=y.message;if(!P||typeof P!="object")continue;let T=String(P.id??`msg-${c()}`),I=P.role,H={id:T,role:I==="user"?"user":I==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(f(H),H.rawContent)try{let J=JSON.parse(H.rawContent)?.props?.artifactId;typeof J=="string"&&xe.add(J)}catch{}v=null,R.current=null,Ve.delete(T),Te.delete(T)}else if(D==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let P=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(P)});let T=v;T&&T.streaming&&(T.streaming=!1,f(T)),n({type:"status",status:"idle"})}}else if(D==="step_error"||D==="dispatch_error"||D==="flow_error"){let P=null;if(y.error instanceof Error)P=y.error;else if(D==="dispatch_error"){let T=y.message??y.error;T!=null&&T!==""&&(P=new Error(String(T)))}else{let T=y.error;typeof T=="string"&&T!==""?P=new Error(T):T!=null&&typeof T=="object"&&Reflect.has(T,"message")&&(P=new Error(String(T.message??T)))}if(P){n({type:"error",error:P});let T=v;T&&T.streaming&&(T.streaming=!1,f(T)),n({type:"status",status:"idle"})}}}}}de.length=0};;){let{done:S,value:D}=await s.read();if(S)break;l+=a.decode(D,{stream:!0});let y=l.split(`
12
12
 
13
- `);l=y.pop()??"";for(let S of y){let E=S.split(`
14
- `),W="message",q="",H=null;for(let ke of E)ke.startsWith("event:")?W=ke.replace("event:","").trim():ke.startsWith("data:")?q+=ke.replace("data:","").trim():ke.startsWith("id:")&&(H=ke.slice(3).trim());let $=()=>{H!==null&&H!==""&&n({type:"cursor",id:H})};if(!q){$();continue}let se;try{se=JSON.parse(q)}catch(ke){n({type:"error",error:ke instanceof Error?ke:new Error("Failed to parse chat stream payload")});continue}let qe=W!=="message"?W:se.type??"message";if(this.onSSEEvent?.(qe,se),this.parseSSEEvent){I.current=v;let ke=await this.handleCustomSSEEvent(se,n,I,f,c,B);if(I.current&&I.current!==v&&(v=I.current),ke){$();continue}}Ke.push({payloadType:qe,payload:se}),Le(),$()}}Le()}};function ua(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Zo(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var fa="[Image]";function Od(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function er(t){return{type:"text",text:t}}var _d=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],zg=["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=[..._d,...zg];function Ug(t){return _d.includes(t)||t.startsWith("image/")}function ga(t){return Ug(t.type)}async function $d(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ga(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 zd(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 jg(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Ud(t,e){let n=jg(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 jd=16e3,qg=24e3,Vg=4096,Kg=1380533830;function Gg(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Kg?new Uint8Array(t,44):new Uint8Array(t)}function Qg(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 Gr=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:jd,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:jd});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Qc(qg);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=`${Qg(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(Vg,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=Gg(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 ko=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 tr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Gr(t.runtype);case"browser":if(!ko.isSupported())throw new Error("Browser speech recognition not supported");return new ko(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 qd(t){if(t?.type==="custom"&&t.custom)return tr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return tr({type:"runtype",runtype:t.runtype});if(ko.isSupported())return tr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function ji(t){try{return qd(t),!0}catch{return!1}}function ma(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 nr=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):ma(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 Qr=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 qi(t){if(!t)return"";let e=Xg(t);return Vd(e!==null?e:t)}function Xg(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 Vd(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
- `),e=e.replace(/\n{2,}/g,`
16
- `),e.trim()}var Kd=null;var Vi=()=>Kd?Kd():import("./runtype-tts-entry-UJAEF7NZ.js");var Jg=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Yg(t,e){return Jg.some(n=>t[n]!==e[n])}function Ki(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}
13
+ `);l=y.pop()??"";for(let P of y){let T=P.split(`
14
+ `),I="message",q="",H=null;for(let Re of T)Re.startsWith("event:")?I=Re.replace("event:","").trim():Re.startsWith("data:")?q+=Re.replace("data:","").trim():Re.startsWith("id:")&&(H=Re.slice(3).trim());let z=()=>{H!==null&&H!==""&&n({type:"cursor",id:H})};if(!q){z();continue}let J;try{J=JSON.parse(q)}catch(Re){n({type:"error",error:Re instanceof Error?Re:new Error("Failed to parse chat stream payload")});continue}let qe=I!=="message"?I:J.type??"message";if(this.onSSEEvent?.(qe,J),this.parseSSEEvent){R.current=v;let Re=await this.handleCustomSSEEvent(J,n,R,f,c,B);if(R.current&&R.current!==v&&(v=R.current),Re){z();continue}}de.push({payloadType:qe,payload:J}),et(),z()}}et()}};function xa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function sr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ca="[Image]";function Zd(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ar(e){return{type:"text",text:e}}var ep=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],cm=["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"],_n=[...ep,...cm];function dm(e){return ep.includes(e)||e.startsWith("image/")}function Aa(e){return dm(e.type)}async function tp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Aa(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function np(e,t=_n,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function pm(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function op(e,t){let n=pm(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var rp=16e3,um=24e3,fm=4096,gm=1380533830;function mm(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===gm?new Uint8Array(e,44):new Uint8Array(e)}function hm(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var os=class{constructor(t){this.config=t;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 t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)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:rp,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:rp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new cd(um);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=`${hm(o)}/ws/agents/${encodeURIComponent(t)}/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(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(fm,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(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.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(t,n){if(n!==this.callGeneration||!this.playback)return;let o=mm(t);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(t=>t.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(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Io=class{constructor(t={}){this.config=t;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(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,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(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ir(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new os(e.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;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: ${e.type}`)}}function sp(e){if(e?.type==="custom"&&e.custom)return ir({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return ir({type:"runtype",runtype:e.runtype});if(Io.isSupported())return ir({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function tl(e){try{return sp(e),!0}catch{return!1}}function Sa(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var lr=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Sa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.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(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var rs=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"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(t,"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(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function nl(e){if(!e)return"";let t=ym(e);return ap(t!==null?t:e)}function ym(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function ap(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
+ `),t=t.replace(/\n{2,}/g,`
16
+ `),t.trim()}var ip=null;var ol=()=>ip?ip():import("./runtype-tts-entry-UJAEF7NZ.js");var bm=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function vm(e,t){return bm.some(n=>e[n]!==t[n])}function rl(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(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 Xr=t=>({isError:!0,content:[{type:"text",text:t}]}),Gd=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Qd=t=>Go(t)||t===Dn,ha=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 Qr(()=>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&&(Go(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 Kr(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||Vi().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 ji(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=nr.isSupported()?new nr({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 Vi().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=tr(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(!Yg(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 Kr(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"?ua():n==="assistant"?Zo():`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"?ua():r==="assistant"?Zo():`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 ss=e=>({isError:!0,content:[{type:"text",text:e}]}),lp=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,cp=e=>Zo(e)||e===On,Ta=class{constructor(t={},n){this.config=t;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 rs(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Zo(n.name)||n.name===On&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.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"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ns(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||ol().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return tl(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 t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=lr.isSupported()?new lr({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return ol().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.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(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=ir(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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!vm(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new ns(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?xa():n==="assistant"?sr():`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(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){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"?xa():r==="assistant"?sr():`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(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:p}=t,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(t,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(er(s)),d.push(...r.contentParts),d.push(...e.contentParts),e.contentParts=d}else if(p){let d=[];a&&d.push(er(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=ua(),s=Zo();this.activeAssistantMessageId=null;let a=n?.contentParts&&Od(n.contentParts)?fa:"",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=Ki(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=Zo();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=Ki(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:_i(),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,Xr(k?"Aborted by cancel()":Gd(B)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,Xr("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,Xr("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=_i():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,Xr("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,Xr(C||p.aborted?"Aborted by cancel()":Gd(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=To(this.config.features?.artifacts,e.artifactType),r=oa(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=>Ki(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=Zo(),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=qi(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ma(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=qi(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 ya={allowedTypes:Fn,maxFileSize:10*1024*1024,maxFiles:4};function Zg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function em(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 Jr=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??ya.allowedTypes,maxFileSize:e.maxFileSize??ya.maxFileSize,maxFiles:e.maxFiles??ya.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:ya.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=zd(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 $d(n),s=ga(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=ga(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=em(e.file.type),p=re(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=h("span");d.textContent=Ud(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 Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,ba=zt+1;var tm=8,nm=8,Gi=10,Qi=new WeakMap,Xd=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,om=t=>{let e=t.getRootNode?.();return Xd(e)?e:t.ownerDocument.body},Xi=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n));function Dt(t){Qi.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,enabled:r=!0,gap:s=tm,viewportPadding:a=nm}=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(),le=d.getBoundingClientRect(),ge=J.documentElement.clientWidth||D.innerWidth,Ce=J.documentElement.clientHeight||D.innerHeight,we=ge-a-le.width,ee=F.left+F.width/2-le.width/2,ce=Xi(ee,a,we),Y=F.top-a,ie=Ce-a-F.bottom,Z=le.height+s,he=Y>=Z||Y>=ie?"top":"bottom",ye=he==="top"?F.top-s-le.height:F.bottom+s,pe=Ce-a-le.height,Te=Xi(ye,a,pe),Ae=F.left+F.width/2,$e=Math.max(Gi,le.width-Gi),Fe=Xi(Ae-ce,Gi,$e);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=om(e);if(!J||!D)return;let F=l(),le=p();d=F.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(ba),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()};le.addEventListener("scroll",Ce,!0),le.addEventListener("resize",Ce);let we=e.getRootNode(),ee=Xd(we)?we:F.documentElement,ce=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||I()});ce?.observe(ee,{childList:!0,subtree:!0}),u=()=>{le.removeEventListener("scroll",Ce,!0),le.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),Qi.delete(e))}};return Qi.set(e,j),j}function Jd(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),Dt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:Sv,load:rm}=Ko({fallbackImport:()=>import("./context-mentions-ONG7A7M6.js")});var Ji=rm;var{setLoader:Ev,load:sm}=Ko({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var Yd=sm;function Yr(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 Zd(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Yc(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=Ji().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=()=>{Yd().then(M=>{let P=M.mountInlineComposer({textarea:t.textarea,renderToken:K=>Yr(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=Jd({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(!Jc(M))return;let P=d,z=P.selectionStart??0;Xc(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:()=>{Ji().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 ep=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Zr(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];ep(s)&&ep(r)?n[o]=Zr(s,r):n[o]=r}return n}var Nn="min(440px, calc(100vw - 24px))",np="440px",am={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)"},at={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:am,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 tp(t,e){if(!(!t&&!e))return t?e?Zr(t,e):t:e}function va(t){return t?{...at,...t,theme:tp(at.theme,t.theme),darkTheme:tp(at.darkTheme,t.darkTheme),launcher:{...at.launcher,...t.launcher,dock:{...at.launcher?.dock,...t.launcher?.dock},clearChat:{...at.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...at.copy,...t.copy},sendButton:{...at.sendButton,...t.sendButton},statusIndicator:{...at.statusIndicator,...t.statusIndicator},voiceRecognition:{...at.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=at.features?.artifacts,n=t.features?.artifacts,o=at.features?.scrollToBottom,r=t.features?.scrollToBottom,s=at.features?.scrollBehavior,a=t.features?.scrollBehavior,l=at.features?.streamAnimation,p=t.features?.streamAnimation,d=at.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{...at.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??at.suggestionChips,suggestionChipsConfig:{...at.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...at.layout,...t.layout,header:{...at.layout?.header,...t.layout?.header},messages:{...at.layout?.messages,...t.layout?.messages,avatar:{...at.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...at.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...at.layout?.slots,...t.layout?.slots}},markdown:{...at.markdown,...t.markdown,options:{...at.markdown?.options,...t.markdown?.options}},messageActions:{...at.messageActions,...t.messageActions}}:at}var wa="16px",xa="transparent",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"},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"}},lm={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"}},cm={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:np,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:wa,canvasBackground:xa},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 op(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 dm(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 rp(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]=rp(s,r):n[o]=r}return n}function pm(t,e){return e?rp(t,e):t}function or(t,e={}){let n={palette:im,semantic:lm,components:cm},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:pm(n.components,t?.components)};if(e.validate!==!1){let r=dm(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 sp(t){let e=op(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"]??wa,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??xa,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 U=Vt(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"]=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"],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 um={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"}}},ap=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Yi=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",fm=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Yi()},ip=t=>fm(t),gm=t=>or(t),mm=t=>or({...t,palette:{...t?.palette,colors:{...um.colors,...t?.palette?.colors}}},{validate:!1}),rr=t=>{let e=ip(t),n=ap(t?.theme),o=ap(t?.darkTheme);return e==="dark"?mm(Zr(n??{},o??{})):gm(n)},hm=t=>sp(t),es=(t,e)=>{let n=rr(e),o=hm(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",ip(e))},Ca=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Yi())});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(Yi());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 lp(t){let e=Sn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Aa(t){if(typeof t!="string")return"";let e=t.indexOf(`
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 ts(t){let e=lp(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(ts(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=lp(t.path);return e?e.toUpperCase():"File"}}}function cp(t){let e=t.markdown??"";return t.file?{filename:Sn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Aa(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}var Zi="http://www.w3.org/2000/svg";function dp(t){let e=document.createElementNS(Zi,"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(Zi,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Zi,"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 pp(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 el="persona-artifact-status-label",up="persona-artifact-status-detail",fp="data-artifact-status-label",tl=new Map,gp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function sr(t){t&&tl.delete(t)}function ym(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?oo(e):t.artifactType==="component"?"Component":"Document"}function ar(t,e,n){let o=ym(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=tl.get(a);t.status!=="complete"&&l===void 0&&(l=gp(),tl.set(a,l));let p=l===void 0?0:Math.max(0,gp()-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 bm(t){t.className=el,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 Lo(t,e,n){let o=t.querySelector(`:scope > .${el}`);o||(o=h("span",el),t.appendChild(o)),o.getAttribute(fp)!==e.label&&(bm(o),pp(o,e.label,n),o.setAttribute(fp,e.label));let r=t.querySelector(`:scope > .${up}`),s=e.detail;s?(r||(r=h("span",up),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var vm={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"},wm=15e4,Sa={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 xm(t,e){let n=(t||"").trim().toLowerCase();if(n&&Sa[n])return Sa[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Sa[r])return Sa[r]}}return null}function Ta(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 Cm=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"]),Am=[{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=>Cm.has(t)?"keyword":"plain"}];function mp(t){return Ta(t,Am)}var Sm=[{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 Tm(t){let e=Ta(t,Sm);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 Mm=[{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 hp(t){let e=Ta(t,Mm),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 Em=[{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 km(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 Ta(p,Em))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"?mp(v):hp(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 Lm(t,e){switch(e){case"html":return km(t);case"css":return hp(t);case"js":return mp(t);case"json":return Tm(t)}}function Pm(t){let e=Gc(),n=h("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=vm[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
- `);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
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 yp(t,e,n){let o=t.length<=wm?xm(e,n):null,r=o?Lm(t,o):[{type:"plain",value:t}];return Pm(r)}function ir(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(ba)):(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 It(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 Po(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 Ma(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=It({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 bp(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=ir({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 Ea="persona-artifact-custom-action-btn";function lr(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 "+Ea+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Ea+(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=Po({icon:t.icon,label:t.label,className:Ea+(n?" persona-artifact-doc-copy-btn":"")}):o=It({icon:t.icon,label:t.label,className:Ea+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function ns(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 vp(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=ar(C,v,"card");Lo(f,I,v)}else s&&sr(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=lr(B);k.setAttribute("data-artifact-custom-action",B.id),k.className=`${k.className} persona-flex-shrink-0`,d.append(k)}}catch{}}let C=Po({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var ka=(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:()=>vp(t,e)});if(l)return l}return vp(t,e)};var so=new WeakMap;function nl(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 Sp(t){return so.has(t)}function Im(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 wp(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 Rm(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 xp=180,Wm=240,Hm=.8,Bm=300,Dm=500,Fm="cubic-bezier(0.2, 0, 0, 1)",Cp=240,Nm=.35;function Om(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:xp,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(Dm,Math.max(Bm,Wm+d*Hm))),u=Math.round(c*Nm),w=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:Cp,delay:u,easing:"ease-out",fill:"backwards"}):null,v=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:c,easing:Fm});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+Cp)+120)},xp)}function _m(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 os="--persona-artifact-inline-body-height";function $m(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 Ap(t,e){let n=Im(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=_m(o),p=o?.inlineActions??[],d=$m(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=>ka(Rm(Y),e),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(os),f.replaceChildren(v(Y)),so.set(f,ie=>{f.replaceChildren(v(ie))})};if(c&&n.status==="complete")return C(n),f;let I=La(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 ie=Y.status!=="complete",Z=ie?d.streamingHeight:d.completeHeight,he=typeof Z=="number";he?f.style.setProperty(os,`${Z}px`):f.style.removeProperty(os);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",!ie&&!pe&&typeof d.completeHeight=="number")},M=n.status,P=(Y,ie)=>{M!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(os,`${d.completeHeight}px`):f.style.removeProperty(os),Mp(B,ie?.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 ${wp(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"),le=h("span","persona-flex persona-items-center persona-gap-1"),ge=()=>u??d.viewMode,Ce=l?Ma({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 ie=Y==="source"?"source":"rendered";ie!==ge()&&(u=ie,I.update(w),k(w))}}):null,we=s?It({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?It({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(le),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:ie,typeLabel:Z}=wp(Y);J.textContent=ie,J.title=ie,z&&B.setAttribute("aria-label",`Open ${ie} 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=ar(Y,o,"inline-chrome");Lo(D,ye,o)}else sr(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=ts(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(le.replaceChildren(),!he&&p.length>0){let ye=ns(Y);if(ye)for(let pe of p)try{if(pe.visible===void 0||pe.visible(ye)){let Te=lr(pe,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",pe.id),Te.classList.add("persona-flex-shrink-0"),le.appendChild(Te)}}catch{}}};return ce(n),so.set(f,(Y,ie)=>{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),Om(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,ie),ce(Y)}),f}var Tp=(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:()=>Ap(t,e)});if(l)return l}return Ap(t,e)};var ol=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 ol;On.register("PersonaArtifactCard",ka,{bubbleChrome:!1});On.register("PersonaArtifactInline",Tp,{bubbleChrome:!1});function rs(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Aa(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var rl=!1;function zm(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Mp(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"||rl||s){o();return}rl=!0;let a=zm(n);t.style.setProperty("view-transition-name",a);let l=()=>{rl=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Um="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",jm="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function qm(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 Vm(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 Km=220;function Gm(){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 Qm(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 Xm(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(dp());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 Jm(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=Xm(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,Km))},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 La(t,e){let{config:n}=e,o=e.registry??On,r=e.bodyLayout,s=n.markdown?Zs(n.markdown):null,a=ea(n.sanitize),l=t,p=!1,d=ee=>{let ce=Hn()!==null;s&&!ce&&!p&&(p=!0,Ys(()=>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)}))},le=(ee,ce,Y,ie)=>{let Z=!!r,he=Y.id+"|"+(Z?"w":"p");if(!C||B!==he||C.parentElement!==c){v(),K(),c.replaceChildren();let Te=h("pre",Um+" persona-code-pre"),Ae=h("code","persona-code");if(Te.appendChild(Ae),Z){let $e=h("div","persona-artifact-source-window");if($e.appendChild(Te),c.appendChild($e),!(r?.overflow==="clip")&&typeof $e.addEventListener=="function"){let ot=()=>$e.scrollHeight-$e.clientHeight>1;$e.addEventListener("scroll",()=>{J($e)&&(k=!1),D($e)},{passive:!0}),$e.addEventListener("wheel",Qe=>{ot()&&Qe.deltaY<0&&(k=!0)},{passive:!0}),$e.addEventListener("touchmove",()=>{ot()&&(k=!0)},{passive:!0})}C=$e}else c.appendChild(Te),C=Te;I=Ae,B=he}let ye=Z?C:null;ye&&(ye.classList.toggle("persona-artifact-source-window--fixed",ie),ye.classList.toggle("persona-artifact-source-window--clip",ie&&r?.overflow==="clip"));let pe=ye?J(ye):!0;if(I.replaceChildren(yp(ee,ce?.language,ce?.path)),ye){let Te=Y.status!=="complete";ie&&Te&&r?.followOutput&&!k&&pe?F(ye):Te||(k=!1),D(ye)}},ge=ee=>{v(),M(),K(),c.replaceChildren();let ce=h("div",jm);ce.innerHTML=d(ee),c.appendChild(ce)},Ce=ee=>{let ce=ee.id,Y=n.features?.artifacts,ie=ar(ee,Y,"status-body");if(P&&z===ce&&P.parentElement===c){let ye=P.querySelector(".persona-artifact-status-view-text");ye&&Lo(ye,ie,Y);return}v(),M(),c.replaceChildren();let Z=h("div","persona-artifact-status-view"),he=h("div","persona-artifact-status-view-text");Lo(he,ie,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,ie=ee.status!=="complete";ie||sr(ee.id);let Z=ie?r?.streamingHeight:r?.completeHeight,he=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&ie){Ce(ee);return}if(Y){let pe=Aa(ee.markdown??""),Te=ts(Y),Ae=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ie&&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,Qe=ot?.iframeSandbox??"allow-scripts";!ot?.dangerouslyAllowSameOrigin&&Qe.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."),Qe=Qe.split(/\s+/).filter(St=>St&&St!=="allow-same-origin").join(" "));let He=Vm(ot?.loading),Ee=h("div","persona-artifact-frame"),Xe=h("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",Qe),Xe.setAttribute("data-artifact-id",ee.id);let on=null;He.enabled&&He.injectReadySignal?(on=Gm(),Xe.srcdoc=pe+Qm(on)):Xe.srcdoc=pe,Ee.appendChild(Xe),c.appendChild(Ee),He.enabled&&(f=Jm(Ee,Xe,on,He,ee.id,n)),u=Ee,w=Fe;return}if(v(),!ie&&Te==="markdown"&&ce==="rendered"){ge(pe);return}le(pe,{language:Y.language,path:Y.path},ee,he);return}if(ee.artifactType==="markdown"){if(ce==="source"){v(),le(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(qm(ee))};return we(t),{el:c,update(ee){we(ee)}}}import{Idiomorph as Ym}from"idiomorph";var Pa=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Ym.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 Ep=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var sl={index:-1,draft:""};function kp(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 Lp(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 Pp(){return new Map}function Ip(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function Rp(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function Wp(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Hp(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function Ia(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 Ra(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 Wa(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 Bp(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Dp(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 Fp(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var ss={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Zm=["pre","code","a","script","style"],Ha=t=>({type:t?.type??ss.type,placeholder:t?.placeholder??ss.placeholder,speed:t?.speed??ss.speed,duration:t?.duration??ss.duration,buffer:t?.buffer??ss.buffer}),eh=[{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"}],Op=new Map;for(let t of eh)Op.set(t.name,t);var cr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Op.get(t)??null,Ba=(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},th=(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},nh=(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},al=/\s/,oh=(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},rh=(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(al.test(s[l])){let p=l;for(;p<s.length&&al.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&&!al.test(s[d]);)p.appendChild(th(o,s[d],e,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,t)},sh=(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(nh(o,p,e,n.value)),n.value+=1));r.replaceChild(a,t)},as=(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??Zm).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)oh(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=e==="char"?rh:sh;for(let u of l)c(u,n,d);return r.innerHTML},Da=(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},is=(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},Np=new WeakMap,ah=(t,e)=>{if(!t.styles)return;let n=Np.get(e);if(n||(n=new Set,Np.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)},il=new WeakMap,ih=(t,e)=>{if(!t.onAttach)return;let n=il.get(e);if(n||(n=new Map,il.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},_p=t=>{let e=il.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Fa=(t,e)=>{ah(t,e),ih(t,e)};function ll(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 ls=0,io=null;function cl(t=document){if(ls++,ls===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,ls=Math.max(0,ls-1),ls===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 cs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Wt=t=>(t?.launcher?.mountMode??"floating")==="docked",ds=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",pn=t=>{let e=t?.launcher?.dock;return{side:e?.side??cs.side,width:e?.width??cs.width,animate:e?.animate??cs.animate,reveal:e?.reveal??cs.reveal,maxHeight:e?.maxHeight??cs.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 lh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Na=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=lh,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||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=re(u,s,"currentColor",1);return C?(C.style.display="block",v.appendChild(C)):v.textContent=w,p.appendChild(v),Dt({anchor:v,trigger:p,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:p}},ch="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Oa=(t,e={})=>{let{wrapperClassName:n=ch,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||Kt.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),Dt({anchor:P,trigger:k,text:()=>P.getAttribute("aria-label")??I,enabled:B}),{button:P,wrapper:k}};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))"},Io=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:Kt.titleColor}}),w=Ne("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",I=null,B=null;if(v){let K=Oa(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}=Na(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}},ps=(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 dh=t=>{let e=Io({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 ph(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=ir({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 uh=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=bp({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=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=Kt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),ph(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||Kt.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}},$p={default:dh,minimal:uh},fh=t=>$p[t]??$p.default,_a=(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=fh(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 $a=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}},za=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),Dt({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}}},Ua=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 Dt({anchor:f,trigger:w,text:()=>f.getAttribute("aria-label")??I,enabled:B}),{button:f,wrapper:w}},ja=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 Dt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},qa=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},Va=()=>Ne("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ka=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=Va(),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}=$a(e);a();let l=za(e),p=Ua(e),d=ja(e),c=qa(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 zp=()=>{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}},Up=t=>{let{config:e}=t,n=Ne("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Va(),r=qa(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=$a(e);s.style.maxHeight="100px",a();let l=za(e),p=Ua(e),d=ja(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 jp=t=>{let e=t?.launcher?.enabled??!0,n=Wt(t);if(ds(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??zt);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??zt),{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??zt);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}},gh=(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}=Na(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=Oa(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=Up({config:t}),{root:k,textNode:M}=zp();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}},qp=(t,e=!0)=>{if(ds(t))return gh(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?_a(t,o,{showClose:e}):Io({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:Wt(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=Ka({config:t}),v=t?.layout?.showFooter!==!1;r?ps(n,s,t):(s.header.style.display="none",ps(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 dl=(t,e)=>{let n=h("button");n.type="button",n.innerHTML=`
22
+ `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];s&&d.push(ar(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(ar(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.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=xa(),s=sr();this.activeAssistantMessageId=null;let a=n?.contentParts&&Zd(n.contentParts)?Ca:"",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=rl(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 t=sr();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:t},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=rl(r,this.config.errorMessage);if(a){let l={id:t,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(t,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(t,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 t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},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(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,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:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.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-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(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(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.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=t.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(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.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(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});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(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==On?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,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=`${t}:${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===On)return{dedupeKey:u,resumeKey:f,output:Ji(),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),R;if(!C)R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{R=await C}catch(B){let L=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return L||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(p,ss(L?"Aborted by cancel()":lp(B)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,ss("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:R,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(t,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===On?{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,ss("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(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.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(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===On,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",f=a;try{let v;if(d?v=Ji():u?v=await u:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,ss("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,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(t,ss(C||p.aborted?"Aborted by cancel()":lp(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(t,n,o,r){let s=await this.client.resumeFlow(t,{[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 t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=ro(this.config.features?.artifacts,t),r=Qr(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=ro(this.config.features?.artifacts,n),s=Qr(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,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(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>rl(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=sr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];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 t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){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(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.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=nl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Sa(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=nl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),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&&cp(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&&cp(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(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].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:_n,maxFileSize:10*1024*1024,maxFiles:4};function wm(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xm(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var as=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ma.allowedTypes,maxFileSize:t.maxFileSize??Ma.maxFileSize,maxFiles:t.maxFiles??Ma.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ma.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=np(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 tp(n),s=Aa(n)?URL.createObjectURL(n):null,a={id:wm(),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(t){let n=this.attachments.findIndex(s=>s.id===t);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="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Aa(t.file),o=h("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=h("img");a.src=t.previewUrl,a.alt=t.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=xm(t.file.type),p=ie(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=h("span");d.textContent=op(t.file.type,t.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=ie("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(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Lt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,Ea=Vt+1;var Cm=8,Am=8,sl=10,al=new WeakMap,dp=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Sm=e=>{let t=e.getRootNode?.();return dp(t)?t:e.ownerDocument.body},il=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ot(e){al.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=Cm,viewportPadding:a=Am}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,u=null,w=!1,f=!1,v=!1,C=()=>(typeof o=="function"?o():o).trim(),R=()=>{u?.(),u=null,d?.remove(),d=null,c=null},B=()=>{if(!d)return;let oe=l(),F=p(),$=t.getBoundingClientRect(),X=d.getBoundingClientRect(),me=oe.documentElement.clientWidth||F.innerWidth,he=oe.documentElement.clientHeight||F.innerHeight,Ae=me-a-X.width,Z=$.left+$.width/2-X.width/2,ce=il(Z,a,Ae),ee=$.top-a,le=he-a-$.bottom,Y=X.height+s,pe=ee>=Y||ee>=le?"top":"bottom",xe=pe==="top"?$.top-s-X.height:$.bottom+s,ye=he-a-X.height,ve=il(xe,a,ye),je=$.left+$.width/2,Me=Math.max(sl,X.width-sl),De=il(je-ce,sl,Me);d.dataset.placement=pe,d.style.left=`${ce}px`,d.style.top=`${ve}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${De}px`)},L=()=>{if(v||!r||d||!t.isConnected)return;let oe=C(),F=Sm(t);if(!oe||!F)return;let $=l(),X=p();d=$.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Ea),c=$.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=oe,d.appendChild(c);let me=$.createElement("span");me.className="persona-control-tooltip__arrow",d.appendChild(me),F.appendChild(d),B(),d.dataset.state="open";let he=()=>{if(!t.isConnected){R();return}c&&(c.textContent=C()),B()};X.addEventListener("scroll",he,!0),X.addEventListener("resize",he);let Ae=t.getRootNode(),Z=dp(Ae)?Ae:$.documentElement,ce=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||R()});ce?.observe(Z,{childList:!0,subtree:!0}),u=()=>{X.removeEventListener("scroll",he,!0),X.removeEventListener("resize",he),ce?.disconnect()}},E=()=>{w||f?L():R()},M=()=>{let oe=p();(!oe.matchMedia||!oe.matchMedia("(hover: none)").matches)&&(w=!0,E())},_=()=>{w=!1,E()},G=()=>{f=!0,E()},x=()=>{f=!1,E()},j=oe=>{oe.key==="Escape"&&(w=!1,f=!1,R())};n.addEventListener("mouseenter",M),n.addEventListener("mouseleave",_),t.addEventListener("focus",G),t.addEventListener("blur",x),t.addEventListener("keydown",j);let U={get isOpen(){return d!==null},show:L,hide:R,reposition:B,destroy:()=>{v||(v=!0,R(),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",G),t.removeEventListener("blur",x),t.removeEventListener("keydown",j),al.delete(t))}};return al.set(t,U),U}function pp(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=h("div","persona-send-button-wrapper"),d=Be("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=ie(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Ot({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:nw,load:Tm}=Yo({fallbackImport:()=>import("./context-mentions-ONG7A7M6.js")});var ll=Tm;var{setLoader:sw,load:Mm}=Yo({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var up=Mm;function is(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Be("span",{className:Dn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ie(e.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(Be("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function fp(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=ud(t).filter(E=>E.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(E=>E.sources.some(M=>typeof M.matchCommand=="function")),r=E=>o.some(M=>M.trigger?M.position==="line-start"?E.split(`
23
+ `).some(G=>G.startsWith(M.trigger)):(M.position==="anywhere"?E:E.split(`
24
+ `)[0]).startsWith(M.trigger):!1),s=(E,M)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${E}`,{detail:M}))}catch{}},a=Be("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,u=null,w=null,f=null,v=()=>{if(l)return Promise.resolve(l);if(p)return p;let E=ll().then(M=>(l=M.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:L,emit:s}),l)).catch(M=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",M),p===E&&(p=null),null));return p=E,E},C=()=>{up().then(E=>{let M=E.mountInlineComposer({textarea:e.textarea,renderToken:G=>is(G,{render:t.renderMentionToken}),onMentionRemoved:G=>l?.untrackMention(G)});c=M.input,u=M.destroy;let _=d;_.replaceWith(M.element),d=M.element,f={next:M.element,prev:_},w?.(M.element,_),l?l.rebindComposer(M.input):p&&p.then(G=>G?.rebindComposer(M.input))}).catch(E=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",E)})};t.display==="inline"&&C();let R=[],B=new Map;for(let E of n){if(!E.showButton)continue;let M=pp({config:{...t,buttonIconName:E.buttonIconName,buttonTooltipText:E.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{v().then(_=>_?.openMenu(E.trigger))}});R.push(M),B.set(E.trigger,M.button)}let L=(E,M,_)=>{let G=B.get(M);G&&(G.setAttribute("aria-expanded",E?"true":"false"),E?G.setAttribute("aria-controls",_):G.removeAttribute("aria-controls"))};return{affordanceButtons:R.map(E=>E.wrapper),contextRow:a,handleInput:E=>{if(l){l.handleInput();return}if(!pd(E))return;let M=d,_=M.selectionStart??0;dd(M.value,_,n)&&v().then(G=>G?.handleInput())},handleKeydown:E=>{if(l?.isMenuOpen())return l.handleKeydown(E);if(E.key==="Backspace"&&l?.hasMentions()&&!f){let M=d,_=M.selectionStart===0&&M.selectionEnd===0;if((M.value.length===0||_)&&l.removeLastChip())return E.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async E=>r(E)?(l??await v())?.dispatchInlineCommand(E)??null:null,clear:()=>l?.clear(),prefetch:()=>{ll().catch(()=>{})},onComposerSwap:E=>{w=E,f&&E(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let E of R)E.wrapper.remove();a.remove()}}}var gp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ls(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];gp(s)&&gp(r)?n[o]=ls(s,r):n[o]=r}return n}var $n="min(440px, calc(100vw - 24px))",hp="440px",Em={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:$n,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)"},at={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:Em,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 mp(e,t){if(!(!e&&!t))return e?t?ls(e,t):e:t}function ka(e){return e?{...at,...e,theme:mp(at.theme,e.theme),darkTheme:mp(at.darkTheme,e.darkTheme),launcher:{...at.launcher,...e.launcher,dock:{...at.launcher?.dock,...e.launcher?.dock},clearChat:{...at.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...at.copy,...e.copy},sendButton:{...at.sendButton,...e.sendButton},statusIndicator:{...at.statusIndicator,...e.statusIndicator},voiceRecognition:{...at.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=at.features?.artifacts,n=e.features?.artifacts,o=at.features?.scrollToBottom,r=e.features?.scrollToBottom,s=at.features?.scrollBehavior,a=e.features?.scrollBehavior,l=at.features?.streamAnimation,p=e.features?.streamAnimation,d=at.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.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{...at.features,...e.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:e.suggestionChips??at.suggestionChips,suggestionChipsConfig:{...at.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...at.layout,...e.layout,header:{...at.layout?.header,...e.layout?.header},messages:{...at.layout?.messages,...e.layout?.messages,avatar:{...at.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...at.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...at.layout?.slots,...e.layout?.slots}},markdown:{...at.markdown,...e.markdown,options:{...at.markdown?.options,...e.markdown?.options}},messageActions:{...at.messageActions,...e.messageActions}}:at}var La="16px",Pa="transparent",km={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"}},Lm={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"}},Pm={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"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:$n,maxWidth:hp,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:La,canvasBackground:Pa},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:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},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 Gt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;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."))?Gt(e,o):o}function yp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Gt(e,a);p!==void 0&&(t[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(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Im(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function bp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=bp(s,r):n[o]=r}return n}function Rm(e,t){return t?bp(e,t):e}function cr(e,t={}){let n={palette:km,semantic:Lm,components:Pm},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:Rm(n.components,e?.components)};if(t.validate!==!1){let r=Im(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function vp(e){let t=yp(e),n={};for(let[x,j]of Object.entries(t)){let U=x.replace(/\./g,"-");n[`--persona-${U}`]=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"]??La,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Pa,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=e.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=e.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"]=Gt(e,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=Gt(e,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"]=Gt(e,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"]=Gt(e,x.chromeBackground)??x.chromeBackground),x.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Gt(e,x.chromeBorder)??x.chromeBorder),x.titleColor&&(n["--persona-artifact-inline-title-color"]=Gt(e,x.titleColor)??x.titleColor),x.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Gt(e,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"]=Gt(e,v.background)??v.background));let C=n["--persona-surface"],R=n["--persona-container"],B=n["--persona-palette-colors-gray-100"]??"#f3f4f6",L=n["--persona-palette-colors-gray-200"]??"#e5e7eb",E=n["--persona-palette-colors-gray-300"]??"#d1d5db",M=!R||R===C,_=M?B:R,G=M?L:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??_,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??G,M&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??E),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??_,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??_,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??_,n}var Wm={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"}}},wp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},cl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Hm=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":cl()},xp=e=>Hm(e),Bm=e=>cr(e),Dm=e=>cr({...e,palette:{...e?.palette,colors:{...Wm.colors,...e?.palette?.colors}}},{validate:!1}),dr=e=>{let t=xp(e),n=wp(e?.theme),o=wp(e?.darkTheme);return t==="dark"?Dm(ls(n??{},o??{})):Bm(n)},Fm=e=>vp(e),cs=(e,t)=>{let n=dr(t),o=Fm(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",xp(t))},Ia=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(cl())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(cl());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Mn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Cp(e){let t=Mn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ra(e){if(typeof e!="string")return"";let t=e.indexOf(`
25
+ `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
26
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function ds(e){let t=Cp(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function lo(e){switch(ds(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Cp(e.path);return t?t.toUpperCase():"File"}}}function Ap(e){let t=e.markdown??"";return e.file?{filename:Mn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Ra(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var dl="http://www.w3.org/2000/svg";function Sp(e){let t=document.createElementNS(dl,"svg");t.setAttribute("class",Dn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(dl,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(dl,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var co=(e,t,n)=>{let o=n;for(let r of t){let s=h("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Tp(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),co(e,t,0)}var pl="persona-artifact-status-label",Mp="persona-artifact-status-detail",Ep="data-artifact-status-label",ul=new Map,kp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function pr(e){e&&ul.delete(e)}function Nm(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?lo(t):e.artifactType==="component"?"Component":"Document"}function ur(e,t,n){let o=Nm(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,l=ul.get(a);e.status!=="complete"&&l===void 0&&(l=kp(),ul.set(a,l));let p=l===void 0?0:Math.max(0,kp()-l),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,w=d||c===""?0:c.split(`
27
+ `).length,f=e.artifactType==="markdown"?e.file:void 0,v={artifactId:a,artifactType:e.artifactType,title:e.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 Om(e){e.className=pl,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Ro(e,t,n){let o=e.querySelector(`:scope > .${pl}`);o||(o=h("span",pl),e.appendChild(o)),o.getAttribute(Ep)!==t.label&&(Om(o),Tp(o,t.label,n),o.setAttribute(Ep,t.label));let r=e.querySelector(`:scope > .${Mp}`),s=t.detail;s?(r||(r=h("span",Mp),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var _m={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"},$m=15e4,Wa={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 zm(e,t){let n=(e||"").trim().toLowerCase();if(n&&Wa[n])return Wa[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Wa[r])return Wa[r]}}return null}function Ha(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let l of t){l.re.lastIndex=o;let p=l.re.exec(e);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(e.length),n}var jm=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"]),Um=[{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:e=>jm.has(e)?"keyword":"plain"}];function Lp(e){return Ha(e,Um)}var Vm=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function qm(e){let t=Ha(e,Vm);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var Km=[{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 Pp(e){let t=Ha(e,Km),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let l=t[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 t}var Gm=[{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 Qm(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),l=a===-1?o:a+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),l=a===-1?o:a+1,p=e.slice(r,l);for(let c of Ha(p,Gm))t.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(e.slice(r)),f=w?r+w.index:o,v=e.slice(r,f),C=c==="script"?Lp(v):Pp(v);for(let R of C)t.push(R);r=f}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function Xm(e,t){switch(t){case"html":return Qm(e);case"css":return Pp(e);case"js":return Lp(e);case"json":return qm(e)}}function Jm(e){let t=ld(),n=h("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=_m[r];if(a){let l=h("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
28
+ `);for(let a=0;a<s.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
29
+ `)),n=h("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Ip(e,t,n){let o=e.length<=$m?zm(t,n):null,r=o?Xm(e,o):[{type:"plain",value:e}];return Jm(r)}function fr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,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(Ea)):(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 t){if(f.dividerBefore){let R=document.createElement("hr");a.appendChild(R)}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 R=ie(f.icon,16,"currentColor",1.5);R&&v.appendChild(R)}let C=document.createElement("span");C.textContent=f.label,v.appendChild(C),v.addEventListener("click",R=>{R.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 Pt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=e,p=h("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ie(t,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(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=e,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),t){let w=ie(t,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 Ba(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,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 t){let u;c.icon?u=Pt({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 Rp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=e,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",t);let c=h("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ie(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=fr({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 Da="persona-artifact-custom-action-btn";function gr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Da+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Da+(n?" persona-artifact-doc-icon-btn":"");o=h("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=h("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Wo({icon:e.icon,label:e.label,className:Da+(n?" persona-artifact-doc-copy-btn":"")}):o=Pt({icon:e.icon,label:e.label,className:Da+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function ps(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Wp(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Mn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?lo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.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",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 w=document.createElement("div");w.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let v=document.createElement("div");if(v.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",v.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,R={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},B=ur(R,C,"card");Ro(v,B,C)}else s&&pr(s),v.textContent=d;if(w.append(f,v),c.append(u,w),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let B={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let L of C)try{if(L.visible===void 0||L.visible(B)){let E=gr(L);E.setAttribute("data-artifact-custom-action",L.id),E.className=`${E.className} persona-flex-shrink-0`,c.append(E)}}catch{}}let R=Wo({label:"Download",className:"persona-flex-shrink-0"});R.title=`Download ${r}`,R.setAttribute("data-download-artifact",s),c.append(R)}return c}var Fa=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Wp(e,t)});if(l)return l}return Wp(e,t)};var po=new WeakMap;function fl(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=po.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Np(e){return po.has(e)}function Ym(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Hp(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Mn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Zm(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Bp=180,eh=240,th=.8,nh=300,oh=500,rh="cubic-bezier(0.2, 0, 0, 1)",Dp=240,sh=.35;function ah(e,t,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(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Bp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of a)B.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(oh,Math.max(nh,eh+d*th))),u=Math.round(c*sh),w=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:Dp,delay:u,easing:"ease-out",fill:"backwards"}):null,v=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:rh});e.style.height=`${p}px`;let C=!1,R=()=>{C||(C=!0,l(),r())};Promise.allSettled([v.finished,f?.finished].filter(Boolean)).then(R),window.setTimeout(R,Math.max(c,u+Dp)+120)},Bp)}function ih(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var us="--persona-artifact-inline-body-height";function lh(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.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=t?.transition==="none"?"none":"auto",f=t?.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(e,t){let n=Ym(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=ih(o),p=o?.inlineActions??[],d=lh(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=ee=>Fa(Zm(ee),t),C=ee=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(us),f.replaceChildren(v(ee)),po.set(f,le=>{f.replaceChildren(v(le))})};if(c&&n.status==="complete")return C(n),f;let R=Na(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),B=h("div","persona-artifact-inline-body");B.appendChild(R.el);let L=ee=>{let le=ee.status!=="complete",Y=le?d.streamingHeight:d.completeHeight,pe=typeof Y=="number";pe?f.style.setProperty(us,`${Y}px`):f.style.removeProperty(us);let xe=!!R.el.querySelector(".persona-code-pre"),ye=!!R.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",xe),B.classList.toggle("persona-artifact-inline-body--sized",pe&&ye),B.classList.toggle("persona-artifact-inline-body--cap",!le&&!ye&&typeof d.completeHeight=="number")},E=n.status,M=(ee,le)=>{E!=="complete"&&ee.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(us,`${d.completeHeight}px`):f.style.removeProperty(us),_p(B,le?.suppressTransition?"none":d.transition,ee.id,()=>{R.update(ee),L(ee)})):R.update(ee),L(ee),E=ee.status};L(n);let _=d.overflow==="clip"&&a&&!!n.id;if(_&&(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),po.set(f,M),f;let G=h("div","persona-artifact-inline-chrome");G.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let x=h("div","persona-artifact-inline-chrome-lead"),j=h("span","persona-flex persona-items-center persona-flex-shrink-0"),U=ie("file-text",16,"currentColor",2);U&&j.appendChild(U);let oe=h("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),F=h("span","persona-artifact-inline-type");x.append(j,oe,F);let $=h("div","persona-artifact-inline-chrome-actions"),X=h("span","persona-flex persona-items-center persona-gap-1"),me=()=>u??d.viewMode,he=l?Ba({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:me(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ee=>{let le=ee==="source"?"source":"rendered";le!==me()&&(u=le,R.update(w),L(w))}}):null,Ae=s?Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Ae&&n.id&&Ae.setAttribute("data-copy-artifact",n.id);let Z=a?Pt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Z&&n.id&&Z.setAttribute("data-expand-artifact-inline",n.id),$.appendChild(X),he&&$.appendChild(he.element),Ae&&$.appendChild(Ae),Z&&$.appendChild(Z),G.append(x,$),f.append(G,B);let ce=ee=>{let{title:le,typeLabel:Y}=Hp(ee);oe.textContent=le,oe.title=le,_&&B.setAttribute("aria-label",`Open ${le} in panel`);let pe=ee.status!=="complete";if(pe){F.classList.contains("persona-artifact-inline-status")||(F.className="persona-artifact-inline-status",F.removeAttribute("data-preserve-animation"),F.replaceChildren());let xe=ur(ee,o,"inline-chrome");Ro(F,xe,o)}else pr(ee.id),F.className="persona-artifact-inline-type",F.removeAttribute("data-preserve-animation"),F.replaceChildren(),F.textContent=Y;if(Ae&&Ae.classList.toggle("persona-hidden",pe),he){let xe=ee.artifactType==="markdown"?ee.file:void 0,ye=!1;if(!pe&&xe&&d.viewMode!=="source"){let ve=ds(xe);ve==="markdown"?ye=!0:(ve==="html"||ve==="svg")&&(ye=o?.filePreview?.enabled!==!1)}he.element.classList.toggle("persona-hidden",!ye),he.setSelected(me())}if(X.replaceChildren(),!pe&&p.length>0){let xe=ps(ee);if(xe)for(let ye of p)try{if(ye.visible===void 0||ye.visible(xe)){let ve=gr(ye,{documentChrome:!0});ve.setAttribute("data-artifact-custom-action",ye.id),ve.classList.add("persona-flex-shrink-0"),X.appendChild(ve)}}catch{}}};return ce(n),po.set(f,(ee,le)=>{if(c&&E!=="complete"&&ee.status==="complete"){let Y=f.isConnected?f.getBoundingClientRect().height:0;E="complete";let pe=ee,xe=!1,ye=ve=>{pe=ve,xe=!0};po.set(f,ye),ah(f,Y,{swap:()=>{C(pe),xe=!1,po.set(f,ye)},onSettled:()=>{xe?C(pe):po.set(f,ve=>{f.replaceChildren(v(ve))})}});return}(ee.status!=="complete"||ee.id!==w.id)&&(u=null),w=ee,M(ee,le),ce(ee)}),f}var Op=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Fp(e,t)});if(l)return l}return Fp(e,t)};var gl=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},zn=new gl;zn.register("PersonaArtifactCard",Fa,{bubbleChrome:!1});zn.register("PersonaArtifactInline",Op,{bubbleChrome:!1});function fs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ra(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var ml=!1;function ch(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function _p(e,t,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(t!=="auto"||!e||typeof r!="function"||ml||s){o();return}ml=!0;let a=ch(n);e.style.setProperty("view-transition-name",a);let l=()=>{ml=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var dh="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",ph="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function uh(e){let t=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=e.component?`Component: ${e.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(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function fh(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var gh=220;function mh(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function hh(e){return`
30
+ <script>(function(){var d=false;var t=`+JSON.stringify(e)+";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 yh(e,t,n){let o=h("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=h("div","persona-artifact-frame-loading-indicator");r.appendChild(Sp());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 bh(e,t,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(E=>clearTimeout(E)),d.clear()},u=(E,M)=>{let _=setTimeout(()=>{d.delete(_),E()},M);d.add(_)},w=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let E=yh(r,s,o);a=E.el,e.appendChild(a),l=Date.now(),o.label!==!1&&u(E.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,gh))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):t.removeEventListener("load",L)},R=()=>{if(p||(p=!0,C(),c(),!a))return;let E=Math.max(0,o.minVisibleMs-(Date.now()-l));E>0?u(v,E):v()};function B(E){if(n===null)return;let M=E.data;!M||M.persona!=="artifact-preview-ready"||M.token!==n||E.source===t.contentWindow&&R()}function L(){let E=M=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>M()):setTimeout(M,0)};E(()=>E(()=>R()))}return u(f,o.delayMs),u(R,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):t.addEventListener("load",L),()=>{p=!0,c(),C(),w()}}function Na(e,t){let{config:n}=t,o=t.registry??zn,r=t.bodyLayout,s=n.markdown?ca(n.markdown):null,a=da(n.sanitize),l=e,p=!1,d=Z=>{let ce=Fn()!==null;s&&!ce&&!p&&(p=!0,la(()=>Ae(l)));let ee=s?s(Z):oo(Z);return s&&ce&&a?a(ee):ee},c=h("div","persona-artifact-preview-body"),u=null,w=null,f=null,v=()=>{f&&(f(),f=null),u=null,w=null},C=null,R=null,B=null,L=!1,E=()=>{C=null,R=null,B=null,L=!1},M=null,_=null,G=()=>{M=null,_=null},x=40,j=0,U=Z=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Z()):setTimeout(Z,0),oe=Z=>Z.scrollHeight-Z.clientHeight-Z.scrollTop<=x,F=Z=>{if(!r)return;let ce=Z.scrollHeight-Z.clientHeight>1,ee=Z.scrollHeight-Z.clientHeight-Z.scrollTop;Z.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ce&&Z.scrollTop>1),Z.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ce&&ee>1)},$=Z=>{j||(j=U(()=>{j=0,Z.scrollTop=Z.scrollHeight,F(Z)}))},X=(Z,ce,ee,le)=>{let Y=!!r,pe=ee.id+"|"+(Y?"w":"p");if(!C||B!==pe||C.parentElement!==c){v(),G(),c.replaceChildren();let ve=h("pre",dh+" persona-code-pre"),je=h("code","persona-code");if(ve.appendChild(je),Y){let Me=h("div","persona-artifact-source-window");if(Me.appendChild(ve),c.appendChild(Me),!(r?.overflow==="clip")&&typeof Me.addEventListener=="function"){let Qe=()=>Me.scrollHeight-Me.clientHeight>1;Me.addEventListener("scroll",()=>{oe(Me)&&(L=!1),F(Me)},{passive:!0}),Me.addEventListener("wheel",Ve=>{Qe()&&Ve.deltaY<0&&(L=!0)},{passive:!0}),Me.addEventListener("touchmove",()=>{Qe()&&(L=!0)},{passive:!0})}C=Me}else c.appendChild(ve),C=ve;R=je,B=pe}let xe=Y?C:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",le),xe.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let ye=xe?oe(xe):!0;if(R.replaceChildren(Ip(Z,ce?.language,ce?.path)),xe){let ve=ee.status!=="complete";le&&ve&&r?.followOutput&&!L&&ye?$(xe):ve||(L=!1),F(xe)}},me=Z=>{v(),E(),G(),c.replaceChildren();let ce=h("div",ph);ce.innerHTML=d(Z),c.appendChild(ce)},he=Z=>{let ce=Z.id,ee=n.features?.artifacts,le=ur(Z,ee,"status-body");if(M&&_===ce&&M.parentElement===c){let xe=M.querySelector(".persona-artifact-status-view-text");xe&&Ro(xe,le,ee);return}v(),E(),c.replaceChildren();let Y=h("div","persona-artifact-status-view"),pe=h("div","persona-artifact-status-view-text");Ro(pe,le,ee),Y.appendChild(pe),c.appendChild(Y),M=Y,_=ce},Ae=Z=>{l=Z;let ce=t.resolveViewMode?.(Z)??r?.viewMode??"rendered",ee=Z.artifactType==="markdown"?Z.file:void 0,le=Z.status!=="complete";le||pr(Z.id);let Y=le?r?.streamingHeight:r?.completeHeight,pe=!!r&&typeof Y=="number";if(r?.streamingView==="status"&&le){he(Z);return}if(ee){let ye=Ra(Z.markdown??""),ve=ds(ee),je=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ce==="rendered"&&je&&(ve==="html"||ve==="svg")){let De=Z.id+"\0"+ye;if(u&&w===De&&u.parentElement===c)return;E(),G(),v(),c.replaceChildren();let Qe=n.features?.artifacts?.filePreview,Ve=Qe?.iframeSandbox??"allow-scripts";!Qe?.dangerouslyAllowSameOrigin&&Ve.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."),Ve=Ve.split(/\s+/).filter(It=>It&&It!=="allow-same-origin").join(" "));let Te=fh(Qe?.loading),Le=h("div","persona-artifact-frame"),Xe=h("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",Ve),Xe.setAttribute("data-artifact-id",Z.id);let Ht=null;Te.enabled&&Te.injectReadySignal?(Ht=mh(),Xe.srcdoc=ye+hh(Ht)):Xe.srcdoc=ye,Le.appendChild(Xe),c.appendChild(Le),Te.enabled&&(f=bh(Le,Xe,Ht,Te,Z.id,n)),u=Le,w=De;return}if(v(),!le&&ve==="markdown"&&ce==="rendered"){me(ye);return}X(ye,{language:ee.language,path:ee.path},Z,pe);return}if(Z.artifactType==="markdown"){if(ce==="source"){v(),X(Z.markdown??"",void 0,Z,pe);return}me(Z.markdown??"");return}v(),E(),G(),c.replaceChildren();let xe=Z.component?o.get(Z.component):void 0;if(xe){let ve={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let je=xe(Z.props??{},ve);if(je){c.appendChild(je);return}}catch{}}c.appendChild(uh(Z))};return Ae(e),{el:c,update(Z){Ae(Z)}}}import{Idiomorph as vh}from"idiomorph";var Oa=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;vh.morph(e,t.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 $p=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hl={index:-1,draft:""};function zp(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="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 jp(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Up(){return new Map}function Vp(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function qp(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Kp(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Gp(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function _a(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function En(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function uo(e,t){return En(e)-e.scrollTop<=t}function $a(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function za(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Qp(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Xp(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Jp(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var gs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},wh=["pre","code","a","script","style"],ja=e=>({type:e?.type??gs.type,placeholder:e?.placeholder??gs.placeholder,speed:e?.speed??gs.speed,duration:e?.duration??gs.duration,buffer:e?.buffer??gs.buffer}),xh=[{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"}],Zp=new Map;for(let e of xh)Zp.set(e.name,e);var mr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Zp.get(e)??null,Ua=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
31
+ `);return s<0?"":e.slice(0,s)}return e},Ch=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},Ah=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},yl=/\s/,Sh=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Th=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(yl.test(s[l])){let p=l;for(;p<s.length&&yl.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&&!yl.test(s[d]);)p.appendChild(Ch(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,e)},Mh=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.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(Ah(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},ms=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??wh).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)Sh(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Th:Mh;for(let u of l)c(u,n,d);return r.innerHTML},Va=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},hs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Yp=new WeakMap,Eh=(e,t)=>{if(!e.styles)return;let n=Yp.get(t);if(n||(n=new Set,Yp.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},bl=new WeakMap,kh=(e,t)=>{if(!e.onAttach)return;let n=bl.get(t);if(n||(n=new Map,bl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},eu=e=>{let t=bl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},qa=(e,t)=>{Eh(e,t),kh(e,t)};function vl(e,t=Vt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var ys=0,fo=null;function wl(e=document){if(ys++,ys===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;fo={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 t=!1;return()=>{if(!t&&(t=!0,ys=Math.max(0,ys-1),ys===0&&fo)){let n=e.body,o=e.defaultView??window;n.style.overflow=fo.originalOverflow,n.style.position=fo.originalPosition,n.style.top=fo.originalTop,n.style.width=fo.originalWidth,o.scrollTo(0,fo.scrollY),fo=null}}}var bs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Dt=e=>(e?.launcher?.mountMode??"floating")==="docked",vs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",gn=e=>{let t=e?.launcher?.dock;return{side:t?.side??bs.side,width:t?.width??bs.width,animate:t?.animate??bs.animate,reveal:t?.reveal??bs.reveal,maxHeight:t?.maxHeight??bs.maxHeight}};var Cn={"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 Lh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ka=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Lh,buttonSize:r,iconSize:s="28px"}=t,a=e?.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=Be("button",{className:Dn("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||Qt.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=ie(u,s,"currentColor",1);return C?(C.style.display="block",v.appendChild(C)):v.textContent=w,p.appendChild(v),Ot({anchor:v,trigger:p,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:p}},Ph="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ga=(e,t={})=>{let{wrapperClassName:n=Ph,buttonSize:o,iconSize:r="20px"}=t,a=(e?.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??"",R=a.tooltipText??"Clear chat",B=a.showTooltip??!0,L=h("div",n),E=!!(u||w),M=Be("button",{className:Dn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!E&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":R},style:{height:l,width:l,color:d||Qt.actionIconColor,backgroundColor:c||void 0,border:E?`${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}}),_=ie(p,r,"currentColor",1);return _&&(_.style.display="block",M.appendChild(_)),L.appendChild(M),Ot({anchor:M,trigger:L,text:()=>M.getAttribute("aria-label")??R,enabled:B}),{button:M,wrapper:L}};var Qt={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))"},Ho=e=>{let{config:t,showClose:n=!0}=e,o=Be("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=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=Be("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 _=parseFloat(s)||24,G=ie(p,_*.6,"currentColor",1);G?d.replaceChildren(G):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=h("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=s,_.style.width=s,d.replaceChildren(_)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Be("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Qt.titleColor}}),w=Be("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Qt.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",R=null,B=null;if(v){let G=Ga(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});R=G.button,B=G.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let L=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:E,wrapper:M}=Ka(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&o.appendChild(M),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:E,closeButtonWrapper:M,clearChatButton:R,clearChatButtonWrapper:B}},ws=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Ih=e=>{let t=Ho({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.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 t};function Rh(e,t,n){if(t?.length)for(let o of t){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=ie(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=fr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Wh=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.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=Rp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Qt.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=Qt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Rh(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let E=r.onTitleClick;d.addEventListener("click",M=>{M.target.closest("button")||E()}),d.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),E())})}let L=r?.titleRowHover;L&&(d.style.borderRadius=L.borderRadius??"10px",d.style.padding=L.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=L.background??"",d.style.borderColor=L.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||Qt.actionIconColor;let v=a.closeButtonIconName??"x",C=ie(v,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),w.appendChild(f),l.appendChild(w);let R=h("div");R.style.display="none";let B=h("span");return B.style.display="none",{header:l,iconHolder:R,headerTitle:c,headerSubtitle:B,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},tu={default:Ih,minimal:Wh},Hh=e=>tu[e]??tu.default,Qa=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.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=t?.layout??"default",s=Hh(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Xa=e=>{let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,r());t.style.height=`${a}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Ja=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",w=t.backgroundColor,f=t.textColor,v=h("div","persona-send-button-wrapper"),C=Be("button",{className:Dn("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:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),R=null,B=null;if(n){let M=parseFloat(u)||24,_=f?.trim()||"currentColor";r?(R=ie(r,M,_,2),R?C.appendChild(R):C.textContent=o):C.textContent=o,B=ie(s,M,_,2)}else C.textContent=p;C.setAttribute("aria-label",a),v.appendChild(C),Ot({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:c});let L="send";return{button:C,wrapper:v,setMode:M=>{if(M===L)return;L=M;let _=M==="stop"?l:a;if(C.setAttribute("aria-label",_),n){if(R&&B){let G=M==="stop"?B:R;C.replaceChildren(G)}}else C.textContent=M==="stop"?d:p}}},Ya=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,w=h("div","persona-send-button-wrapper"),f=Be("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":t.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:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ie(l,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",w.appendChild(f);let R=t.tooltipText??"Start voice recognition",B=t.showTooltip??!1;return Ot({anchor:f,trigger:w,text:()=>f.getAttribute("aria-label")??R,enabled:B}),{button:f,wrapper:w}},Za=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.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=(t.allowedTypes??_n).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=h("div","persona-send-button-wrapper"),c=Be("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":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ie(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=t.buttonTooltipText??"Attach file";return Ot({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},ei=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.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=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=h("a");a.href=t.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},ti=()=>Be("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ni=e=>{let{config:t}=e,n=Be("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=ti(),r=Be("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Xa(t);a();let l=Ja(t),p=Ya(t),d=Za(t),c=ei(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=Be("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 nu=()=>{let e=Be("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=h("span","persona-pill-peek__icon"),n=ie("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=h("span","persona-pill-peek__text"),r=h("span","persona-pill-peek__caret"),s=ie("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ou=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ti(),r=ei(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Xa(t);s.style.maxHeight="100px",a();let l=Ja(t),p=Ya(t),d=Za(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Be("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 ru=e=>{let t=e?.launcher?.enabled??!0,n=Dt(e);if(vs(e)){let c=e?.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(e?.launcher?.zIndex??Vt);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(e?.launcher?.zIndex??Vt),{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(!t){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=e?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Cn[r.position]?Cn[r.position]:Cn["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Vt);let l=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??$n;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},Bh=(e,t)=>{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}=Ka(e,{showClose:t,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=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let M=Ga(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=M.button,l=M.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Be("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Be("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=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),w=Be("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=e?.layout?.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(w.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(w,f);let R=Be("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=ou({config:e}),{root:L,textNode:E}=nu();return n.append(p,r,d,R),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:R,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,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:L,peekTextNode:E}},su=(e,t=!0)=>{if(vs(e))return Bh(e,t);let n=Be("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Qa(e,o,{showClose:t}):Ho({config:e,showClose:t}),a=Be("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=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Dt(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),c=h("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.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=ni({config:e}),v=e?.layout?.showFooter!==!1;r?ws(n,s,e):(s.header.style.display="none",ws(n,s,e)),n.append(a);let C=Be("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 xl=(e,t)=>{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 Xr=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=Wt(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??zt));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 Vp=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=jp(t),s=qp(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}}},pl=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>dl(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=dl(t,n);return{instance:r,element:r.element}};var mh=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}},hh=(t,e)=>{if(!t)return null;let n=mh(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},yh=(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},bh=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ul=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(":"))},fl=320,Xp=320,vh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),wh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),xh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Ch=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Ah=t=>{if(!t||t.length===0)return null;let e=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},Sh=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Yr(o.ref,{readonly:!0,render:e}))}return n},Kp="\uE000",Gp="\uE001",Th=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${Kp}${r}:${w}${Gp}`,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(Sh(e,o));return}t.innerHTML=l;let d=new RegExp(`${Kp}${r}:(\\d+)${Gp}`),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(Yr(C.ref,{readonly:!0,render:o}),I),f=I}}},Mh=(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=`${fl}px`,d.style.maxHeight=`${Xp}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}),bh(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}},Eh=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(!ul(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=`${fl}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},kh=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(!ul(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=`${fl}px`,r.style.maxHeight=`${Xp}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}},Lh=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(!ul(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}},us=()=>{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},Ph=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:us};if(e){let r=e(o);if(r!==null)return r}return us()},Ih=(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},Qp=(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},Rh=(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},Wh=(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=It({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},gl=(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=Rh(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=vh(t),B=t.content?.trim()??"",M=I.length>0&&B===fa,P=Ha(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,K=t.role==="assistant"&&P.type!=="none"?cr(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?Ba(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"?as(Z,"char",t.id,{skipTags:K.skipTags}):U&&K?.wrap==="word"?as(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?Th(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=Da(),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=Qp(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=Mh(I,!M&&!!B,()=>{M&&F&&(F.style.display="")});Z?C.appendChild(Z):M&&F&&(F.style.display="")}let le=wh(t);if(le.length>0){let Z=Eh(le);Z&&C.appendChild(Z)}let ge=xh(t);if(ge.length>0){let Z=kh(ge);Z&&C.appendChild(Z)}let Ce=Ch(t);if(Ce.length>0){let Z=Lh(Ce);Z&&C.appendChild(Z)}let we=t.contentSegments?.length?null:Ah(t.contextMentions);if(we&&C.appendChild(we),C.appendChild(j),u&&f==="below"&&t.createdAt){let Z=Qp(t,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let ee=t.role==="assistant"?hh(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(is());else if(he)C.appendChild(is());else{let pe=Ph("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);pe&&C.appendChild(pe)}}if(ee&&t.stopReason&&!t.streaming&&(B||(j.style.display="none"),C.appendChild(yh(t.stopReason,ee))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let Z=Wh(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":""}`),ie=Ih(p,t.role);return w==="right"||w==="left"&&t.role==="user"?Y.append(C,ie):Y.append(ie,C),Y};var dr=new Set,Hh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Bh=(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
- `):""},Jp=(t,e)=>{let n=dr.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")},ml=(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&&dr.has(t.id),l=n.status!=="complete",p=Bh(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=ca(n),ge},I=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:w,previewText:p,isActive:l,config:e??{},elapsed:ca(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=Id(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=da(ge,""),ee=0;for(let ce of we){let Y=ce.styles.length>0?(()=>{let ie=h("span",ce.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(ie),ie})():u;if(ce.isDuration&&l)Y.appendChild(C());else{let ie=ce.isDuration?ca(n):ce.text;Ce?ee=ro(Y,ie,ee):Y.appendChild(document.createTextNode(ie))}}};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??{}});Hh(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 pr=new Set,Dh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Fh=(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
- `);let r=no(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
42
- `):""},hl=(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)"},Nh=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Fh(t,o?.previewMaxLines??3),a=n?Rd(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=zi(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=zi(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},Yp=(t,e,n)=>{let o=pr.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")},yl=(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&&pr.has(t.id),{summary:p,previewText:d,isActive:c}=Nh(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=jr(n),D},I=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:e??{},elapsed:jr(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 le=n.name?.trim()||"tool",ge=da(D,le),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?jr(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 le=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");le.append(x),u.append(w,le)}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??{}});Dh(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 le=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");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",hl(le,o),le.textContent=no(n.args),D.append(F,le),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 le=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");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",hl(le,o),le.textContent=n.chunks.join(""),D.append(F,le),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 le=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");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",hl(le,o),le.textContent=no(n.result),D.append(F,le),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 Ro=new Map,Ga=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)},Zp=t=>t?.approval!==!1?t?.approval:void 0,eu=(t,e)=>{let n=Zp(e)?.detailsDisplay??"collapsed";return Ro.get(t)??n==="expanded"},tu=(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=re(e?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},nu=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=eu(t,n);tu(o,s,n),r.style.display=s?"":"none"};var Qa=(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)?_r(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??Ga(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=eu(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),tu(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 le=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(le),x.append(U,D),u.appendChild(x)}return a.append(l,u),s.appendChild(a),s};var Oh=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),ou=(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))},Wo=(t,e)=>{ou(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)},_h=t=>t?.approval!==!1?t?.approval:void 0,$h=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return Ro.get(t)??n==="expanded"},bl=t=>{let e=h("span","persona-approval-kbd");return e.textContent=t,e},zh=(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)?_r(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??Ga(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},Uh=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?Ga(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},jh=(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&&$h(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=zh(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",bl("\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(bl("Esc"));let F=h("div","persona-approval-menu"),le=h("button","persona-approval-menu-item");le.type="button",le.append("Allow once",bl("\u2318\u23CE")),F.appendChild(le),z=Zc({anchor:U,content:F,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),le.addEventListener("click",()=>{Wo(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),Ro.set(e.id,F)}return}if(J==="toggle-menu"){z?.toggle();return}if(J==="always"){Wo(t,e.id),r({remember:!0});return}if(J==="allow"){Wo(t,e.id),r();return}if(J==="deny"){Wo(t,e.id),s();return}}),l},ru=()=>{let t=Oh();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=_h(a);if(l.status!=="pending"){if(Wo(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Uh(l)}ou(t,o.id);let d=p?.enableAlwaysAllow===!0,c=jh(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=>{ed(w)||o.id===t.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),Wo(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()])Wo(t,o);t.latestPendingApprovalId=null}}};var su=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 fs=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 gs=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 qh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Vh=new Set(["step_start","execution_start"]),Kh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Gh=new Set(["step_complete","agent_turn_complete"]),Qh=new Set(["flow_complete","agent_complete"]),au=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),lu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),nn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Ho=(t,e)=>{let n=t[e];return lu(n)?n:void 0};function vl(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Xa(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Xh(t,e){return typeof e.type=="string"?e.type:t}function Jh(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 Yh(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 iu(t){let e=Ho(t,"result"),n=[Ho(t,"tokens"),Ho(t,"totalTokens"),e?Ho(e,"tokens"):void 0,Ho(t,"usage"),e?Ho(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 Zh(t){let e=Ho(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 ey(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ms=class{constructor(e=ey){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:Xa(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(!lu(n)){au.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Xh(e,n),r=this.now();if(qh.has(o)){this.startRun(r);return}if(Vh.has(o)){this.run||this.startRun(r);return}if(Kh.has(o)){if(!Yh(o,n))return;let s=Jh(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+vl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Xa(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Gh.has(o)){if(!this.run)return;let s=this.run,a=iu(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+vl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Xa(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(Qh.has(o)){if(!this.run)return;let s=this.run,a=iu(n),l=a??s.exactOutputTokens+vl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Xa(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(au.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:Zh(n)??o-e.startedAt}};function ur(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var ty={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)"}},ny={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},oy=["flowName","stepName","reasoningText","text","name","tool","toolName"],ry=100;function sy(t,e){let n={...ty,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return ny}function ay(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function iy(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 ly(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 cy(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 dy(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 py(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function uy(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 fy(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 wl(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");ur(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"?ay(t.timestamp,n):iy(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=sy(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??oy,K=ly(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 cy(dy(t)),j.innerHTML="";let F=re("check","12px","currentColor",1.5);F&&j.appendChild(F),setTimeout(()=>{j.innerHTML="";let le=re("clipboard","12px","currentColor",1.5);le&&j.appendChild(le)},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(fy(t,a,l)),w}}function cu(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");ur(C,v?.panel);let I=[],B="",k="",M=null,P=[],z={},K=0,x=Ia(),U=0,j=0,J=!1,D=null,F=!1,le=0,ge=new Set,Ce=new Map,we="",ee="",ce=null,Y,ie,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(ur($,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 Je=pe,lo=Te,co=()=>{if(!lo.textContent)return;let ws=Je.getBoundingClientRect(),Ut=H.getBoundingClientRect();lo.style.left=`${ws.left-Ut.left}px`,lo.style.top=`${ws.bottom-Ut.top+4}px`,lo.style.display="block"},Za=()=>{lo.style.display="none"};pe.addEventListener("mouseenter",co),pe.addEventListener("mouseleave",Za),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 qe=h("option","");qe.value="",qe.textContent="All events (0)",Y.appendChild(qe),ie=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"),ie.type="button",ie.title="Copy All";let rt=re("clipboard-copy","12px","currentColor",1.5);rt&&ie.appendChild(rt);let V=h("span","persona-event-copy-all persona-text-xs");V.textContent="Copy All",ie.appendChild(V),pe&&$.appendChild(pe),$.appendChild(se),$.appendChild(Y),$.appendChild(ie);let ze=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ur(ze,v?.searchBar);let Se=re("search","14px","var(--persona-muted, #9ca3af)",1.5),We=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&&We.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"),ur(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 Pe=re("x","12px","currentColor",2);return Pe&&he.appendChild(Pe),ze.appendChild(We),ze.appendChild(Z),ze.appendChild(he),H.appendChild($),H.appendChild(ze),Te&&H.appendChild(Te),H}let $e,Fe=s.find(H=>H.renderEventStreamToolbar);Fe?.renderEventStreamToolbar&&r?$e=Fe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ae(),eventCount:e.getSize(),filteredCount:0,onFilterChange:$=>{B=$,Le(),be()},onSearchChange:$=>{k=$,Le(),be()}})??Ae():$e=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 Qe(){if(!a||!ye||!pe)return;let H=a(),$=py(H);ye.textContent=$;let se=uy(H);Te&&(Te.textContent=se,se||(Te.style.display="none")),pe.setAttribute("aria-label",se?`Throughput: ${$}, ${se}`:`Throughput: ${$}`)}let He=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Ee=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Ee.style.height="100%";let Xe=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");ur(Xe,v?.scrollIndicator),Xe.style.display="none",Xe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let on=re(d,"14px","currentColor",2);on&&Xe.appendChild(on);let St=h("span","");St.textContent=c,Xe.appendChild(St);let ht=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ht.style.display="none",He.appendChild(Ee),He.appendChild(ht),He.appendChild(Xe),C.setAttribute("tabindex","0"),C.appendChild($e),C.appendChild(ot),C.appendChild(He);function Be(){let H=e.getAll(),$={};for(let ze of H)$[ze.type]=($[ze.type]||0)+1;let se=Object.keys($).sort(),qe=se.length!==P.length||!se.every((ze,Se)=>ze===P[Se]),ke=!qe&&se.some(ze=>$[ze]!==z[ze]),rt=H.length!==Object.values(z).reduce((ze,Se)=>ze+Se,0);if(!qe&&!ke&&!rt||(P=se,z=$,!Y))return;let V=Y.value;if(Y.options[0].textContent=`All events (${H.length})`,qe){for(;Y.options.length>1;)Y.remove(1);for(let ze of se){let Se=h("option","");Se.value=ze,Se.textContent=`${ze} (${$[ze]||0})`,Y.appendChild(Se)}V&&se.includes(V)?Y.value=V:V&&(Y.value="",B="")}else for(let ze=1;ze<Y.options.length;ze++){let Se=Y.options[ze];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 Ke(){return B!==""||k!==""}function Le(){K=0,U=0,x.resume(),Xe.style.display="none"}function ue(H){ge.has(H)?ge.delete(H):ge.add(H),ce=H;let $=Ee.scrollTop,se=x.isFollowing();F=!0,x.pause(),be(),Ee.scrollTop=$,se&&x.resume(),F=!1}function ae(){return ao(Ee,50)}function be(){j=Date.now(),J=!1,Qe(),Be();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&&Ke()?(ht.textContent=k?`No events matching '${k}'`:"No events matching filter",ht.style.display="",Ee.style.display="none"):(ht.style.display="none",Ee.style.display=""),ie&&(ie.title=Ke()?`Copy Filtered (${$})`:"Copy All"),p&&!x.isFollowing()&&$>K&&(U+=$-K,St.textContent=c?`${c}${U>0?` (${U})`:""}`:"",Xe.style.display=""),K=$;let qe=e.getAll(),ke=qe.length>0?qe[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,ze=Ce.size===0&&I.length>0;if(V||ze||I.length===0){Ee.innerHTML="",Ce.clear();let Se=document.createDocumentFragment();for(let We=0;We<I.length;We++){let Pe=wl(I[We],We,ke,u,ge,ue,s,r);Ce.set(I[We].id,Pe),Se.appendChild(Pe)}Ee.appendChild(Se),we=B,ee=k,ce=null}else{if(ce!==null){let We=Ce.get(ce);if(We&&We.parentNode===Ee){let Pe=I.findIndex(Je=>Je.id===ce);if(Pe>=0){let Je=wl(I[Pe],Pe,ke,u,ge,ue,s,r);Ee.insertBefore(Je,We),We.remove(),Ce.set(ce,Je)}}ce=null}let Se=new Set(I.map(We=>We.id));for(let[We,Pe]of Ce)Se.has(We)||(Pe.remove(),Ce.delete(We));for(let We=0;We<I.length;We++){let Pe=I[We];if(!Ce.has(Pe.id)){let Je=wl(Pe,We,ke,u,ge,ue,s,r);Ce.set(Pe.id,Je),Ee.appendChild(Je)}}}x.isFollowing()&&(Ee.scrollTop=Ee.scrollHeight)}function yt(){if(Date.now()-j>=ry){D!==null&&(cancelAnimationFrame(D),D=null),be();return}J||(J=!0,D=requestAnimationFrame(()=>{D=null,be()}))}let ve=(H,$)=>{if(!ie)return;ie.innerHTML="";let se=re(H,"12px","currentColor",1.5);se&&ie.appendChild(se);let qe=h("span","persona-text-xs");qe.textContent="Copy All",ie.appendChild(qe),setTimeout(()=>{ie.innerHTML="";let ke=re("clipboard-copy","12px","currentColor",1.5);ke&&ie.appendChild(ke);let rt=h("span","persona-text-xs");rt.textContent="Copy All",ie.appendChild(rt),ie.disabled=!1},$)},de=async()=>{if(ie){ie.disabled=!0;try{let H;Ke()?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,Le(),be())},X=()=>{!Z||!he||(he.style.display=Z.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{k=Z.value,Le(),be()},150))},T=()=>{!Z||!he||(Z.value="",k="",he.style.display="none",M&&clearTimeout(M),Le(),be())},O=()=>{if(F)return;let H=Ee.scrollTop,{action:$,nextLastScrollTop:se}=Ra({following:x.isFollowing(),currentScrollTop:H,lastScrollTop:le,nearBottom:ae(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});le=se,$==="resume"?(x.resume(),U=0,Xe.style.display="none"):$==="pause"&&(x.pause(),p&&(St.textContent=c,Xe.style.display=""))},y=H=>{let $=Wa({following:x.isFollowing(),deltaY:H.deltaY,nearBottom:ae(),resumeWhenNearBottom:!0});$==="pause"?(x.pause(),p&&(St.textContent=c,Xe.style.display="")):$==="resume"&&(x.resume(),U=0,Xe.style.display="none")},S=()=>{p&&(Ee.scrollTop=Ee.scrollHeight,x.resume(),U=0,Xe.style.display="none")},E=H=>{let $=H.target;if(!$||$.closest("button"))return;let se=$.closest("[data-event-id]");if(!se)return;let qe=se.getAttribute("data-event-id");qe&&ue(qe)},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())};ie&&ie.addEventListener("click",de),Y&&Y.addEventListener("change",un),Z&&Z.addEventListener("input",X),he&&he.addEventListener("click",T),Ee.addEventListener("scroll",O),Ee.addEventListener("wheel",y,{passive:!0}),Ee.addEventListener("click",E),Xe.addEventListener("click",S),C.addEventListener("keydown",W);function q(){M&&clearTimeout(M),D!==null&&(cancelAnimationFrame(D),D=null),J=!1,Ce.clear(),ie&&ie.removeEventListener("click",de),Y&&Y.removeEventListener("change",un),Z&&Z.removeEventListener("input",X),he&&he.removeEventListener("click",T),Ee.removeEventListener("scroll",O),Ee.removeEventListener("wheel",y),Ee.removeEventListener("click",E),Xe.removeEventListener("click",S),C.removeEventListener("keydown",W)}return{element:C,update:yt,destroy:q}}}function du(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 pu(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=It({icon:"x",label:a});B.addEventListener("click",()=>{f(),e.onDismiss?.()});let k="rendered",M=Ma({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?Po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):It({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?Po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):It({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=It({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=It({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(J=It({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&J.classList.add("persona-hidden"));let le=r?It({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):It({icon:"refresh-cw",label:"Refresh"}),ge=r?It({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):It({icon:"x",label:a}),Ce=It({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=He.find(S=>S.id===Ee)??He[He.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=He.find(T=>T.id===Ee)??He[He.length-1];try{await navigator.clipboard.writeText(rs(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=ir({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()})}le.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ve()}),ge.addEventListener("click",()=>{f(),e.onDismiss?.()});let ie=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,le,ge):P.append(J,le,ge),P.insertBefore(we,ge),P.insertBefore(Ce,ge),C.append(M.element,ie,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=du(Z,{onSelect:X=>e.onSelect(He[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,$e=()=>{if(Ae)return;let X=()=>{Ae=0,Te(Z)};Ae=typeof requestAnimationFrame=="function"?requestAnimationFrame(X):setTimeout(X,0)};Z.addEventListener("scroll",()=>$e(),{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},Qe=()=>{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 He=[],Ee=null,Xe=!1,on=!1,St=!0,ht=!1,Be=null,me="",Ke=null,Le=!1,ue=X=>X.artifactType==="markdown"&&!!X.file||r?k:"rendered",ae=X=>{r||(X&&!Le?(C.insertBefore(M.element,I),Le=!0):!X&&Le&&(M.element.remove(),Le=!1))},be=()=>Ee&&He.find(X=>X.id===Ee)||He[He.length-1],yt=()=>{let X=ns(be());if(!X){we.replaceChildren();return}let T=ee.filter(O=>O.visible===void 0||O.visible(X)).map(O=>lr(O,{documentChrome:r,onClick:()=>{let y=ns(be());if(y)try{Promise.resolve(O.onClick(y)).catch(()=>{})}catch{}}}));we.replaceChildren(...T)},ve=()=>{yt();let X=r&&He.length<=1,T=!!he;if(Z.classList.toggle("persona-hidden",X||T),ye.classList.toggle("persona-hidden",X||!T),T&&he){let S=He.map(E=>E.id).join("|")+" "+(Ee??"");if(S!==me){me=S;let E=he({records:He,selectedId:Ee,onSelect:e.onSelect});ye.firstElementChild!==E&&ye.replaceChildren(E)}}else{pe.beforeRender(),Z.replaceChildren();let S=[],E=-1;for(let[W,q]of He.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),qe=$?.path||q.title||se;H.textContent=se,H.title=qe,H.setAttribute("aria-label",qe),q.id===Ee&&(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&&Ee!==Be){Be=Ee;let W=S[E];typeof W.scrollIntoView=="function"&&W.scrollIntoView({block:"nearest",inline:"nearest"})}Te(Z)}let O=Ee&&He.find(S=>S.id===Ee)||He[He.length-1];if(!O){Fe.replaceChildren(),Ke=null,ae(!1);return}let y=O.artifactType==="markdown"?O.file:void 0;if(ae(!!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";ie.textContent=`${W} \xB7 ${S}`}else I.textContent=y?Sn(y.path):s;Ke?(Ke.el.parentElement!==Fe&&Fe.replaceChildren(Ke.el),Ke.update(O)):(Ke=La(O,{config:t,resolveViewMode:ue}),Fe.replaceChildren(Ke.el)),Fe.classList.toggle("persona-artifact-content-flush",!!Fe.querySelector(".persona-code-pre"))},de=()=>{let X=He.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&&Xe?(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=()=>{ht=!1,ve(),de()};return{element:v,backdrop:w,update(X){let T=X.selectedId??X.artifacts[X.artifacts.length-1]?.id??null,O=T!==Ee;He=X.artifacts,Ee=T,He.length>0&&(Xe=!0),ht=!0,St&&un(),O&&ot()},setMobileOpen(X){Xe=X,!X&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):de()},setExpanded(X){X!==on&&(on=X,Qe());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,yt()},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!==St&&(St=X,X&&ht&&un())}}}function Gt(t){return t?.features?.artifacts?.enabled===!0}function uu(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 gy(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 fu=["panel","seamless","detached"];function xl(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&fu.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Cl(t){return!t||!Gt(t)?!1:xl(t)==="detached"}function hs(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"),gy(t),uu(t,e);return}let n=e.features?.artifacts?.layout,o=xl(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"),uu(t,e)}function ys(t,e){for(let l of fu)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=xl(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 gu(t,e){return!e||!Gt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function my(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 hy(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 yy(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function by(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Al(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 mu(t,e,n,o,r,s){let a=my(r,200),l=by(e,n,o,200);l=Math.max(a,l);let p=hy(s);return p!==null&&(l=Math.min(l,p)),yy(t,a,l)}var hu={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"}},Sl=(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=hu[a]??hu.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 Tl=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()}},Ml=new Tl;var yu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),vy=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),bu=(t,e,n)=>{if(!yu(t)||!yu(e)||vy.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]=bu(t[r],e[r],s)}return o};function vu(t,e){let n=bu(t,e,"");return va(n)}var wu=()=>{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 wy=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},xy=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},kl=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=wy(t),n=xy(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}},El=t=>typeof t=="string"?t:t==null?"":String(t),bs={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:El(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=El(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:El(n.text)}}},xu=t=>Array.isArray(t)?t.map(e=>String(e)):[],Ll=t=>{let e=new Set(xu(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(xu(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 Cy=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}},Ay=t=>t.map(e=>({...e,streaming:!1})),Sy=t=>t.map(e=>({...e,status:"complete"})),Cu=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Cy(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?Ay(n.messages):void 0,artifacts:n.artifacts?Sy(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 iA,STR as lA,OBJ as cA}from"partial-json";function Au(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 Su(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 Pl(t){let e=Su(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 Tu(t){let e=Su(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 Ty=["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=Ty}=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=`
39
+ `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Dt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let E=a.title??"Chat Assistant";p.textContent=E,p.setAttribute("title",E)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let E=a.subtitle??"Here to help you get answers fast";d.textContent=E,d.setAttribute("title",E)}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 E=a.agentIconSize??"40px";if(u.style.height=E,u.style.width=E,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 M=parseFloat(E)||24,_=ie(a.agentIconName,M*.6,"var(--persona-text-inverse, #ffffff)",2);_?(u.appendChild(_),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 E=a.agentIconSize??"40px";w.style.height=E,w.style.width=E,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 E=a.callToActionIconSize??"32px";f.style.height=E,f.style.width=E,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 M=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,M=(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 _=parseFloat(E)||24,G=Math.max(_-M,8),x=ie(a.callToActionIconName,G,"currentColor",2);x?f.appendChild(x):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&Cn[a.position]?Cn[a.position]:Cn["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",R="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?R:`${C} ${v}`,l||(n.style.zIndex=String(a.zIndex??Vt));let B="1px solid var(--persona-border, #e5e7eb)",L="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:L,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",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var au=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=ru(e),s=su(e,t),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}}},Cl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>xl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=xl(e,n);return{instance:r,element:r.element}};var Dh=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Fh=(e,t)=>{if(!e)return null;let n=Dh(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Nh=(e,t)=>{let n=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Oh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Al=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Sl=320,du=320,_h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),zh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Uh=e=>{if(!e||e.length===0)return null;let t=Be("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Be("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=h("span","persona-mention-chip-icon"),s=ie(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Be("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Vh=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(is(o.ref,{readonly:!0,render:t}))}return n},iu="\uE000",lu="\uE001",qh=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${iu}${r}:${w}${lu}`,a=t.map((w,f)=>w.kind==="text"?w.text:s(f)).join(""),l=n(a);if(!t.every((w,f)=>w.kind==="text"||l.includes(s(f)))){e.replaceChildren(Vh(t,o));return}e.innerHTML=l;let d=new RegExp(`${iu}${r}:(\\d+)${lu}`),c=document.createTreeWalker(e,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=t[Number(v[1])],R=f.splitText(v.index);R.data=R.data.slice(v[0].length),C?.kind==="mention"&&R.parentNode?.insertBefore(is(C.ref,{readonly:!0,render:o}),R),f=R}}},Kh=(e,t,n)=>{if(e.length===0)return null;try{let o=h("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.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=`${Sl}px`,d.style.maxHeight=`${du}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}),Oh(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}},Gh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Al(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=`${Sl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Qh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Al(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=`${Sl}px`,r.style.maxHeight=`${du}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Xh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Al(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",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},xs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let 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",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Jh=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:xs};if(t){let r=t(o);if(r!==null)return r}return xs()},Yh=(e,t)=>{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=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=h("img");r.src=o,r.alt=t==="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(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},cu=(e,t,n="div")=>{let o=h(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Tl=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Zh=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=h("div");return v.style.display="none",v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id),v}let l=t.visibility??"hover",p=t.align??"right",d=t.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-${e.id}`,w.setAttribute("data-actions-for",e.id);let f=(v,C,R)=>{let B=Pt({icon:v,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",R),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},Ml=(e,t,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=Tl(e.role,l),C=h("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let R=_h(e),B=e.content?.trim()??"",E=R.length>0&&B===Ca,M=ja(s?.widgetConfig?.features?.streamAnimation),_=s?.widgetConfig?.features?.streamAnimation?.plugins,G=e.role==="assistant"&&M.type!=="none"?mr(M.type,_):null,x=e.role==="assistant"&&G?.isAnimating?.(e)===!0,j=e.role==="assistant"&&G!==null&&(!!e.streaming||x);j&&G?.bubbleClass&&C.classList.add(G.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),e.streaming&&U.classList.add("persona-content-streaming"),j&&G&&(G.containerClass&&U.classList.add(G.containerClass),U.style.setProperty("--persona-stream-step",`${M.speed}ms`),U.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let oe=j?Ua(e.content??"",M.buffer,G,e,!!e.streaming):e.content??"",F=()=>{let Y=t({text:oe,message:e,streaming:!!e.streaming,raw:e.rawContent});return j&&G?.wrap==="char"?ms(Y,"char",e.id,{skipTags:G.skipTags}):j&&G?.wrap==="word"?ms(Y,"word",e.id,{skipTags:G.skipTags}):Y},$=null;if(E?($=document.createElement("div"),$.innerHTML=F(),$.style.display="none",U.appendChild($)):e.contentSegments?.length?qh(U,e.contentSegments,Y=>t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):U.innerHTML=F(),j&&G?.useCaret&&!E&&B){let Y=Va(),pe=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),xe=pe[pe.length-1];if(xe?.parentNode)xe.parentNode.insertBefore(Y,xe.nextSibling);else{let ye=U.lastElementChild;ye?ye.appendChild(Y):U.appendChild(Y)}}if(u&&f==="inline"&&e.createdAt){let Y=cu(e,d,"span");Y.classList.add("persona-timestamp-inline");let pe=U.lastElementChild;pe?pe.appendChild(Y):U.appendChild(Y)}if(R.length>0){let Y=Kh(R,!E&&!!B,()=>{E&&$&&($.style.display="")});Y?C.appendChild(Y):E&&$&&($.style.display="")}let X=$h(e);if(X.length>0){let Y=Gh(X);Y&&C.appendChild(Y)}let me=zh(e);if(me.length>0){let Y=Qh(me);Y&&C.appendChild(Y)}let he=jh(e);if(he.length>0){let Y=Xh(he);Y&&C.appendChild(Y)}let Ae=e.contentSegments?.length?null:Uh(e.contextMentions);if(Ae&&C.appendChild(Ae),C.appendChild(U),u&&f==="below"&&e.createdAt){let Y=cu(e,d);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let Z=e.role==="assistant"?Fh(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(oe&&oe.trim()),pe=M.placeholder==="skeleton",xe=pe&&M.buffer==="line"&&Y;if(Y)xe&&C.appendChild(hs());else if(pe)C.appendChild(hs());else{let ye=Jh("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&C.appendChild(ye)}}if(Z&&e.stopReason&&!e.streaming&&(B||(U.style.display="none"),C.appendChild(Nh(e.stopReason,Z))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Y=Zh(e,o,r);C.appendChild(Y)}if(!c||e.role==="system")return C;let ee=h("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=Yh(p,e.role);return w==="right"||w==="left"&&e.role==="user"?ee.append(C,le):ee.append(le,C),ee};var hr=new Set,ey=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ty=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
40
+ `):""},pu=(e,t)=>{let n=hr.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.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=ie(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")},El=(e,t)=>{let n=e.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-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&hr.has(e.id),l=n.status!=="complete",p=ty(e,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=t?.reasoning??{},v=String(n.startedAt??Date.now()),C=()=>{let me=h("span","");return me.setAttribute("data-tool-elapsed",v),me.textContent=ba(n),me},R=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:w,previewText:p,isActive:l,config:t??{},elapsed:ba(n),createElapsedElement:C});typeof R=="string"&&R.trim()?(u.textContent=R,c.appendChild(u)):R instanceof HTMLElement?c.appendChild(R):(u.textContent=w,c.appendChild(u));let B=h("span","persona-text-xs persona-text-persona-primary");B.textContent=Vd(n),c.appendChild(B);let L=r.loadingAnimation??"none",E=f.activeTextTemplate,M=f.completeTextTemplate,_=l?E:M,G=R instanceof HTMLElement,x=(me,he)=>{u.textContent="";let Ae=va(me,""),Z=0;for(let ce of Ae){let ee=ce.styles.length>0?(()=>{let le=h("span",ce.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return u.appendChild(le),le})():u;if(ce.isDuration&&l)ee.appendChild(C());else{let le=ce.isDuration?ba(n):ce.text;he?Z=co(ee,le,Z):ee.appendChild(document.createTextNode(le))}}};if(!G&&_)if(B.style.display="none",u.style.display="",l&&L!=="none"){let me=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),x(_,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),L==="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(_,!0))}else x(_,!1);else if(!G&&l&&L!=="none"){u.style.display="";let me=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),L==="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 he=u.textContent||w;u.textContent="",co(u,he,0)}n.status==="complete"&&(u.style.display="none")}else G||(n.status==="complete"?u.style.display="none":u.style.display="");let j=null;if(s){j=h("div","persona-flex persona-items-center");let he=ie(a?"chevron-up":"chevron-down",16,"currentColor",2);he?j.appendChild(he):j.textContent=a?"Hide":"Show";let Ae=h("div","persona-flex persona-items-center persona-ml-auto");Ae.append(j),d.append(c,Ae)}else d.append(c);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","reasoning"),U.style.display="none",U.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&p){let me=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});ey(U,me)||(U.textContent=p),U.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,U),o;let oe=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");oe.style.display=a?"":"none";let F=n.chunks.join(""),$=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return $.textContent=F||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),oe.appendChild($),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let he=ie(a?"chevron-up":"chevron-down",16,"currentColor",2);he?j.appendChild(he):j.textContent=a?"Hide":"Show"}oe.style.display=a?"":"none",U.style.display=a?"none":U.textContent||U.childNodes.length?"":"none"})(),o.append(d,U,oe),o};var yr=new Set,ny=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),oy=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
41
+ `);let r=io(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
42
+ `):""},kl=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},ry=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=oy(e,o?.previewMaxLines??3),a=n?qd(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=Zi(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=Zi(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},uu=(e,t,n)=>{let o=yr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),l=t.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=ie(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")},Ll=(e,t)=>{let n=e.toolCall,o=t?.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-${e.id}`,r.setAttribute("data-message-id",e.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=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&yr.has(e.id),{summary:p,previewText:d,isActive:c}=ry(e,t),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 F=h("span","");return F.setAttribute("data-tool-elapsed",v),F.textContent=Zr(n),F},R=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Zr(n),createElapsedElement:C});typeof R=="string"&&R.trim()?(f.textContent=R,w.appendChild(f)):R instanceof HTMLElement?w.appendChild(R):(f.textContent=p,w.appendChild(f));let B=s.loadingAnimation??"none",L=o.activeTextTemplate,E=o.completeTextTemplate,M=c?L:E,_=R instanceof HTMLElement,G=(F,$)=>{f.textContent="";let X=n.name?.trim()||"tool",me=va(F,X),he=0;for(let Ae of me){let Z=Ae.styles.length>0?(()=>{let ce=h("span",Ae.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(ce),ce})():f;if(Ae.isDuration&&c)Z.appendChild(C());else{let ce=Ae.isDuration?Zr(n):Ae.text;$?he=co(Z,ce,he):Z.appendChild(document.createTextNode(ce))}}};if(!_)if(c&&B!=="none"){let F=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",`${F}ms`),M&&G(M,!1);else if(f.classList.add(`persona-tool-loading-${B}`),f.style.setProperty("--persona-tool-anim-duration",`${F}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)),M)G(M,!0);else{let $=f.textContent||p;f.textContent="",co(f,$,0)}}else M&&G(M,!1);let x=null;if(a){x=h("div","persona-flex persona-items-center");let F=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=ie(l?"chevron-up":"chevron-down",16,F,2);$?x.appendChild($):x.textContent=l?"Hide":"Show";let X=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(x),u.append(w,X)}else u.append(w);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","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let F=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});ny(j,F)||(j.textContent=d),j.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,j),r;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(U.style.display=l?"":"none",o.contentBackgroundColor&&(U.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(U.style.color=o.contentTextColor),o.contentPaddingX&&(U.style.paddingLeft=o.contentPaddingX,U.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(U.style.paddingTop=o.contentPaddingY,U.style.paddingBottom=o.contentPaddingY),n.name){let F=h("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?F.style.color=o.contentTextColor:o.headerTextColor&&(F.style.color=o.headerTextColor),F.textContent=n.name,U.appendChild(F)}if(n.args!==void 0){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Arguments";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=io(n.args),F.append($,X),U.appendChild(F)}if(n.chunks&&n.chunks.length){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Activity";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=n.chunks.join(""),F.append($,X),U.appendChild(F)}if(n.status==="complete"&&n.result!==void 0){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Result";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=io(n.result),F.append($,X),U.appendChild(F)}if(n.status==="complete"&&typeof n.duration=="number"){let F=h("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(F.style.color=o.contentTextColor),F.textContent=`Duration: ${n.duration}ms`,U.appendChild(F)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),x){x.innerHTML="";let F=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=ie(l?"chevron-up":"chevron-down",16,F,2);$?x.appendChild($):x.textContent=l?"Hide":"Show"}U.style.display=l?"":"none",j.style.display=l?"none":j.textContent||j.childNodes.length?"":"none"})(),r.append(u,j,U),r};var Bo=new Map,oi=e=>{let n=(e.startsWith(Nn)?e.slice(Nn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},fu=e=>e?.approval!==!1?e?.approval:void 0,gu=(e,t)=>{let n=fu(t)?.detailsDisplay??"collapsed";return Bo.get(e)??n==="expanded"},mu=(e,t,n)=>{let o=fu(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ie(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},hu=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=gu(e,n);mu(o,s,n),r.style.display=s?"":"none"};var ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.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-${e.id}`,s.setAttribute("data-message-id",e.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=ie(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(Nn)?Gr(n.toolName):void 0,R=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,L=R||(B?n.description:`The assistant wants to use \u201C${C??oi(n.toolName)}\u201D.`),E=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(E.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(E.style.color=o.descriptionColor),E.textContent=L,u.appendChild(E),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 j=h("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 M=o?.detailsDisplay??"collapsed",_=!!n.description&&!B,G=_||!!n.parameters;if(M!=="hidden"&&G){let x=gu(e.id,t),j=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");j.type="button",j.setAttribute("data-expand-header","true"),j.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(j.style.color=o.descriptionColor);let U=h("span");U.setAttribute("data-approval-details-label","true");let oe=h("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),j.append(U,oe),mu(j,x,t),u.appendChild(j);let F=h("div");if(F.setAttribute("data-approval-details","true"),F.style.display=x?"":"none",_){let $=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&($.style.color=o.descriptionColor),$.textContent=n.description,F.appendChild($)}if(n.parameters){let $=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&&($.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&($.style.color=o.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=io(n.parameters),F.appendChild($)}u.appendChild(F)}if(r){let x=h("div","persona-flex persona-gap-2 persona-mt-2");x.setAttribute("data-approval-buttons","true");let j=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");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 U=ie("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);U&&(U.style.marginRight="4px",j.appendChild(U));let oe=document.createTextNode(o?.approveLabel??"Approve");j.appendChild(oe);let F=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");F.type="button",F.style.backgroundColor=o?.denyButtonColor??"transparent",F.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",F.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,F.setAttribute("data-approval-action","deny");let $=ie("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);$&&($.style.marginRight="4px",F.appendChild($));let X=document.createTextNode(o?.denyLabel??"Deny");F.appendChild(X),x.append(j,F),u.appendChild(x)}return a.append(l,u),s.appendChild(a),s};var sy=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),yu=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Do=(e,t)=>{yu(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},ay=e=>e?.approval!==!1?e?.approval:void 0,iy=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Bo.get(e)??n==="expanded"},Pl=e=>{let t=h("span","persona-approval-kbd");return t.textContent=e,t},ly=(e,t)=>{let n=h("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Nn)?Gr(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??oi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.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},cy=e=>{let t=h("div","persona-approval-resolved"),n=ie("ban",15,"currentColor",2);n&&t.appendChild(n);let o=h("span","persona-approval-resolved-name");return o.textContent=e.toolName?oi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},dy=(e,t,n,o,r,s,a)=>{let l=h("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.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&&iy(t.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 R=h("span","persona-approval-logo"),B=ie("shield-check",16,"currentColor",2);B&&R.appendChild(B),C.appendChild(R);let L=ly(n,o);if(u){let j=h("span","persona-approval-toggle");j.setAttribute("aria-hidden","true");let U=ie("chevron-down",14,"currentColor",2);U&&j.appendChild(U),L.append(" "),L.appendChild(j)}C.appendChild(L),l.appendChild(C);let E=h("div","persona-approval-body");if(u){let j=h("div","persona-approval-details");if(j.setAttribute("data-role","params"),j.hidden=!w,d){let U=h("p","persona-approval-desc");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,j.appendChild(U)}if(c){let U=h("pre","persona-approval-params");o?.parameterBackgroundColor&&(U.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.textContent=io(n.parameters),j.appendChild(U)}E.appendChild(j)}if(n.reason){let j=h("p","persona-approval-reason");o?.reasonColor?j.style.color=o.reasonColor:o?.descriptionColor&&(j.style.color=o.descriptionColor);let U=h("span","persona-approval-reason-label");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,j.append(U,document.createTextNode(n.reason)),E.appendChild(j)}let M=h("div","persona-approval-actions"),_=null,G=j=>{o?.approveButtonColor&&(j.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(j.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 j=h("div","persona-approval-split"),U=h("button","persona-approval-primary");U.type="button",U.setAttribute("data-action","always"),G(U),U.append(o?.approveLabel??"Always allow",Pl("\u23CE"));let oe=h("button","persona-approval-caret");oe.type="button",oe.setAttribute("data-action","toggle-menu"),oe.setAttribute("aria-label","More options"),G(oe);let F=ie("chevron-down",15,"currentColor",2);F&&oe.appendChild(F),j.append(U,oe),M.append(j,x),x.append(Pl("Esc"));let $=h("div","persona-approval-menu"),X=h("button","persona-approval-menu-item");X.type="button",X.append("Allow once",Pl("\u2318\u23CE")),$.appendChild(X),_=fd({anchor:j,content:$,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,_),X.addEventListener("click",()=>{Do(e,t.id),r()})}else{let j=h("button","persona-approval-primary persona-approval-primary--solo");j.type="button",j.setAttribute("data-action","allow"),G(j),j.append(o?.approveLabel??"Allow"),M.append(j,x)}return E.appendChild(M),l.appendChild(E),l.addEventListener("click",j=>{let U=j.target instanceof Element?j.target.closest("[data-action]"):null;if(!U)return;let oe=U.getAttribute("data-action");if(oe==="toggle-params"){let F=l.querySelector('[data-role="params"]');if(F){let $=F.hidden;F.hidden=!$,C.setAttribute("aria-expanded",$?"true":"false"),C.setAttribute("aria-label",$?v:f),Bo.set(t.id,$)}return}if(oe==="toggle-menu"){_?.toggle();return}if(oe==="always"){Do(e,t.id),r({remember:!0});return}if(oe==="allow"){Do(e,t.id),r();return}if(oe==="deny"){Do(e,t.id),s();return}}),l},bu=()=>{let e=sy();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=ay(a);if(l.status!=="pending"){if(Do(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return cy(l)}yu(e,o.id);let d=p?.enableAlwaysAllow===!0,c=dy(e,o,l,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=w=>{gd(w)||o.id===e.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),Do(e,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Do(e,o);e.latestPendingApprovalId=null}}};var vu=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,l,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(s?s.getMessages():[])).some(R=>R.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&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let v=JSON.stringify(r);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Cs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;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=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}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 As=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,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,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},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((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var py=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),uy=new Set(["step_start","execution_start"]),fy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),gy=new Set(["step_complete","agent_turn_complete"]),my=new Set(["flow_complete","agent_complete"]),wu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Cu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Fo=(e,t)=>{let n=e[t];return Cu(n)?n:void 0};function Il(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function si(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function hy(e,t){return typeof t.type=="string"?t.type:e}function yy(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function by(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function xu(e){let t=Fo(e,"result"),n=[Fo(e,"tokens"),Fo(e,"totalTokens"),t?Fo(t,"tokens"):void 0,Fo(e,"usage"),t?Fo(t,"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(e.outputTokens)??rn(e.completionTokens)??(t?rn(t.outputTokens)??rn(t.completionTokens):void 0)}function vy(e){let t=Fo(e,"result");return rn(e.executionTime)??rn(e.executionTimeMs)??rn(e.execution_time)??rn(e.duration)??(t?rn(t.executionTime)??rn(t.executionTimeMs):void 0)}function wy(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ss=class{constructor(t=wy){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:si(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!Cu(n)){wu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=hy(t,n),r=this.now();if(py.has(o)){this.startRun(r);return}if(uy.has(o)){this.run||this.startRun(r);return}if(fy.has(o)){if(!by(o,n))return;let s=yy(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+Il(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:si(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(gy.has(o)){if(!this.run)return;let s=this.run,a=xu(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+Il(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:si(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(my.has(o)){if(!this.run)return;let s=this.run,a=xu(n),l=a??s.exactOutputTokens+Il(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:si(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(wu.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:vy(n)??o-t.startedAt}};function br(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var xy={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)"}},Cy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ay=["flowName","stepName","reasoningText","text","name","tool","toolName"],Sy=100;function Ty(e,t){let n={...xy,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Cy}function My(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Ey(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function ky(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){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 Ly(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Py(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Iy(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Ry(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Wy(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,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 Rl(e,t,n,o,r,s,a,l){let p=r.has(e.id),d=h("div","persona-border-b persona-border-persona-divider persona-text-xs");br(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.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",e.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=ie(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&v.appendChild(C);let R=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";R.textContent=B==="relative"?My(e.timestamp,n):Ey(e.timestamp);let L=null;o.showSequenceNumbers!==!1&&(L=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(t+1));let E=Ty(e.type,o.badgeColors),M=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");M.style.backgroundColor=E.bg,M.style.color=E.text,M.style.borderColor=E.text+"50",M.textContent=e.type;let _=o.descriptionFields??Ay,G=ky(e.payload,_),x=null;G&&(x=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),x.textContent=G);let j=h("div","persona-flex-1 persona-min-w-0"),U=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"),oe=ie("clipboard","12px","currentColor",1.5);return oe&&U.appendChild(oe),U.addEventListener("click",async F=>{F.stopPropagation(),await Ly(Py(e)),U.innerHTML="";let $=ie("check","12px","currentColor",1.5);$&&U.appendChild($),setTimeout(()=>{U.innerHTML="";let X=ie("clipboard","12px","currentColor",1.5);X&&U.appendChild(X)},1500)}),f.appendChild(v),f.appendChild(R),L&&f.appendChild(L),f.appendChild(M),x&&f.appendChild(x),f.appendChild(j),f.appendChild(U),w.appendChild(f),p&&w.appendChild(Wy(e,a,l)),w}}function Au(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,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:t.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");br(C,v?.panel);let R=[],B="",L="",E=null,M=[],_={},G=0,x=_a(),j=0,U=0,oe=!1,F=null,$=!1,X=0,me=new Set,he=new Map,Ae="",Z="",ce=null,ee,le,Y,pe,xe=null,ye=null,ve=null;function je(){let H=h("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),z=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(br(z,v?.headerBar),a){ye=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ye.style.cursor="help",xe=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"),xe.textContent="-- tok/s",ve=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"),ve.style.display="none",ve.style.pointerEvents="none";let Fe=ye,Rt=ve,di=()=>{if(!Rt.textContent)return;let Ls=Fe.getBoundingClientRect(),Ps=H.getBoundingClientRect();Rt.style.left=`${Ls.left-Ps.left}px`,Rt.style.top=`${Ls.bottom-Ps.top+4}px`,Rt.style.display="block"},go=()=>{Rt.style.display="none"};ye.addEventListener("mouseenter",di),ye.addEventListener("mouseleave",go),ye.appendChild(xe)}let J=h("div","persona-flex-1");ee=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 qe=h("option","");qe.value="",qe.textContent="All events (0)",ee.appendChild(qe),le=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"),le.type="button",le.title="Copy All";let Je=ie("clipboard-copy","12px","currentColor",1.5);Je&&le.appendChild(Je);let rt=h("span","persona-event-copy-all persona-text-xs");rt.textContent="Copy All",le.appendChild(rt),ye&&z.appendChild(ye),z.appendChild(J),z.appendChild(ee),z.appendChild(le);let V=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");br(V,v?.searchBar);let _e=ie("search","14px","var(--persona-muted, #9ca3af)",1.5),be=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");_e&&be.appendChild(_e),Y=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"),br(Y,v?.searchInput),Y.type="text",Y.placeholder="Search event payloads...",pe=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"),pe.type="button",pe.style.display="none";let $e=ie("x","12px","currentColor",2);return $e&&pe.appendChild($e),V.appendChild(be),V.appendChild(Y),V.appendChild(pe),H.appendChild(z),H.appendChild(V),ve&&H.appendChild(ve),H}let Me,De=s.find(H=>H.renderEventStreamToolbar);De?.renderEventStreamToolbar&&r?Me=De.renderEventStreamToolbar({config:r,defaultRenderer:()=>je(),eventCount:t.getSize(),filteredCount:0,onFilterChange:z=>{B=z,et(),se()},onSearchChange:z=>{L=z,et(),se()}})??je():Me=je();let Qe=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");Qe.style.display="none";function Ve(){if(!a||!xe||!ye)return;let H=a(),z=Iy(H);xe.textContent=z;let J=Ry(H);ve&&(ve.textContent=J,J||(ve.style.display="none")),ye.setAttribute("aria-label",J?`Throughput: ${z}, ${J}`:`Throughput: ${z}`)}let Te=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Le=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Le.style.height="100%";let Xe=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");br(Xe,v?.scrollIndicator),Xe.style.display="none",Xe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Ht=ie(d,"14px","currentColor",2);Ht&&Xe.appendChild(Ht);let It=h("span","");It.textContent=c,Xe.appendChild(It);let qt=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");qt.style.display="none",Te.appendChild(Le),Te.appendChild(qt),Te.appendChild(Xe),C.setAttribute("tabindex","0"),C.appendChild(Me),C.appendChild(Qe),C.appendChild(Te);function xt(){let H=t.getAll(),z={};for(let V of H)z[V.type]=(z[V.type]||0)+1;let J=Object.keys(z).sort(),qe=J.length!==M.length||!J.every((V,_e)=>V===M[_e]),Re=!qe&&J.some(V=>z[V]!==_[V]),Je=H.length!==Object.values(_).reduce((V,_e)=>V+_e,0);if(!qe&&!Re&&!Je||(M=J,_=z,!ee))return;let rt=ee.value;if(ee.options[0].textContent=`All events (${H.length})`,qe){for(;ee.options.length>1;)ee.remove(1);for(let V of J){let _e=h("option","");_e.value=V,_e.textContent=`${V} (${z[V]||0})`,ee.appendChild(_e)}rt&&J.includes(rt)?ee.value=rt:rt&&(ee.value="",B="")}else for(let V=1;V<ee.options.length;V++){let _e=ee.options[V];_e.textContent=`${_e.value} (${z[_e.value]||0})`}}function He(){let H=t.getAll();if(B&&(H=H.filter(z=>z.type===B)),L){let z=L.toLowerCase();H=H.filter(J=>J.type.toLowerCase().includes(z)||J.payload.toLowerCase().includes(z))}return H}function de(){return B!==""||L!==""}function et(){G=0,j=0,x.resume(),Xe.style.display="none"}function Ie(H){me.has(H)?me.delete(H):me.add(H),ce=H;let z=Le.scrollTop,J=x.isFollowing();$=!0,x.pause(),se(),Le.scrollTop=z,J&&x.resume(),$=!1}function fe(){return uo(Le,50)}function se(){U=Date.now(),oe=!1,Ve(),xt();let H=t.getEvictedCount();H>0?(Qe.textContent=`${H.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",R=He();let z=R.length,J=t.getSize()>0;z===0&&J&&de()?(qt.textContent=L?`No events matching '${L}'`:"No events matching filter",qt.style.display="",Le.style.display="none"):(qt.style.display="none",Le.style.display=""),le&&(le.title=de()?`Copy Filtered (${z})`:"Copy All"),p&&!x.isFollowing()&&z>G&&(j+=z-G,It.textContent=c?`${c}${j>0?` (${j})`:""}`:"",Xe.style.display=""),G=z;let qe=t.getAll(),Re=qe.length>0?qe[0].timestamp:0,Je=new Set(R.map(_e=>_e.id));for(let _e of me)Je.has(_e)||me.delete(_e);let rt=B!==Ae||L!==Z,V=he.size===0&&R.length>0;if(rt||V||R.length===0){Le.innerHTML="",he.clear();let _e=document.createDocumentFragment();for(let be=0;be<R.length;be++){let $e=Rl(R[be],be,Re,u,me,Ie,s,r);he.set(R[be].id,$e),_e.appendChild($e)}Le.appendChild(_e),Ae=B,Z=L,ce=null}else{if(ce!==null){let be=he.get(ce);if(be&&be.parentNode===Le){let $e=R.findIndex(Fe=>Fe.id===ce);if($e>=0){let Fe=Rl(R[$e],$e,Re,u,me,Ie,s,r);Le.insertBefore(Fe,be),be.remove(),he.set(ce,Fe)}}ce=null}let _e=new Set(R.map(be=>be.id));for(let[be,$e]of he)_e.has(be)||($e.remove(),he.delete(be));for(let be=0;be<R.length;be++){let $e=R[be];if(!he.has($e.id)){let Fe=Rl($e,be,Re,u,me,Ie,s,r);he.set($e.id,Fe),Le.appendChild(Fe)}}}x.isFollowing()&&(Le.scrollTop=Le.scrollHeight)}function Pe(){if(Date.now()-U>=Sy){F!==null&&(cancelAnimationFrame(F),F=null),se();return}oe||(oe=!0,F=requestAnimationFrame(()=>{F=null,se()}))}let it=(H,z)=>{if(!le)return;le.innerHTML="";let J=ie(H,"12px","currentColor",1.5);J&&le.appendChild(J);let qe=h("span","persona-text-xs");qe.textContent="Copy All",le.appendChild(qe),setTimeout(()=>{le.innerHTML="";let Re=ie("clipboard-copy","12px","currentColor",1.5);Re&&le.appendChild(Re);let Je=h("span","persona-text-xs");Je.textContent="Copy All",le.appendChild(Je),le.disabled=!1},z)},ue=async()=>{if(le){le.disabled=!0;try{let H;de()?H=R:n?(H=await n(),H.length===0&&(H=t.getAll())):H=t.getAll();let z=H.map(J=>{try{return JSON.parse(J.payload)}catch{return J.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),it("check",1500)}catch{it("x",1500)}}},Ce=()=>{ee&&(B=ee.value,et(),se())},te=()=>{!Y||!pe||(pe.style.display=Y.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{L=Y.value,et(),se()},150))},S=()=>{!Y||!pe||(Y.value="",L="",pe.style.display="none",E&&clearTimeout(E),et(),se())},D=()=>{if($)return;let H=Le.scrollTop,{action:z,nextLastScrollTop:J}=$a({following:x.isFollowing(),currentScrollTop:H,lastScrollTop:X,nearBottom:fe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});X=J,z==="resume"?(x.resume(),j=0,Xe.style.display="none"):z==="pause"&&(x.pause(),p&&(It.textContent=c,Xe.style.display=""))},y=H=>{let z=za({following:x.isFollowing(),deltaY:H.deltaY,nearBottom:fe(),resumeWhenNearBottom:!0});z==="pause"?(x.pause(),p&&(It.textContent=c,Xe.style.display="")):z==="resume"&&(x.resume(),j=0,Xe.style.display="none")},P=()=>{p&&(Le.scrollTop=Le.scrollHeight,x.resume(),j=0,Xe.style.display="none")},T=H=>{let z=H.target;if(!z||z.closest("button"))return;let J=z.closest("[data-event-id]");if(!J)return;let qe=J.getAttribute("data-event-id");qe&&Ie(qe)},I=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),Y?.focus(),Y?.select();return}H.key==="Escape"&&(Y&&document.activeElement===Y?(S(),Y.blur(),C.focus()):o&&o())};le&&le.addEventListener("click",ue),ee&&ee.addEventListener("change",Ce),Y&&Y.addEventListener("input",te),pe&&pe.addEventListener("click",S),Le.addEventListener("scroll",D),Le.addEventListener("wheel",y,{passive:!0}),Le.addEventListener("click",T),Xe.addEventListener("click",P),C.addEventListener("keydown",I);function q(){E&&clearTimeout(E),F!==null&&(cancelAnimationFrame(F),F=null),oe=!1,he.clear(),le&&le.removeEventListener("click",ue),ee&&ee.removeEventListener("change",Ce),Y&&Y.removeEventListener("input",te),pe&&pe.removeEventListener("click",S),Le.removeEventListener("scroll",D),Le.removeEventListener("wheel",y),Le.removeEventListener("click",T),Xe.removeEventListener("click",P),C.removeEventListener("keydown",I)}return{element:C,update:Pe,destroy:q}}}function Su(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.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&&t.onSelect(f)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.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(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Tu(e,t){let n=e.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=te=>({start:te===!1?!1:typeof te=="object"&&te?te.start!==!1:!0,end:te===!1?!1:typeof te=="object"&&te?te.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"),$?.hide()};w&&w.addEventListener("click",()=>{f(),t.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 R=h("span","persona-text-xs persona-font-medium persona-truncate");R.textContent=s;let B=Pt({icon:"x",label:a});B.addEventListener("click",()=>{f(),t.onDismiss?.()});let L="rendered",E=Ba({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:te=>{L=te==="source"?"source":"rendered",it()}}),M=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),_=n?.documentToolbarShowCopyLabel===!0,G=n?.documentToolbarShowCopyChevron===!0,x=n?.documentToolbarCopyMenuItems,j=!!(G&&x&&x.length>0),U=null,oe,F=null,$=null;if(r&&(_||G)&&!j){if(oe=_?Wo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G){let te=ie("chevron-down",14,"currentColor",2);te&&oe.appendChild(te)}}else r&&j?(U=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),oe=_?Wo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),F=Pt({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"}}),U.append(oe,F)):r?oe=Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(oe=Pt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&oe.classList.add("persona-hidden"));let X=r?Pt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"refresh-cw",label:"Refresh"}),me=r?Pt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Pt({icon:"x",label:a}),he=Pt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&he.classList.add("persona-hidden");let Ae=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),Z=e.features?.artifacts?.toolbarActions??[],ce=()=>{let te=Te.find(P=>P.id===Le)??Te[Te.length-1],S=te?.id??null,D=te?.artifactType==="markdown"?te.markdown??"":"",y=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:D,jsonPayload:y,id:S}},ee=async()=>{let te=Te.find(S=>S.id===Le)??Te[Te.length-1];try{await navigator.clipboard.writeText(fs(te))}catch{}};if(oe.addEventListener("click",async()=>{let te=n?.onDocumentToolbarCopyMenuSelect;if(te&&j){let{markdown:S,jsonPayload:D,id:y}=ce();try{await te({actionId:"primary",artifactId:y,markdown:S,jsonPayload:D})}catch{}return}await ee()}),F&&x?.length){let te=()=>v.closest("[data-persona-root]")??document.body,S=()=>{$=fr({items:x.map(D=>({id:D.id,label:D.label})),onSelect:async D=>{let{markdown:y,jsonPayload:P,id:T}=ce(),I=n?.onDocumentToolbarCopyMenuSelect;try{I?await I({actionId:D,artifactId:T,markdown:y,jsonPayload:P}):D==="markdown"||D==="md"?await navigator.clipboard.writeText(y):D==="json"||D==="source"?await navigator.clipboard.writeText(P):await navigator.clipboard.writeText(y||P)}catch{}},anchor:U??F,position:"bottom-right",portal:te()})};v.isConnected?S():requestAnimationFrame(S),F.addEventListener("click",D=>{D.stopPropagation(),$?.toggle()})}X.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}it()}),me.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=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(),U?M.append(U,X,me):M.append(oe,X,me),M.insertBefore(Ae,me),M.insertBefore(he,me),C.append(E.element,le,M);else{let te=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");te.append(oe,Ae,he,B),C.appendChild(R),C.appendChild(te)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let Y=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&&Y.style.setProperty("--persona-artifact-tab-fade-size",p);let pe=e.features?.artifacts?.renderTabBar,xe=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ye=Su(Y,{onSelect:te=>t.onSelect(Te[te].id)}),ve=te=>{let S=te.scrollWidth-te.clientWidth,D=S>1,y=Math.abs(te.scrollLeft);te.classList.toggle("persona-artifact-tab-fade-start",c&&D&&y>1),te.classList.toggle("persona-artifact-tab-fade-end",u&&D&&y<S-1)},je=0,Me=()=>{if(je)return;let te=()=>{je=0,ve(Y)};je=typeof requestAnimationFrame=="function"?requestAnimationFrame(te):setTimeout(te,0)};Y.addEventListener("scroll",()=>Me(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ve(Y)).observe(Y);let De=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Qe=()=>{De.scrollLeft=0},Ve=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Qe):setTimeout(Qe,0)};if(l){for(let te of[Y,xe])te.style.paddingLeft=l,te.style.paddingRight=l;De.style.padding=l}v.appendChild(C),v.appendChild(Y),v.appendChild(xe),v.appendChild(De);let Te=[],Le=null,Xe=!1,Ht=!1,It=!0,qt=!1,xt=null,He="",de=null,et=!1,Ie=te=>te.artifactType==="markdown"&&!!te.file||r?L:"rendered",fe=te=>{r||(te&&!et?(C.insertBefore(E.element,R),et=!0):!te&&et&&(E.element.remove(),et=!1))},se=()=>Le&&Te.find(te=>te.id===Le)||Te[Te.length-1],Pe=()=>{let te=ps(se());if(!te){Ae.replaceChildren();return}let S=Z.filter(D=>D.visible===void 0||D.visible(te)).map(D=>gr(D,{documentChrome:r,onClick:()=>{let y=ps(se());if(y)try{Promise.resolve(D.onClick(y)).catch(()=>{})}catch{}}}));Ae.replaceChildren(...S)},it=()=>{Pe();let te=r&&Te.length<=1,S=!!pe;if(Y.classList.toggle("persona-hidden",te||S),xe.classList.toggle("persona-hidden",te||!S),S&&pe){let P=Te.map(T=>T.id).join("|")+" "+(Le??"");if(P!==He){He=P;let T=pe({records:Te,selectedId:Le,onSelect:t.onSelect});xe.firstElementChild!==T&&xe.replaceChildren(T)}}else{ye.beforeRender(),Y.replaceChildren();let P=[],T=-1;for(let[I,q]of Te.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 z=q.artifactType==="markdown"?q.file:void 0,J=z?Mn(z.path):q.title||q.id.slice(0,8),qe=z?.path||q.title||J;H.textContent=J,H.title=qe,H.setAttribute("aria-label",qe),q.id===Le&&(H.classList.add("persona-bg-persona-container","persona-border-persona-border"),T=I),H.addEventListener("click",()=>t.onSelect(q.id)),Y.appendChild(H),P.push(H)}if(ye.render(P,T),T>=0&&Le!==xt){xt=Le;let I=P[T];typeof I.scrollIntoView=="function"&&I.scrollIntoView({block:"nearest",inline:"nearest"})}ve(Y)}let D=Le&&Te.find(P=>P.id===Le)||Te[Te.length-1];if(!D){De.replaceChildren(),de=null,fe(!1);return}let y=D.artifactType==="markdown"?D.file:void 0;if(fe(!!y),r){let P=y?lo(y):D.artifactType==="markdown"?"MD":D.component??"Component",T=(D.title||"Document").trim(),I=y?Mn(y.path):T.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${I} \xB7 ${P}`}else R.textContent=y?Mn(y.path):s;de?(de.el.parentElement!==De&&De.replaceChildren(de.el),de.update(D)):(de=Na(D,{config:e,resolveViewMode:Ie}),De.replaceChildren(de.el)),De.classList.toggle("persona-artifact-content-flush",!!De.querySelector(".persona-code-pre"))},ue=()=>{let te=Te.length>0;if(v.classList.toggle("persona-hidden",!te),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;te&&y&&Xe?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},Ce=()=>{qt=!1,it(),ue()};return{element:v,backdrop:w,update(te){let S=te.selectedId??te.artifacts[te.artifacts.length-1]?.id??null,D=S!==Le;Te=te.artifacts,Le=S,Te.length>0&&(Xe=!0),qt=!0,It&&Ce(),D&&Qe()},setMobileOpen(te){Xe=te,!te&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):ue()},setExpanded(te){te!==Ht&&(Ht=te,Ve());let S=ie(te?"minimize":"maximize",16,"currentColor",2);S&&he.replaceChildren(S);let D=te?"Collapse artifacts panel":"Expand artifacts panel";he.setAttribute("aria-label",D),he.title=D},setExpandToggleVisible(te){he.classList.toggle("persona-hidden",!te)},setCopyButtonVisible(te){r||oe.classList.toggle("persona-hidden",!te)},setCustomActions(te){Z=te,Pe()},setTabFade(te){let S=d(te);S.start===c&&S.end===u||(c=S.start,u=S.end,ve(Y))},setRenderTabBar(te){te!==pe&&(pe=te,He="",it())},setVisible(te){te!==It&&(It=te,te&&qt&&Ce())}}}function Xt(e){return e?.features?.artifacts?.enabled===!0}function Mu(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Hy(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Eu=["panel","seamless","detached"];function Wl(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Eu.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Hl(e){return!e||!Xt(e)?!1:Wl(e)==="detached"}function Ts(e,t){if(!Xt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Hy(e),Mu(e,t);return}let n=t.features?.artifacts?.layout,o=Wl(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Mu(e,t)}function Ms(e,t){for(let l of Eu)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=Wl(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function ku(e,t){return!t||!Xt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var By=new Set(["__proto__","prototype","constructor"]),Dy=new Set(["collapsed","card","panel","inline"]),Lu=new Set(["markdown","component"]),Fy=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,No=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ii=e=>!By.has(e),Bl=e=>typeof e=="string"&&Dy.has(e),Oo=e=>Object.keys(e).length>0;function kn(e,t,n,o){e.push({path:t,code:n,message:o})}var Ny="Ignored because this key is not part of the persisted preference schema.",ai="Ignored an unsupported value.",Oy="Expected collapsed, panel, or inline.",_y='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Pu={kind:"mode",message:ai},vr={kind:"string",message:"Expected a CSS length string."},jn={kind:"boolean"},$y={paneWidth:vr,paneMaxWidth:vr,paneMinWidth:vr,expandedPanelWidth:vr,resizableMinWidth:vr,resizableMaxWidth:vr,expandLauncherPanelWhenOpen:jn,resizable:jn},zy={kind:"object",message:"Expected a preference object.",children:{showToolCalls:jn,showReasoning:jn,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:ai},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:ai},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:ai},expandable:jn,grouped:jn}},reasoningDisplay:{kind:"object",children:{expandable:jn,activePreview:jn}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Pu,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Pu,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Lu,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Lu}}},filePreview:{kind:"object",children:{enabled:jn}},layout:{kind:"object",children:$y}}}}};function Iu(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:kn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:kn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:kn(o,n,"invalid_value",t.message);case"mode":return Bl(e)?un(e):kn(o,n,"invalid_value",t.message);case"modeMap":{if(!No(e))return kn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let p=r?a:er(a);ii(a)&&(r?r.has(a):Fy.test(p))?Bl(l)?s[p]=un(l):kn(o,`${n}.${a}`,"invalid_value",Oy):kn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":_y)}return Oo(s)?s:void 0}case"object":{if(t.bareMode&&Bl(e))return un(e);if(!No(e))return kn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!ii(l)||!r.includes(l))&&kn(o,s(l),"unknown_key",Ny);let a={};for(let l of r){let p=t.children[l],d=Iu(e[l],p,s(l),o);if(p.deprecated&&e[l]!==void 0&&kn(o,s(l),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??l,u=a[c];a[c]=No(u)&&No(d)?{...u,...d}:d}return Oo(a)?a:void 0}}}function jy(e){let t=[];return{preferences:(e===null?void 0:Iu(e,zy,"",t))??{},issues:t}}function wr(e){if(Array.isArray(e))return e.map(wr);if(!No(e))return e;let t={};for(let[n,o]of Object.entries(e))ii(n)&&o!==void 0&&(t[n]=wr(o));return t}function Ru(e,t){let n=wr(e);for(let[o,r]of Object.entries(t)){if(!ii(o)||r===void 0)continue;let s=n[o];n[o]=No(s)&&No(r)?Ru(s,r):wr(r)}return n}function Uy(e){let t={},n;for(let r of e){let s=jy(r).preferences;n=Wu(n,s.artifacts?.display),t=Ru(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Vy(e,t){if(t===void 0)return e===void 0?void 0:wr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...Oo(r)?{byMediaType:r}:{}};return Oo(s)?s:void 0}function Wu(e,t){if(t===void 0)return e===void 0?void 0:wr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=Vy(n.files,t.files),a={...o?{default:o}:{},...Oo(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Oo(a)?a:void 0}function qy(e={},t){let n=Uy(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=Wu(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Dl(e){let t=e.preferences;return!t||!Oo(t)?e:{...e,features:qy(e.features??{},[t])}}function Ky(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Gy(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Qy(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Xy(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Fl(e,t){let o=(t.getComputedStyle(e).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 Hu(e,t,n,o,r,s){let a=Ky(r,200),l=Xy(t,n,o,200);l=Math.max(a,l);let p=Gy(s);return p!==null&&(l=Math.min(l,p)),Qy(e,a,l)}var Bu={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"}},Nl=(e,t,n,o)=>{let r=e.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=Bu[a]??Bu.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=`${t.id}-${a}-${v.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=v.label,C.appendChild(R);let B=v.type??"text",L;B==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=B),L.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",L.id=`${t.id}-${a}-${v.name}`,L.name=v.name,L.placeholder=v.placeholder??"",v.required&&(L.required=!0),C.appendChild(L),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",R=new FormData(c),B={};R.forEach((L,E)=>{B[E]=L}),B.type=a,f.disabled=!0,w.textContent="Submitting\u2026";try{let L=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let E=await L.json();w.textContent=E.message??"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(L){w.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Ol=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},_l=new Ol;var Du=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jy=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Fu=(e,t,n)=>{if(!Du(e)||!Du(t)||Jy.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Fu(e[r],t[r],s)}return o};function Nu(e,t){let n=Fu(e,t,"");return ka(n)}var Ou=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var Yy=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Zy=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},zl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Yy(e),n=Zy(t);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}},$l=e=>typeof e=="string"?e:e==null?"":String(e),Es={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:$l(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=$l(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:$l(n.text)}}},_u=e=>Array.isArray(e)?e.map(t=>String(t)):[],jl=e=>{let t=new Set(_u(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(_u(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let p={action:l,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.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 eb=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},tb=e=>e.map(t=>({...t,streaming:!1})),nb=e=>e.map(t=>({...t,status:"complete"})),$u=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?eb(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?tb(n.messages):void 0,artifacts:n.artifacts?nb(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as $A,STR as zA,OBJ as jA}from"partial-json";function zu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=zn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.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(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function ju(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Ul(e){let t=ju(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Uu(e){let t=ju(e);if(!t)return null;try{let n=JSON.parse(t);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:t}}}catch{}return null}var ob=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vu(e){let{onSubmit:t,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=ob}=e,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 R=document.createElement("div");R.className="persona-feedback-rating persona-feedback-rating-csat",R.setAttribute("role","radiogroup"),R.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let G=1;G<=5;G++){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",`${G} star${G>1?"s":""}: ${d[G-1]}`),x.title=d[G-1],x.dataset.rating=String(G),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=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 Eu(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((le,ge)=>{le.classList.toggle("selected",ge===D),le.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 fr="persona-chat-history",My=30*1e3,Ey=641,ky={"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 Ly(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=ky[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 Ja(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 Py(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 Iy(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Il=t=>!t||typeof t!="object"?{}:{...t},ku=t=>t.map(e=>({...e,streaming:!1})),Lu=(t,e,n)=>{let o=t?.markdown?Zs(t.markdown):null,r=ea(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?rd(a):a,u=o(c);d=r&&p?r(u):u}else d=Zn(a);return d}};function Pu(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 Ry=(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},Wy=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:Ry(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Iu=(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=va(e),r=Ml.getForInstance(o.plugins),{plugin:s,teardown:a}=ru();o.components&&On.registerAll(o.components);let l=wu(),d=o.persistState===!1?null:o.storageAdapter??Cu(),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=Il(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})??{},fi()},I=o.actionParsers&&o.actionParsers.length?o.actionParsers:[kl],B=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[bs.message,bs.messageAndClick],k=Ll({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=()=>ds(o),D=()=>M||J(),F=J()?!1:M?P:!0,le=!1,ge=null,Ce=()=>{le=!0,ge&&clearTimeout(ge),ge=setTimeout(()=>{le&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),le=!1)},1e4)},we=Lu(o,k,Ce),ee=o.features?.showReasoning??!0,ce=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,ie=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,pe=Y?new gs(ye):null,Te=o.features?.eventStream?.maxEvents??2e3,Ae=Y?new fs(Te,pe):null,$e=Y?new ms:null,Fe=null,ot=!1,Qe=null,He=0;pe?.open().then(()=>Ae?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Ee={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)}},Xe=o.statusIndicator??{},on=i=>i==="idle"?Xe.idleText??Pt.idle:i==="connecting"?Xe.connectingText??Pt.connecting:i==="connected"?Xe.connectedText??Pt.connected:i==="error"?Xe.errorText??Pt.error:i==="paused"?Xe.pausedText??Pt.paused:i==="resuming"?Xe.resumingText??Pt.resuming:Pt[i];function St(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 ht=Vp({config:o,showClose:D()}),{wrapper:Be,panel:me,pillRoot:Ke}=ht.shell,Le=ht.panelElements,{container:ue,body:ae,messagesWrapper:be,suggestions:yt,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:qe}=Le,ke=Le.leftActions,rt=Le.setSendButtonMode,V=Le.micButton,ze=Le.micButtonWrapper,Se=Le.attachmentButton,We=Le.attachmentButtonWrapper,Pe=Le.attachmentInput,Je=Le.attachmentPreviewsContainer;ue.classList.add("persona-relative"),ae.classList.add("persona-relative");let lo=12,co=()=>ie.label??"",Za=()=>ie.iconName??"arrow-down",ws=()=>ie.enabled!==!1,Ut=()=>Z.mode??"anchor-top",_n=()=>Ut()==="follow"||Ut()==="anchor-top"&&Sr,Nl=()=>Z.anchorTopOffset??16,Uu=()=>Z.restorePosition??"bottom",Ol=()=>Z.pauseOnInteraction===!0,_l=()=>Z.showActivityWhilePinned!==!1,$l=()=>Z.announce===!0,Mt=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");Mt.type="button",Mt.style.display="none",Mt.setAttribute("data-persona-scroll-to-bottom","true");let mr=h("span","persona-flex persona-items-center"),ei=h("span",""),po=h("span","");po.setAttribute("data-persona-scroll-to-bottom-count",""),po.style.display="none",Mt.append(mr,ei,po),ue.appendChild(Mt);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",ae.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 hr=null,xs=null,zl=i=>{!$l()||!i||(xs=i,hr===null&&(hr=setTimeout(()=>{hr=null,xs&&$l()&&(uo.textContent=xs),xs=null},400)))},Bo=()=>{let g=$.style.display==="none"?0:$.offsetHeight;Mt.style.bottom=`${g+lo}px`};Bo();let Ul=()=>{let i=!!co();Mt.setAttribute("aria-label",co()||"Jump to latest"),Mt.title=co(),Mt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),mr.innerHTML="";let g=re(Za(),"14px","currentColor",2);g?(mr.appendChild(g),mr.style.display=""):mr.style.display="none",ei.textContent=co(),ei.style.display=i?"":"none"};Ul();let xt=null,Jt=null,jl=null,ql=r.find(i=>i.renderHeader);if(ql?.renderHeader){let i=ql.renderHeader({config:o,defaultRenderer:()=>{let g=Io({config:o,showClose:D()});return ps(ue,g,o),g.header},onClose:()=>ct(!1,"user")});if(i){let g=ue.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),H=i,ht.header.element=i)}}let ti=()=>{if(!Ae)return;if(ot=!0,!Fe&&Ae&&(Fe=cu({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>yr(),config:o,plugins:r,getThroughput:()=>$e?.getMetric()??{status:"idle"}})),Fe&&(ae.style.display="none",$.parentNode?.insertBefore(Fe.element,$),Fe.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${Kt.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-He>=200&&(Fe?.update(),He=g),Qe=requestAnimationFrame(i)};He=0,Qe=requestAnimationFrame(i),Zt(),l.emit("eventStream:opened",{timestamp:Date.now()})},yr=()=>{if(ot){if(ot=!1,Fe&&Fe.element.remove(),ae.style.display="",et){et.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&et.classList.remove(g))}Qe!==null&&(cancelAnimationFrame(Qe),Qe=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=Kt.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=Le.clearChatButtonWrapper,A=Le.closeButtonWrapper,L=b||A;L&&L.parentNode===H?H.insertBefore(et,L):H.appendChild(et),et.addEventListener("click",()=>{ot?yr():ti()})}let ju=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)}},Vl=r.find(i=>i.renderComposer);if(Vl?.renderComposer){let i=o.composer,g=Vl.renderComposer({config:o,defaultRenderer:()=>Ka({config:o}).footer,onSubmit:m=>{if(!_||_.isStreaming())return;let b=m.trim(),A=xt?.hasAttachments()??!1;if(!b&&!A)return;Cc();let L;A&&(L=[],L.push(...xt.getContentParts()),b&&L.push(er(b))),_.sendMessage(b,{contentParts:L}),A&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Pe?.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?()=>{jl?.()}:void 0});g&&(ht.replaceComposer(g),$=ht.composer.footer)}let qu=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,ze=L.parentElement),Q&&(T=Q);let N=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(yt=N);let G=g("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(Se=G,We=G.parentElement),Pe=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Je=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),ke=g(".persona-widget-composer__left-actions")};ju($),qu($);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&&yt&&!J()&&(yt.style.maxWidth=zn,yt.style.marginLeft="auto",yt.style.marginRight="auto"),zn&&Je&&!J()&&(Je.style.maxWidth=zn,Je.style.marginLeft="auto",Je.style.marginRight="auto"),o.attachments?.enabled&&Pe&&Je){xt=Jr.fromConfig(o.attachments),xt.setPreviewsContainer(Je),Pe.addEventListener("change",m=>{let b=m.target;xt?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,g=Pu(i);ue.appendChild(g)}let Vu=()=>Jt?.prefetch();if(o.contextMentions?.enabled&&ve&&(Jt=Zd({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];ke?ke.insertBefore(b,ke.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 yt;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=ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");L?L.replaceWith(A):ae.insertBefore(A,ae.firstChild);break}case"body-bottom":ae.appendChild(A);break;case"footer-top":yt.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 Kl=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")dr.has(A)?dr.delete(A):dr.add(A),Jp(A,b);else if(L==="tool")pr.has(A)?pr.delete(A):pr.add(A),Yp(A,b,o);else if(L==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Ro.get(A)??N;Ro.set(A,!G),nu(A,b,o)}ho.delete(A)};be.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Kl(i))}),be.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Kl(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=Ep(A);!L||L===A||(g.setData("text/plain",L),i.preventDefault())});let ni=new Map,Gl=null,Ql="idle",Ku={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Gu=(i,g)=>{let{icon:m,label:b}=Ku[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))},Xl=()=>{be.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let b=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Gu(g,b&&b===Gl?Ql:"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&&Ee.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)}),Ee.onCopy(N)}}else if(L==="read-aloud")_.toggleReadAloud(A);else if(L==="upvote"||L==="downvote"){let N=(ni.get(A)??null)===L,G=L==="upvote"?"thumbs-up":"thumbs-down";if(N){ni.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))}ni.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 je=_.getMessages().find(dt=>dt.id===A);je&&Ee.onFeedback&&Ee.onFeedback({type:L,messageId:je.id,message:je})}}}),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 Ye=null,br=null,vr=()=>{},wr="none",Cs=null,fn={artifacts:[],selectedId:null},Mn=!1,gn=!1,xr=!1,Do=!1,Jl=()=>Do||fn.artifacts.some(i=>To(o.features?.artifacts,i.artifactType)==="panel"),As=()=>fn.artifacts.length>0&&!Mn&&Jl(),it={current:null},oi=(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}=oi(m,b);if(!L)return;let{filename:G,mime:oe,content:fe}=cp({title:Q,markdown:L,file:N}),ne=new Blob([fe],{type:oe}),xe=URL.createObjectURL(ne),je=document.createElement("a");je.href=xe,je.download=G,je.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(dt=>dt.id===b);if(!G)return;let{markdown:oe,title:fe,file:ne,artifactType:xe}=oi(m,Q??""),je={artifactId:Q,title:fe,artifactType:xe,markdown:oe,file:ne};try{Promise.resolve(G.onClick(je)).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=rs(A);else{let{markdown:Q,file:N,artifactType:G}=oi(m,b);G==="markdown"&&(L=rs({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,Do=!0,gn=!0,xr=!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,Do=!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 Fo=Le.composerOverlay,No=(i,g,m)=>{let b=g.trim();if(!b||!it.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})),Yo(Fo,A);let Q=it.current.getMessages().find(N=>N.toolCall?.id===A);Q?.agentMetadata?.awaitingLocalTool?it.current.resolveAskUserQuestion(Q,m.structured??b):it.current.sendMessage(b)},fo=i=>{let g=it.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:ra(i,b),currentIndex:dn(i)})},Yl=i=>Object.entries(i).map(([g,m])=>`${g}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),ri=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=dn(i),m=Jo(i);if(g>=m-1)return;let b=it.current?.getMessages().find(A=>A.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(aa(i,b,o,g+1),fo(i))};Fo.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})),Yo(Fo,L);let Q=it.current?.getMessages().find(N=>N.toolCall?.id===L);Q?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(Q),it.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=Eo(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),ri(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=Oi(b).length===0);return}No(b,L,{source:"pick",values:[L]});return}if(A==="submit-multi"){let L=Oi(b);if(L.length===0)return;No(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),ri(b);return}No(b,Q,{source:"free-text"});return}if(A==="next"||A==="back"){if(!it.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=it.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=Eo(b)[dn(b)];(typeof ne!="string"||ne!==G)&&to(b,G)}let oe=A==="next"?1:-1,fe=dn(b)+oe;aa(b,Q,o,fe),fo(b);return}if(A==="submit-all"){if(!it.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=it.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=ra(b,Q);it.current.persistAskUserQuestionProgress(Q,{answers:oe,currentIndex:dn(b)});let fe=Yl(oe);No(b,fe||"(submitted)",{source:"submit-all",structured:oe});return}if(A==="skip"){if(!it.current)return;let L=b.getAttribute("data-tool-call-id")??"",Q=it.current.getMessages().find(xe=>xe.toolCall?.id===L);if(!Q)return;let N=eo(b),G=dn(b),oe=Jo(b),fe=G>=oe-1;if(!N){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),Yo(Fo,L),Q.agentMetadata?.awaitingLocalTool&&(it.current.markAskUserQuestionResolved(Q),it.current.resolveAskUserQuestion(Q,"(dismissed)"));return}to(b,"");let ne=b.querySelector('[data-ask-free-text-input="true"]');if(ne&&(ne.value=""),fe){let xe=ra(b,Q),je=Yl(xe);No(b,je||"(skipped)",{source:"submit-all",structured:xe});return}aa(b,Q,o,G+1),fo(b);return}}),Fo.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),ri(b);return}No(b,A,{source:"free-text"})}});let Zl=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=Fo.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",Zl);let Un=null,bt=null,Cr=null,Ss=null,si=()=>{},ec=!1,Ts="",Ms="";function ai(){Ss?.(),Ss=null}let tc=()=>{if(!Un||!bt)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){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let b=Un.firstElementChild;if(!b||b===bt)return;let A=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${A}px`,bt.style.zIndex="5";let L=Al(Un,g),Q=b.offsetWidth+L/2-A/2;bt.style.left=`${Math.max(0,Q)}px`},Es=()=>{},Qu=()=>{let i=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>m?!1:M||Wt(o)},ks=()=>!Gt(o)||!As()||t.classList.contains("persona-artifact-narrow-host")||Qu()||(t.ownerDocument.defaultView??window).innerWidth<Ey?"none":Cl(o)?"detached":"welded",En=()=>{if(!Ye||!Gt(o))return;hs(t,o),ys(t,o),Es();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=As();Ye.setVisible(m),Ye.update(fn),Mn?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),gn=!1,xr=!1):fn.artifacts.length>0&&Jl()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),gn=!1,xr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(b),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!xr&&(gn=!1),gn!==ec){let L=Ye.element;gn?(Ts=L.style.width,Ms=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(Ts&&(L.style.width=Ts),Ms&&(L.style.maxWidth=Ms),Ts="",Ms=""),ec=gn}t.classList.toggle("persona-artifact-expanded",gn),Ye.setExpanded(gn);let A=ks();A!==wr&&(wr=A,vr()),si()};if(Gt(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),Ye=pu(o,{onSelect:m=>it.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||(xr=!1),En())}}),Ye.element.classList.add("persona-hidden"),Un=g,g.appendChild(i),g.appendChild(Ye.element),Ye.backdrop&&me.appendChild(Ye.backdrop),me.appendChild(g),si=()=>{if(!Un||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Cr?.(),Cr=null,ai(),bt&&(bt.remove(),bt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!bt){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(!Ye||N.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||L.innerWidth<=640)return;N.preventDefault(),ai();let G=N.clientX,oe=Ye.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,ne=je=>{let dt=Un.getBoundingClientRect().width,tt=t.classList.contains("persona-artifact-welded-split"),en=Al(Un,L),Ct=tt?0:b.getBoundingClientRect().width||6,kt=oe-(je.clientX-G),R=mu(kt,dt,en,Ct,fe?.resizableMinWidth,fe?.resizableMaxWidth);Ye.element.style.width=`${R}px`,Ye.element.style.maxWidth="none",tc()},xe=()=>{A.removeEventListener("pointermove",ne),A.removeEventListener("pointerup",xe),A.removeEventListener("pointercancel",xe),Ss=null;try{b.releasePointerCapture(N.pointerId)}catch{}};Ss=xe,A.addEventListener("pointermove",ne),A.addEventListener("pointerup",xe),A.addEventListener("pointercancel",xe);try{b.setPointerCapture(N.pointerId)}catch{}};b.addEventListener("pointerdown",Q),bt=b,Un.insertBefore(b,Ye.element),Cr=()=>{b.removeEventListener("pointerdown",Q)}}if(bt){let b=As();bt.classList.toggle("persona-hidden",!b),tc()}},Es=()=>{if(!M||!Ye||(o.launcher?.sidebarMode??!1)||Wt(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||!gu(o,M))return;let Q=o.launcher?.width??o.launcherWidth??Nn,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";As()?(me.style.width=N,me.style.maxWidth=N):(me.style.width=Q,me.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(br=new ResizeObserver(()=>{En()}),br.observe(me))}else me.appendChild(ue);J()&&Ke&&(Le.peekBanner&&Ke.appendChild(Le.peekBanner),Ke.appendChild($)),t.appendChild(Be),Ke&&t.appendChild(Ke);let Ls=()=>{if(J()){me.style.width="100%",me.style.maxWidth="100%";let Tt=o.launcher?.composerBar??{},Xt=Be.dataset.state==="expanded",Ks=Tt.expandedSize??"anchored";if(!(Xt&&Ks!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Nr=o.theme?.components?.panel,Gs=rr(o),Vo=(In,So)=>In==null||In===""?So:Vt(Gs,In)??In,Qs="1px solid var(--persona-border)",ki="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ao="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Vo(Nr?.border,Qs),ue.style.borderRadius=Vo(Nr?.borderRadius,Ao),ue.style.boxShadow=Vo(Nr?.shadow,ki),ue.style.overflow="hidden";return}let i=Wt(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=rr(o),N=(Tt,Xt)=>Tt==null||Tt===""?Xt:Vt(Q,Tt)??Tt,G=t.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,ne=G.innerWidth<=fe,xe=oe&&ne&&M,je=i&&oe&&ne,dt=o.launcher?.position??"bottom-left",tt=dt==="bottom-left"||dt==="top-left",en=o.launcher?.zIndex??zt,Ct="var(--persona-panel-border, 1px solid var(--persona-border))",kt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",R="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ie=A&&!xe&&!je;Ie?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Oe=Ie?Ct:g||xe?"none":Ct,Me=Ie?kt: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":kt;i&&!xe&&!Ie&&(Me="none",Oe="none");let At=Ie?R:g||xe?"0":R,pt=N(L?.border,Oe),qt=N(L?.shadow,Me),ut=N(L?.borderRadius,At),Qt=ks(),Lt=Qt==="detached",Re=Qt==="welded";t.classList.toggle("persona-artifact-detached-split",Lt),t.classList.toggle("persona-artifact-welded-split",Re);let _e="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",wt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Gt(o)&&Cl(o)&&b&&!i;t.classList.toggle("persona-artifact-chat-flush",wt);let lt=Lt||wt?"none":qt,ft=Lt?Ct:Re?"none":pt,Ze=Lt?R:ut;wt&&(ft="none",Ze="0");let De=L?.borderRadius!=null&&L.borderRadius!=="",mt=wt&&!De?"0":ut,Ot=ae.scrollTop;t.style.cssText="",Be.style.cssText="",me.style.cssText="",ue.style.cssText="",ae.style.cssText="",$.style.cssText="",ot&&(ae.style.display="none"),(m||b)&&(t.style.minWidth="0");let cn=()=>{if(Ot<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===Ot)return;let Xt=ae.scrollHeight-ae.clientHeight;Xt<=0||(ae.scrollTop=Math.min(Ot,Xt))})};if(xe){Be.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"),Be.style.cssText=`
46
+ `,x.addEventListener("click",()=>{u=G,B.forEach((j,U)=>{let oe=U<G;j.classList.toggle("selected",oe),j.setAttribute("aria-checked",U===G-1?"true":"false")})}),B.push(x),R.appendChild(x)}w.appendChild(R);let L=null;if(p){let G=document.createElement("div");G.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),G.appendChild(L),w.appendChild(G)}let E=document.createElement("div");E.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=l,M.addEventListener("click",()=>{n?.(),c.remove()});let _=document.createElement("button");return _.type="button",_.className="persona-feedback-btn persona-feedback-btn-submit",_.textContent=a,_.addEventListener("click",async()=>{if(u===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let G=L?.value.trim()||void 0;await t(u,G),c.remove()}catch(G){_.disabled=!1,_.textContent=a,console.error("[CSAT Feedback] Failed to submit:",G)}}),E.appendChild(M),E.appendChild(_),w.appendChild(E),c.appendChild(w),c}function qu(e){let{onSubmit:t,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"}=e,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 R=document.createElement("p");R.className="persona-feedback-subtitle",R.textContent=r,v.appendChild(R),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 L=document.createElement("div");L.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=d;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=c,L.appendChild(E),L.appendChild(M);let _=document.createElement("div");_.className="persona-feedback-numbers";let G=[];for(let F=0;F<=10;F++){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 ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{w=F,G.forEach((X,me)=>{X.classList.toggle("selected",me===F),X.setAttribute("aria-checked",me===F?"true":"false")})}),G.push($),_.appendChild($)}B.appendChild(L),B.appendChild(_),f.appendChild(B);let x=null;if(p){let F=document.createElement("div");F.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"),F.appendChild(x),f.appendChild(F)}let j=document.createElement("div");j.className="persona-feedback-actions";let U=document.createElement("button");U.type="button",U.className="persona-feedback-btn persona-feedback-btn-skip",U.textContent=l,U.addEventListener("click",()=>{n?.(),u.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=a,oe.addEventListener("click",async()=>{if(w===null){_.classList.add("persona-feedback-shake"),setTimeout(()=>_.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let F=x?.value.trim()||void 0;await t(w,F),u.remove()}catch(F){oe.disabled=!1,oe.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),j.appendChild(U),j.appendChild(oe),f.appendChild(j),u.appendChild(f),u}var xr="persona-chat-history",rb=30*1e3,sb=641,ab={"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 ib(e){if(!e)return[];let t=[],n=Array.from(e.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){t.push(r);continue}let s=ab[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function li(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function lb(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function cb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Vl=e=>!e||typeof e!="object"?{}:{...e},Ku=e=>e.map(t=>({...t,streaming:!1})),Gu=(e,t,n)=>{let o=e?.markdown?ca(e.markdown):null,r=da(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(t){let c=t.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=Fn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?bd(a):a,u=o(c);d=r&&p?r(u):u}else d=oo(a);return d}};function Qu(e){let t=h("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ie(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=h("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var db=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},pb=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:db(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Xu=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=ka(t),r=o.features;o=Dl(o);let s=_l.getForInstance(o.plugins),{plugin:a,teardown:l}=bu();o.components&&zn.registerAll(o.components);let p=Ou(),c=o.persistState===!1?null:o.storageAdapter??$u(),u={},w=null,f=!1,v=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&&(f=!0),m}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return i};if(c?.load)try{let i=c.load();if(i&&typeof i.then=="function")w=i.then(g=>v(g??{messages:[],metadata:{}}));else{let m=v(i??{messages:[],metadata:{}});m.metadata&&(u=Vl(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=v({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let C=()=>u,R=i=>{u=i({...u})??{},Si()},B=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zl],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Es.message,Es.messageAndClick],E=jl({parsers:B,handlers:L,getSessionMetadata:C,updateSessionMetadata:R,emit:p.emit,documentRef:typeof document<"u"?document:null});E.syncFromMetadata();let M=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,G=o.autoFocusInput??!1,x=_,j=M,U=o.layout?.header?.layout,oe=!1,F=()=>vs(o),$=()=>M||F(),X=F()?!1:M?_:!0,me=!1,he=null,Ae=()=>{me=!0,he&&clearTimeout(he),he=setTimeout(()=>{me&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),me=!1)},1e4)},Z=Gu(o,E,Ae),ce=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,le=o.features?.showEventStreamToggle??!1,Y=o.features?.scrollToBottom??{},pe=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ve=le?new As(ye):null,je=o.features?.eventStream?.maxEvents??2e3,Me=le?new Cs(je,ve):null,De=le?new Ss:null,Qe=null,Ve=!1,Te=null,Le=0;ve?.open().then(()=>Me?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Xe={onCopy:i=>{p.emit("message:copy",i),O?.isClientTokenMode()&&O.submitMessageFeedback(i.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{p.emit("message:feedback",i),O?.isClientTokenMode()&&O.submitMessageFeedback(i.messageId,i.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(i)}},Ht=o.statusIndicator??{},It=i=>i==="idle"?Ht.idleText??Lt.idle:i==="connecting"?Ht.connectingText??Lt.connecting:i==="connected"?Ht.connectedText??Lt.connected:i==="error"?Ht.errorText??Lt.error:i==="paused"?Ht.pausedText??Lt.paused:i==="resuming"?Ht.resumingText??Lt.resuming:Lt[i];function qt(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 xt=au({config:o,showClose:$()}),{wrapper:He,panel:de,pillRoot:et}=xt.shell,Ie=xt.panelElements,{container:fe,body:se,messagesWrapper:Pe,suggestions:it,textarea:ue,sendButton:Ce,sendButtonWrapper:te,composerForm:S,statusText:D,introTitle:y,introSubtitle:P,closeButton:T,iconHolder:I,headerTitle:q,headerSubtitle:H,header:z,footer:J,actionsRow:qe,rightActions:Re}=Ie,Je=Ie.leftActions,rt=Ie.setSendButtonMode,V=Ie.micButton,_e=Ie.micButtonWrapper,be=Ie.attachmentButton,$e=Ie.attachmentButtonWrapper,Fe=Ie.attachmentInput,Rt=Ie.attachmentPreviewsContainer;fe.classList.add("persona-relative"),se.classList.add("persona-relative");let di=12,go=()=>Y.label??"",Ls=()=>Y.iconName??"arrow-down",Ps=()=>Y.enabled!==!1,sn=()=>pe.mode??"anchor-top",Un=()=>sn()==="follow"||sn()==="anchor-top"&&Rr,Yl=()=>pe.anchorTopOffset??16,cf=()=>pe.restorePosition??"bottom",Zl=()=>pe.pauseOnInteraction===!0,ec=()=>pe.showActivityWhilePinned!==!1,tc=()=>pe.announce===!0,Tt=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");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let Ar=h("span","persona-flex persona-items-center"),pi=h("span",""),mo=h("span","");mo.setAttribute("data-persona-scroll-to-bottom-count",""),mo.style.display="none",Tt.append(Ar,pi,mo),fe.appendChild(Tt);let Vn=h("div","persona-stream-anchor-spacer");Vn.setAttribute("aria-hidden","true"),Vn.setAttribute("data-persona-anchor-spacer",""),Vn.style.flexShrink="0",Vn.style.pointerEvents="none",Vn.style.height="0px",se.appendChild(Vn);let ho=h("div","persona-sr-only");ho.setAttribute("aria-live","polite"),ho.setAttribute("aria-atomic","true"),ho.setAttribute("role","status"),ho.setAttribute("data-persona-live-region",""),Object.assign(ho.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"}),fe.appendChild(ho);let Sr=null,Is=null,nc=i=>{!tc()||!i||(Is=i,Sr===null&&(Sr=setTimeout(()=>{Sr=null,Is&&tc()&&(ho.textContent=Is),Is=null},400)))},_o=()=>{let g=J.style.display==="none"?0:J.offsetHeight;Tt.style.bottom=`${g+di}px`};_o();let oc=()=>{let i=!!go();Tt.setAttribute("aria-label",go()||"Jump to latest"),Tt.title=go(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Ar.innerHTML="";let g=ie(Ls(),"14px","currentColor",2);g?(Ar.appendChild(g),Ar.style.display=""):Ar.style.display="none",pi.textContent=go(),pi.style.display=i?"":"none"};oc();let Ct=null,Zt=null,rc=null,sc=s.find(i=>i.renderHeader);if(sc?.renderHeader){let i=sc.renderHeader({config:o,defaultRenderer:()=>{let g=Ho({config:o,showClose:$()});return ws(fe,g,o),g.header},onClose:()=>dt(!1,"user")});if(i){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),z=i,xt.header.element=i)}}let ui=()=>{if(!Me)return;if(Ve=!0,!Qe&&Me&&(Qe=Au({buffer:Me,getFullHistory:()=>Me.getAllFromStore(),onClose:()=>Tr(),config:o,plugins:s,getThroughput:()=>De?.getMetric()??{status:"idle"}})),Qe&&(se.style.display="none",J.parentNode?.insertBefore(Qe.element,J),Qe.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Qt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(m=>m&&tt.classList.add(m))}let i=()=>{if(!Ve)return;let g=Date.now();g-Le>=200&&(Qe?.update(),Le=g),Te=requestAnimationFrame(i)};Le=0,Te=requestAnimationFrame(i),tn(),p.emit("eventStream:opened",{timestamp:Date.now()})},Tr=()=>{if(Ve){if(Ve=!1,Qe&&Qe.element.remove(),se.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&tt.classList.remove(g))}Te!==null&&(cancelAnimationFrame(Te),Te=null),tn(),p.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(le){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:"");tt=h("button",g),tt.style.width="28px",tt.style.height="28px",tt.style.color=Qt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let m=ie("activity","18px","currentColor",1.5);m&&tt.appendChild(m);let b=Ie.clearChatButtonWrapper,A=Ie.closeButtonWrapper,k=b||A;k&&k.parentNode===z?z.insertBefore(tt,k):z.appendChild(tt),tt.addEventListener("click",()=>{Ve?Tr():ui()})}let df=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??_n).join(","),A.multiple=(g.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),i.appendChild(A)}},ac=s.find(i=>i.renderComposer);if(ac?.renderComposer){let i=o.composer,g=ac.renderComposer({config:o,defaultRenderer:()=>ni({config:o}).footer,onSubmit:m=>{if(!O||O.isStreaming())return;let b=m.trim(),A=Ct?.hasAttachments()??!1;if(!b&&!A)return;Dc();let k;A&&(k=[],k.push(...Ct.getContentParts()),b&&k.push(ar(b))),O.sendMessage(b,{contentParts:k}),A&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe?.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?()=>{rc?.()}:void 0});g&&(xt.replaceComposer(g),J=xt.composer.footer)}let pf=i=>{let g=(...ge)=>{for(let re of ge){let we=i.querySelector(re);if(we)return we}return null},m=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),A=i.querySelector("[data-persona-composer-submit]"),k=i.querySelector("[data-persona-composer-mic]"),Q=i.querySelector("[data-persona-composer-status]");m&&(S=m),b&&(ue=b),A&&(Ce=A),k&&(V=k,_e=k.parentElement),Q&&(D=Q);let N=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(it=N);let K=g("[data-persona-composer-attachment-button]",".persona-attachment-button");K&&(be=K,$e=K.parentElement),Fe=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Rt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(qe=ae),Je=g(".persona-widget-composer__left-actions")};df(J),pf(J);let qn=o.layout?.contentMaxWidth??(F()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(qn&&(Pe.style.maxWidth=qn,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%"),qn&&S&&!F()&&(S.style.maxWidth=qn,S.style.marginLeft="auto",S.style.marginRight="auto"),qn&&it&&!F()&&(it.style.maxWidth=qn,it.style.marginLeft="auto",it.style.marginRight="auto"),qn&&Rt&&!F()&&(Rt.style.maxWidth=qn,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),o.attachments?.enabled&&Fe&&Rt){Ct=as.fromConfig(o.attachments),Ct.setPreviewsContainer(Rt),Fe.addEventListener("change",m=>{let b=m.target;Ct?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,g=Qu(i);fe.appendChild(g)}let uf=()=>Zt?.prefetch();if(o.contextMentions?.enabled&&ue&&(Zt=fp({config:o,textarea:ue,anchor:S??ue,getMessages:()=>O.getMessages(),liveRegionHost:fe}),Zt)){let i=ue;i.parentElement?.insertBefore(Zt.contextRow,i);let g=Zt.affordanceButtons;for(let m=g.length-1;m>=0;m--){let b=g[m];Je?Je.insertBefore(b,Je.firstChild):S?.appendChild(b)}}(()=>{let i=o.layout?.slots??{},g=b=>{switch(b){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Pe;case"footer-top":return it;case"composer":return S;case"footer-bottom":return D;default:return null}},m=(b,A)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")z.insertBefore(A,z.firstChild);else if(b==="header-right")z.appendChild(A);else{let k=z.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(A,k.nextSibling):z.appendChild(A)}break;case"body-top":{let k=se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");k?k.replaceWith(A):se.insertBefore(A,se.firstChild);break}case"body-bottom":se.appendChild(A);break;case"footer-top":it.replaceWith(A);break;case"footer-bottom":D.replaceWith(A);break;default:break}};for(let[b,A]of Object.entries(i))if(A)try{let k=A({config:o,defaultContent:()=>g(b)});k&&m(b,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,k)}})();let ic=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 k=m.getAttribute("data-bubble-type");if(k==="reasoning")hr.has(A)?hr.delete(A):hr.add(A),pu(A,b);else if(k==="tool")yr.has(A)?yr.delete(A):yr.add(A),uu(A,b,o);else if(k==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",K=Bo.get(A)??N;Bo.set(A,!K),hu(A,b,o)}wo.delete(A)};Pe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ic(i))}),Pe.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ic(i))}),Pe.addEventListener("copy",i=>{let{clipboardData:g}=i;if(!g)return;let m=Pe.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let A=b.toString(),k=$p(A);!k||k===A||(g.setData("text/plain",k),i.preventDefault())});let fi=new Map,lc=null,cc="idle",ff={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},gf=(i,g)=>{let{icon:m,label:b}=ff[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=ie(m,14,"currentColor",2);A&&(i.innerHTML="",i.appendChild(A))},dc=()=>{Pe.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let b=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;gf(g,b&&b===lc?cc:"idle")})};Pe.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 k=m.getAttribute("data-action");if(k==="copy"){let N=O.getMessages().find(K=>K.id===A);if(N&&Xe.onCopy){let K=N.content||"";navigator.clipboard.writeText(K).then(()=>{m.classList.add("persona-message-action-success");let ae=ie("check",14,"currentColor",2);ae&&(m.innerHTML="",m.appendChild(ae)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let ge=ie("copy",14,"currentColor",2);ge&&(m.innerHTML="",m.appendChild(ge))},2e3)}).catch(ae=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ae)}),Xe.onCopy(N)}}else if(k==="read-aloud")O.toggleReadAloud(A);else if(k==="upvote"||k==="downvote"){let N=(fi.get(A)??null)===k,K=k==="upvote"?"thumbs-up":"thumbs-down";if(N){fi.delete(A),m.classList.remove("persona-message-action-active");let ae=ie(K,14,"currentColor",2);ae&&(m.innerHTML="",m.appendChild(ae))}else{let ae=k==="upvote"?"downvote":"upvote",ge=b.querySelector(`[data-action="${ae}"]`);if(ge){ge.classList.remove("persona-message-action-active");let nt=ie(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(ge.innerHTML="",ge.appendChild(nt))}fi.set(A,k),m.classList.add("persona-message-action-active");let re=ie(K,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(re)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ue=O.getMessages().find(pt=>pt.id===A);Ue&&Xe.onFeedback&&Xe.onFeedback({type:k,messageId:Ue.id,message:Ue})}}}),Pe.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 k=m.getAttribute("data-approval-action");if(!k)return;let Q=k==="approve"?"approved":"denied",K=O.getMessages().find(ge=>ge.id===A);if(!K?.approval)return;let ae=b.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),K.approval.toolType==="webmcp"?O.resolveWebMcpApproval(A,Q):O.resolveApproval(K.approval,Q)});let Ye=null,Mr=null,Er=()=>{},kr="none",Rs=null,mn={artifacts:[],selectedId:null},Ln=!1,hn=!1,Lr=!1,$o=!1,pc=()=>$o||mn.artifacts.some(i=>ro(o.features?.artifacts,i)==="panel"),Ws=()=>mn.artifacts.length>0&&!Ln&&pc(),lt={current:null},gi=(i,g)=>{let m=O.getArtifactById(g),b=m?.markdown,A=m?.title||"artifact",k=m?.file,Q=m?.artifactType??"markdown";if(!b){let ae=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ae){let re=O.getMessages().find(we=>we.id===ae);if(re?.rawContent)try{let we=JSON.parse(re.rawContent);b=we?.props?.markdown,A=we?.props?.title||A,we?.props?.file&&typeof we.props.file=="object"&&(k=we.props.file),!m&&typeof we?.props?.artifactType=="string"&&(Q=we.props.artifactType)}catch{}}}return{markdown:b,title:A,file:k,artifactType:Q}};Pe.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:k,title:Q,file:N}=gi(m,b);if(!k)return;let{filename:K,mime:ae,content:ge}=Ap({title:Q,markdown:k,file:N}),re=new Blob([ge],{type:ae}),we=URL.createObjectURL(re),Ue=document.createElement("a");Ue.href=we,Ue.download=K,Ue.click(),URL.revokeObjectURL(we)}),Pe.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]"),k=A?null:m.closest("[data-open-artifact]"),Q=A?A.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,K=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===b);if(!K)return;let{markdown:ae,title:ge,file:re,artifactType:we}=gi(m,Q??""),Ue={artifactId:Q,title:ge,artifactType:we,markdown:ae,file:re};try{Promise.resolve(K.onClick(Ue)).catch(()=>{})}catch{}}),Pe.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=O.getArtifactById(b),k="";if(A)k=fs(A);else{let{markdown:Q,file:N,artifactType:K}=gi(m,b);K==="markdown"&&(k=fs({id:b,artifactType:"markdown",status:"complete",markdown:Q??"",...N?{file:N}:{}}))}k&&navigator.clipboard.writeText(k).then(()=>{let Q=ie("check",16,"currentColor",2);Q&&(m.replaceChildren(Q),setTimeout(()=>{let N=ie("copy",16,"currentColor",2);N&&m.replaceChildren(N)},1500))}).catch(()=>{})}),Pe.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||(Ln=!1,$o=!0,hn=!0,Lr=!0,O.selectArtifact(b),Pn())}),Pe.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(),Ln=!1,$o=!0,O.selectArtifact(b),Pn())}),Pe.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 zo=Ie.composerOverlay,jo=(i,g,m)=>{let b=g.trim();if(!b||!lt.current)return;let A=i.getAttribute("data-tool-call-id")??"",k=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:b,answers:m.structured,values:m.values??(m.source==="multi"?b.split(", "):[b]),isFreeText:k,source:m.source},bubbles:!0,composed:!0})),rr(zo,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)},yo=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:fa(i,b),currentIndex:fn(i)})},uc=i=>Object.entries(i).map(([g,m])=>`${g}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),mi=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=fn(i),m=or(i);if(g>=m-1)return;let b=lt.current?.getMessages().find(A=>A.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(ma(i,b,o,g+1),yo(i))};zo.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 k=b.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),rr(zo,k);let Q=lt.current?.getMessages().find(N=>N.toolCall?.id===k);Q?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(Q),lt.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(A==="pick"){let k=m.getAttribute("data-option-label");if(!k)return;let Q=b.getAttribute("data-multi-select")==="true",N=so(b);if(N&&Q){let K=Po(b)[fn(b)],ae=new Set(Array.isArray(K)?K:[]);ae.has(k)?ae.delete(k):ae.add(k),ao(b,Array.from(ae)),yo(b);return}if(N){ao(b,k),yo(b),mi(b);return}if(Q){let K=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",K?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!K);let ae=b.querySelector('[data-ask-user-action="submit-multi"]');ae&&(ae.disabled=Xi(b).length===0);return}jo(b,k,{source:"pick",values:[k]});return}if(A==="submit-multi"){let k=Xi(b);if(k.length===0)return;jo(b,k.join(", "),{source:"multi",values:k});return}if(A==="open-free-text"){let k=b.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.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(so(b)){ao(b,Q.trim()),yo(b),mi(b);return}jo(b,Q,{source:"free-text"});return}if(A==="next"||A==="back"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(re=>re.toolCall?.id===k);if(!Q)return;let K=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(K){let re=Po(b)[fn(b)];(typeof re!="string"||re!==K)&&ao(b,K)}let ae=A==="next"?1:-1,ge=fn(b)+ae;ma(b,Q,o,ge),yo(b);return}if(A==="submit-all"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(re=>re.toolCall?.id===k);if(!Q)return;let K=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";K&&ao(b,K);let ae=fa(b,Q);lt.current.persistAskUserQuestionProgress(Q,{answers:ae,currentIndex:fn(b)});let ge=uc(ae);jo(b,ge||"(submitted)",{source:"submit-all",structured:ae});return}if(A==="skip"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(we=>we.toolCall?.id===k);if(!Q)return;let N=so(b),K=fn(b),ae=or(b),ge=K>=ae-1;if(!N){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),rr(zo,k),Q.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(Q),lt.current.resolveAskUserQuestion(Q,"(dismissed)"));return}ao(b,"");let re=b.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),ge){let we=fa(b,Q),Ue=uc(we);jo(b,Ue||"(skipped)",{source:"submit-all",structured:we});return}ma(b,Q,o,K+1),yo(b);return}}),zo.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(so(b)){ao(b,A.trim()),yo(b),mi(b);return}jo(b,A,{source:"free-text"})}});let fc=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=zo.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),k=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];k&&(i.preventDefault(),k.click())};document.addEventListener("keydown",fc);let Kn=null,yt=null,Pr=null,Hs=null,hi=()=>{},gc=!1,Bs="",Ds="";function yi(){Hs?.(),Hs=null}let mc=()=>{if(!Kn||!yt)return;let i=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,m=g.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||m){yt.style.removeProperty("position"),yt.style.removeProperty("left"),yt.style.removeProperty("top"),yt.style.removeProperty("bottom"),yt.style.removeProperty("width"),yt.style.removeProperty("z-index");return}let b=Kn.firstElementChild;if(!b||b===yt)return;let A=10;yt.style.position="absolute",yt.style.top="0",yt.style.bottom="0",yt.style.width=`${A}px`,yt.style.zIndex="5";let k=Fl(Kn,g),Q=b.offsetWidth+k/2-A/2;yt.style.left=`${Math.max(0,Q)}px`},Fs=()=>{},mf=()=>{let i=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>m?!1:M||Dt(o)},Ns=()=>!Xt(o)||!Ws()||e.classList.contains("persona-artifact-narrow-host")||mf()||(e.ownerDocument.defaultView??window).innerWidth<sb?"none":Hl(o)?"detached":"welded",Pn=()=>{if(!Ye||!Xt(o))return;Ts(e,o),Ms(e,o),Fs();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=i);let m=Ws();Ye.setVisible(m),Ye.update(mn),Ln?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),hn=!1,Lr=!1):mn.artifacts.length>0&&pc()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),hn=!1,Lr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(b),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!Lr&&(hn=!1),hn!==gc){let k=Ye.element;hn?(Bs=k.style.width,Ds=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Bs&&(k.style.width=Bs),Ds&&(k.style.maxWidth=Ds),Bs="",Ds=""),gc=hn}e.classList.toggle("persona-artifact-expanded",hn),Ye.setExpanded(hn);let A=Ns();A!==kr&&(kr=A,Er()),hi()};if(Xt(o)){de.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(fe),Ye=Tu(o,{onSelect:m=>lt.current?.selectArtifact(m),onDismiss:()=>{Ln=!0,Pn()},onToggleExpand:()=>{let m=!hn,b=mn.selectedId??mn.artifacts[mn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:b,expanded:m})!==!0&&(hn=m,m||(Lr=!1),Pn())}}),Ye.element.classList.add("persona-hidden"),Kn=g,g.appendChild(i),g.appendChild(Ye.element),Ye.backdrop&&de.appendChild(Ye.backdrop),de.appendChild(g),hi=()=>{if(!Kn||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Pr?.(),Pr=null,yi(),yt&&(yt.remove(),yt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!yt){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=e.ownerDocument,k=A.defaultView??window,Q=N=>{if(!Ye||N.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||k.innerWidth<=640)return;N.preventDefault(),yi();let K=N.clientX,ae=Ye.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,re=Ue=>{let pt=Kn.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),nn=Fl(Kn,k),At=nt?0:b.getBoundingClientRect().width||6,Et=ae-(Ue.clientX-K),W=Hu(Et,pt,nn,At,ge?.resizableMinWidth,ge?.resizableMaxWidth);Ye.element.style.width=`${W}px`,Ye.element.style.maxWidth="none",mc()},we=()=>{A.removeEventListener("pointermove",re),A.removeEventListener("pointerup",we),A.removeEventListener("pointercancel",we),Hs=null;try{b.releasePointerCapture(N.pointerId)}catch{}};Hs=we,A.addEventListener("pointermove",re),A.addEventListener("pointerup",we),A.addEventListener("pointercancel",we);try{b.setPointerCapture(N.pointerId)}catch{}};b.addEventListener("pointerdown",Q),yt=b,Kn.insertBefore(b,Ye.element),Pr=()=>{b.removeEventListener("pointerdown",Q)}}if(yt){let b=Ws();yt.classList.toggle("persona-hidden",!b),mc()}},Fs=()=>{if(!M||!Ye||(o.launcher?.sidebarMode??!1)||Dt(o)&&gn(o).reveal==="emerge")return;let b=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(A&&b.innerWidth<=k||!ku(o,M))return;let Q=o.launcher?.width??o.launcherWidth??$n,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Ws()?(de.style.width=N,de.style.maxWidth=N):(de.style.width=Q,de.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(Mr=new ResizeObserver(()=>{Pn()}),Mr.observe(de))}else de.appendChild(fe);F()&&et&&(Ie.peekBanner&&et.appendChild(Ie.peekBanner),et.appendChild(J)),e.appendChild(He),et&&e.appendChild(et);let Os=()=>{if(F()){de.style.width="100%",de.style.maxWidth="100%";let St=o.launcher?.composerBar??{},Yt=He.dataset.state==="expanded",oa=St.expandedSize??"anchored";if(!(Yt&&oa!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let qr=o.theme?.components?.panel,ra=dr(o),Jo=(Hn,ko)=>Hn==null||Hn===""?ko:Gt(ra,Hn)??Hn,sa="1px solid var(--persona-border)",Oi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Eo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=Jo(qr?.border,sa),fe.style.borderRadius=Jo(qr?.borderRadius,Eo),fe.style.boxShadow=Jo(qr?.shadow,Oi),fe.style.overflow="hidden";return}let i=Dt(o),g=o.launcher?.sidebarMode??!1,m=i||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,k=o.theme?.components?.panel,Q=dr(o),N=(St,Yt)=>St==null||St===""?Yt:Gt(Q,St)??St,K=e.ownerDocument.defaultView??window,ae=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640,re=K.innerWidth<=ge,we=ae&&re&&M,Ue=i&&ae&&re,pt=o.launcher?.position??"bottom-left",nt=pt==="bottom-left"||pt==="top-left",nn=o.launcher?.zIndex??Vt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Et="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",W="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ee=A&&!we&&!Ue;Ee?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Ne=Ee?At:g||we?"none":At,Se=Ee?Et:we?"none":g?nt?"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":Et;i&&!we&&!Ee&&(Se="none",Ne="none");let wt=Ee?W:g||we?"0":W,ut=N(k?.border,Ne),Bt=N(k?.shadow,Se),ft=N(k?.borderRadius,wt),Jt=Ns(),kt=Jt==="detached",ke=Jt==="welded";e.classList.toggle("persona-artifact-detached-split",kt),e.classList.toggle("persona-artifact-welded-split",ke);let Oe="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)))))",vt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Xt(o)&&Hl(o)&&b&&!i;e.classList.toggle("persona-artifact-chat-flush",vt);let ct=kt||vt?"none":Bt,gt=kt?At:ke?"none":ut,Ze=kt?W:ft;vt&&(gt="none",Ze="0");let We=k?.borderRadius!=null&&k.borderRadius!=="",ht=vt&&!We?"0":ft,zt=se.scrollTop;e.style.cssText="",He.style.cssText="",de.style.cssText="",fe.style.cssText="",se.style.cssText="",J.style.cssText="",Ve&&(se.style.display="none"),(m||b)&&(e.style.minWidth="0");let pn=()=>{if(zt<=0)return;(se.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(se.scrollTop===zt)return;let Yt=se.scrollHeight-se.clientHeight;Yt<=0||(se.scrollTop=Math.min(zt,Yt))})};if(we){He.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"),He.style.cssText=`
47
47
  position: fixed !important;
48
48
  inset: 0 !important;
49
49
  width: 100% !important;
@@ -53,9 +53,9 @@ _Details: ${n.message}_`:o}var Xr=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: ${en} !important;
56
+ z-index: ${nn} !important;
57
57
  background-color: var(--persona-surface, #ffffff) !important;
58
- `,me.style.cssText=`
58
+ `,de.style.cssText=`
59
59
  position: relative !important;
60
60
  display: flex !important;
61
61
  flex-direction: column !important;
@@ -68,7 +68,7 @@ _Details: ${n.message}_`:o}var Xr=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
- `,ue.style.cssText=`
71
+ `,fe.style.cssText=`
72
72
  display: flex !important;
73
73
  flex-direction: column !important;
74
74
  flex: 1 1 0% !important;
@@ -79,33 +79,33 @@ _Details: ${n.message}_`:o}var Xr=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
- `,ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",$.style.flexShrink="0",j=!0,cn();return}let Vs=o?.launcher?.width??o?.launcherWidth??Nn;if(!g&&!i)b&&m?(me.style.width="100%",me.style.maxWidth="100%"):(me.style.width=Vs,me.style.maxWidth=Vs);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(Es(),me.style.boxShadow=lt,me.style.borderRadius=mt,Lt?me.style.border="none":Re&&(me.style.border=pt),ue.style.border=ft,ue.style.borderRadius=Ze,ue.style.boxShadow=Lt&&!wt?_e:"",wt&&(ue.style.background="transparent",ae.style.background="transparent",$.style.background="transparent",$.style.borderTop="none"),Re){let Tt=o.features?.artifacts?.layout;Cs=Tt?.unifiedSplitOuterRadius?.trim()||Tt?.paneBorderRadius?.trim()||ut}else Cs=null;if(i&&!xe&&!Ie&&!Lt&&!Re&&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&&Re&&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%"),Be.style.display="flex",Be.style.flexDirection="column",Be.style.flex="1 1 0%",Be.style.minHeight="0",Be.style.maxHeight="100%",Be.style.height="100%",b&&(Be.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%",Lt||(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",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",$.style.flexShrink="0"),b&&(Ie||Lt||wt)&&!i&&(wt||(Be.style.padding="var(--persona-panel-inset)"),Be.style.background="var(--persona-panel-canvas-bg)"),Be.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[dt]??wn["bottom-right"]).split(" ").forEach(Xt=>Be.classList.add(Xt)),g){let Tt=o.launcher?.sidebarWidth??"420px";A?Be.style.cssText=`
82
+ `,se.style.flex="1 1 0%",se.style.minHeight="0",se.style.overflowY="auto",J.style.flexShrink="0",oe=!0,pn();return}let na=o?.launcher?.width??o?.launcherWidth??$n;if(!g&&!i)b&&m?(de.style.width="100%",de.style.maxWidth="100%"):(de.style.width=na,de.style.maxWidth=na);else if(i)if(gn(o).reveal==="emerge"&&!A){let Yt=gn(o).width;de.style.width=Yt,de.style.maxWidth=Yt}else de.style.width="100%",de.style.maxWidth="100%";if(Fs(),de.style.boxShadow=ct,de.style.borderRadius=ht,kt?de.style.border="none":ke&&(de.style.border=ut),fe.style.border=gt,fe.style.borderRadius=Ze,fe.style.boxShadow=kt&&!vt?Oe:"",vt&&(fe.style.background="transparent",se.style.background="transparent",J.style.background="transparent",J.style.borderTop="none"),ke){let St=o.features?.artifacts?.layout;Rs=St?.unifiedSplitOuterRadius?.trim()||St?.paneBorderRadius?.trim()||ft}else Rs=null;if(i&&!we&&!Ee&&!kt&&!ke&&k?.border===void 0&&(fe.style.border="none",gn(o).side==="right"?fe.style.borderLeft="1px solid var(--persona-border)":fe.style.borderRight="1px solid var(--persona-border)"),i&&!we&&ke&&k?.border===void 0&&(gn(o).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),m&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),He.style.display="flex",He.style.flexDirection="column",He.style.flex="1 1 0%",He.style.minHeight="0",He.style.maxHeight="100%",He.style.height="100%",b&&(He.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",kt||(de.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.overflow="hidden",se.style.flex="1 1 0%",se.style.minHeight="0",se.style.overflowY="auto",J.style.flexShrink="0"),b&&(Ee||kt||vt)&&!i&&(vt||(He.style.padding="var(--persona-panel-inset)"),He.style.background="var(--persona-panel-canvas-bg)"),He.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&&(Cn[pt]??Cn["bottom-right"]).split(" ").forEach(Yt=>He.classList.add(Yt)),g){let St=o.launcher?.sidebarWidth??"420px";A?He.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: ${Tt} !important;
86
+ width: ${St} !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: ${en} !important;
94
- ${tt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
95
- `:Be.style.cssText=`
93
+ z-index: ${nn} !important;
94
+ ${nt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
95
+ `:He.style.cssText=`
96
96
  position: fixed !important;
97
97
  top: 0 !important;
98
98
  bottom: 0 !important;
99
- width: ${Tt} !important;
99
+ width: ${St} !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: ${en} !important;
107
- ${tt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
108
- `,me.style.cssText=`
106
+ z-index: ${nn} !important;
107
+ ${nt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
108
+ `,de.style.cssText=`
109
109
  position: relative !important;
110
110
  display: flex !important;
111
111
  flex-direction: column !important;
@@ -116,10 +116,10 @@ _Details: ${n.message}_`:o}var Xr=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: ${lt} !important;
120
- border-radius: ${mt} !important;
121
- ${Lt?"border: none !important;":Re?`border: ${pt} !important;`:""}
122
- `,me.style.setProperty("width","100%","important"),me.style.setProperty("max-width","100%","important"),ue.style.cssText=`
119
+ box-shadow: ${ct} !important;
120
+ border-radius: ${ht} !important;
121
+ ${kt?"border: none !important;":ke?`border: ${ut} !important;`:""}
122
+ `,de.style.setProperty("width","100%","important"),de.style.setProperty("max-width","100%","important"),fe.style.cssText=`
123
123
  display: flex !important;
124
124
  flex-direction: column !important;
125
125
  flex: 1 1 0% !important;
@@ -129,39 +129,39 @@ _Details: ${n.message}_`:o}var Xr=t=>({isError:!0,content:[{type:"text",text:t}]
129
129
  max-height: 100% !important;
130
130
  overflow: hidden !important;
131
131
  border-radius: ${Ze} !important;
132
- border: ${ft} !important;
133
- ${Lt&&!wt?`box-shadow: ${_e} !important;`:""}
134
- ${wt?"background: transparent !important;":""}
135
- `,$.style.cssText=`
132
+ border: ${gt} !important;
133
+ ${kt&&!vt?`box-shadow: ${Oe} !important;`:""}
134
+ ${vt?"background: transparent !important;":""}
135
+ `,J.style.cssText=`
136
136
  flex-shrink: 0 !important;
137
137
  border-top: none !important;
138
138
  padding: 8px 16px 12px 16px !important;
139
- ${wt?"background: transparent !important;":""}
140
- `}if(!b&&!i){let Tt="max-height: -moz-available !important; max-height: stretch !important;",Xt=g?"":"padding-top: 1.25em !important;",Ks=g?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;Be.style.cssText+=Tt+Xt+Ks}cn()};Ls(),es(t,o),hs(t,o),ys(t,o),vr=()=>{Ls(),es(t,o),hs(t,o),ys(t,o),Cs?t.style.setProperty("--persona-artifact-welded-outer-radius",Cs):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ue=[];Ue.push(()=>{document.removeEventListener("keydown",Zl)}),Ue.push(()=>{hr!==null&&clearTimeout(hr)});let xn=null,Cn=null;Ue.push(()=>{xn?.(),xn=null,Cn?.(),Cn=null}),br&&Ue.push(()=>{br?.disconnect(),br=null}),Ue.push(()=>{Cr?.(),Cr=null,ai(),bt&&(bt.remove(),bt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),Y&&Ue.push(()=>{Qe!==null&&(cancelAnimationFrame(Qe),Qe=null),Fe?.destroy(),Fe=null,Ae?.destroy(),Ae=null,pe=null});let go=null,nc=()=>{go&&(go(),go=null),o.colorScheme==="auto"&&(go=Ca(()=>{es(t,o)}))};nc(),Ue.push(()=>{go&&(go(),go=null)}),Ue.push(a);let Ps=o.features?.streamAnimation;if(Ps?.type&&Ps.type!=="none"){let i=cr(Ps.type,Ps.plugins);i&&(Fa(i,t),Ue.push(()=>_p(t)))}let Is=su(yt),mo=null,_,ii=i=>{if(!_)return;let g=i??_.getMessages(),m=o.features?.suggestReplies?.enabled!==!1?kd(g):null;m?Is.render(m,_,ve,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(b=>b.role==="user")?Is.render([],_,ve,g):Is.render(o.suggestionChips,_,ve,g,o.suggestionChipsConfig)},mn=!1,ho=Pp(),Oo=new Map,yo=new Map,jn=new Map,li=0,Xu=Hn()!==null,Yt=Ia(),rn=0,qn=null,sn=!1,Rs=!1,Vn=0,hn=null,bo=null,ci=!1,Ws=!1,Ar=null,Sr=!0,Hs=!1,Bs=null,Ds=!1,vo=()=>{Ds=!0},di=null,Ju=4,Fs=24,Yu=80,pi=new Map,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},oc=o.voiceRecognition?.autoResume??!1,kn=i=>{l.emit("voice:state",{active:Ge.active,source:i,timestamp:Date.now()})},yn=()=>{C(i=>({...i,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},Zu=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Il(c.voiceState),g=!!i.active,m=Number(i.timestamp??0);Ge.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-m<My&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),kn("restore"),_.isVoiceActive()&&jo()}):zs("restore"))},1e3)},ef=()=>_?ku(_.getMessages()).filter(i=>!i.__skipPersist):[],Ns=null,rc=(i,g)=>{typeof console<"u"&&console.error(i,g)},ui=(i,g)=>{let m=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(N=>{rc(g,N)})}catch(Q){return rc(g,Q),null}},b=Ns,A=b?b.then(()=>m()??void 0):m();if(!A)return;let L=A.finally(()=>{Ns===L&&(Ns=null)});Ns=L};function fi(i){if(!d?.save)return;let m={messages:i?ku(i):_?ef():[],metadata:c,artifacts:fn.artifacts,selectedArtifactId:fn.selectedId};ui(()=>d.save(m),"[AgentWidget] Failed to persist state:")}let _o=null,sc=()=>Be.querySelector("#persona-scroll-container")||ae,Tr=()=>{_o!==null&&(cancelAnimationFrame(_o),_o=null),sn=!1},ac=()=>{qn!==null&&(cancelAnimationFrame(qn),qn=null),Rs=!1,Tr()},tf=()=>mn&&mi()&&(Ut()!=="anchor-top"||_l()),gi=()=>{let i=co()||"Jump to latest",g=tf();Mt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Vn>0?(po.textContent=String(Vn),po.style.display="",Mt.setAttribute("aria-label",`${i} (${Vn} new)`)):(po.textContent="",po.style.display="none",Mt.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},ic=()=>{Vn!==0&&(Vn=0,gi())},mi=()=>_n()?!Yt.isFollowing():!ao(ae,Fs),Zt=()=>{if(!ws()||ot){Mt.parentNode&&Mt.remove(),Mt.style.display="none";return}Mt.parentNode!==ue&&ue.appendChild(Mt),Bo();let g=Tn(ae)>0&&mi();g?gi():ic(),Mt.style.display=g?"":"none"},Mr=()=>{Yt.pause()&&(ac(),Zt())},Kn=()=>{Yt.resume(),ic(),Zt()},Gn=(i=!1)=>{_n()&&Yt.isFollowing()&&(!i&&!mn||(qn!==null&&(cancelAnimationFrame(qn),qn=null),Rs=!0,qn=requestAnimationFrame(()=>{qn=null,Rs=!1,Yt.isFollowing()&&nf(sc(),i?220:140)})))},lc=(i,g,m,b=()=>!0)=>{let A=i.scrollTop,L=g(),Q=L-A;if(Tr(),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()){Tr();return}let ne=g();ne!==L&&(L=ne,Q=L-A);let xe=fe-N,je=Math.min(xe/m,1),dt=G(je),tt=A+Q*dt;i.scrollTop=tt,rn=i.scrollTop,je<1?_o=requestAnimationFrame(oe):(i.scrollTop=L,rn=i.scrollTop,_o=null,sn=!1)};_o=requestAnimationFrame(oe)},nf=(i,g=500)=>{let m=Tn(i)-i.scrollTop;if(Math.abs(m)<1){rn=i.scrollTop;return}if(Math.abs(m)>=Yu){Tr(),sn=!0,i.scrollTop=Tn(i),rn=i.scrollTop,sn=!1;return}lc(i,()=>Tn(i),g,()=>Yt.isFollowing())},cc=()=>{let i=sc();sn=!0,i.scrollTop=Tn(i),rn=i.scrollTop,sn=!1,Zt()},dc=i=>{let g=0,m=i;for(;m&&m!==ae;)g+=m.offsetTop,m=m.offsetParent;return g},of=()=>{let i=ae.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ae.ownerDocument.getSelection()},Os=()=>Bp(of(),ae),pc=()=>{if(Uu()!=="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=ae.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let A=Math.min(Math.max(0,dc(b)-Nl()),Tn(ae));return sn=!0,ae.scrollTop=A,rn=ae.scrollTop,sn=!1,Ut()==="follow"&&!ao(ae,Fs)&&Yt.pause(),Zt(),!0},uc=i=>{$n.style.height=`${Math.max(0,Math.round(i))}px`,hn&&(hn.spacerHeight=Math.max(0,i))},Er=()=>{bo!==null&&(cancelAnimationFrame(bo),bo=null),Tr(),hn=null,$n.style.height="0px"},fc=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=ae.querySelector(`[data-message-id="${g}"]`);if(!m)return;let b=dc(m),A=hn?.spacerHeight??0,L=ae.scrollHeight-A,{targetScrollTop:Q,spacerHeight:N}=Dp({anchorOffsetTop:b,topOffset:Nl(),viewportHeight:ae.clientHeight,contentHeight:L});hn={initialSpacerHeight:N,contentHeightAtAnchor:L,spacerHeight:N},uc(N),lc(ae,()=>Q,220)})},rf=()=>{if(_n()){if(!Yt.isFollowing()||ao(ae,1))return;Gn(!mn);return}if(hn&&hn.initialSpacerHeight>0){let i=ae.scrollHeight-hn.spacerHeight,g=Fp({initialSpacerHeight:hn.initialSpacerHeight,contentHeightAtAnchor:hn.contentHeightAtAnchor,currentContentHeight:i});g!==hn.spacerHeight&&uc(g)}Zt()},sf=i=>{let g=Ut();g==="follow"?(Kn(),Gn(!0)):g==="anchor-top"&&(Sr=!1,Hs=!0,Ds=!1,Bs=i,fc(i))},af=()=>{if(Ut()==="anchor-top"){if(Hs){Sr=!1;return}Sr=!0,Er(),Kn(),Gn(!0)}},lf=i=>{if(Ut()!=="anchor-top"||!Hs||Ds||Os())return;let g=Ar===null;for(let m of i){if(!g){m.id===Ar&&(g=!0);continue}if(Hp(m)){if(m.id===Bs)return;Bs=m.id,fc(m.id);return}}},cf=i=>{let g=new Map;i.forEach(m=>{let b=pi.get(m.id);g.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(l.emit("assistant:message",m),!Ws&&(Ut()!=="anchor-top"||_l())&&mi()&&(Vn+=1,gi(),Zt(),zl(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}))}),pi.clear(),g.forEach((m,b)=>{pi.set(b,m)})},_s=(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)},wo=(i,g)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),_s(m,g),m},df=(i,g,m)=>{let b=document.createElement("div"),L=(()=>{let R=r.find(Ie=>Ie.renderLoadingIndicator);if(R?.renderLoadingIndicator)return R.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(R,Ie)=>Ie==null?!1:typeof Ie=="string"?(R.textContent=Ie,!0):(R.appendChild(Ie),!0),N=new Set,G=new Map,oe=new Set,fe=r.some(R=>R.renderAskUserQuestion),ne=[],xe=[],je=o.enableComponentStreaming!==!1,dt=o.approval!==!1,tt=[];if(g.forEach(R=>{N.add(R.id),G.set(R.id,R.role);let Ie=fe&&Mo(R),Oe=dt&&R.variant==="approval"&&!!R.approval,Me=!Ie&&R.role==="assistant"&&!R.variant&&je&&Pl(R);!Oe&&jn.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),jn.delete(R.id)),!Me&&yo.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),yo.delete(R.id));let At=Mo(R)?`:${R.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${R.agentMetadata?.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",pt=Lp(R,li)+At,qt=Ie||Oe||Me?null:Ip(ho,R.id,pt);if(qt){b.appendChild(qt.cloneNode(!0)),Mo(R)&&R.toolCall?.id&&R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(oe.add(R.toolCall.id),sa(R,o,Le.composerOverlay));return}let ut=null,Qt=r.find(_e=>!!(R.variant==="reasoning"&&_e.renderReasoning||R.variant==="tool"&&_e.renderToolCall||!R.variant&&_e.renderMessage)),Lt=o.layout?.messages;if(Mo(R)&&R.agentMetadata?.askUserQuestionAnswered===!0){Oo.delete(R.id),i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime");return}if($i(R)&&o.features?.suggestReplies?.enabled!==!1)return;if(Mo(R)&&o.features?.askUserQuestion?.enabled!==!1){let _e=r.find(Ft=>typeof Ft.renderAskUserQuestion=="function");if(_e&&it.current){let Ft=Oo.get(R.id),Nt=Ft!==pt,wt=null;if(Nt){let{payload:Ze,complete:De}=Xo(R),mt=R.id,Ot=()=>it.current?.getMessages().find(cn=>cn.id===mt);wt=_e.renderAskUserQuestion({message:R,payload:Ze,complete:De,resolve:cn=>{let Fr=Ot();Fr&&it.current?.resolveAskUserQuestion(Fr,cn)},dismiss:()=>{let cn=Ot();cn?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(cn),it.current?.resolveAskUserQuestion(cn,"(dismissed)"))},config:o})}let lt=Ft!=null;if(Nt&&wt===null&&!lt){R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(oe.add(R.toolCall.id),sa(R,o,Le.composerOverlay));return}let ft=wo(R.id,R.role);ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),b.appendChild(ft),ne.push({messageId:R.id,fingerprint:pt,bubble:wt});return}else{R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(oe.add(R.toolCall.id),sa(R,o,Le.composerOverlay));return}}else if(Oe){let _e=r.find(lt=>typeof lt.renderApproval=="function")??s,Nt=jn.get(R.id)!==pt,wt=null;if(Nt&&_e?.renderApproval){let lt=R.id,ft=(Ze,De)=>{let mt=it.current?.getMessages().find(Ot=>Ot.id===lt);mt?.approval&&(mt.approval.toolType==="webmcp"?it.current?.resolveWebMcpApproval(mt.id,Ze):it.current?.resolveApproval(mt.approval,Ze,De))};wt=_e.renderApproval({message:R,defaultRenderer:()=>Qa(R,o),config:o,approve:Ze=>ft("approved",Ze),deny:Ze=>ft("denied",Ze)})}if(Nt&&wt===null)i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),jn.delete(R.id),ut=Qa(R,o);else{let lt=wo(R.id,R.role);lt.setAttribute("data-approval-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),b.appendChild(lt),tt.push({messageId:R.id,fingerprint:pt,bubble:wt});return}}else if(Qt)if(R.variant==="reasoning"&&R.reasoning&&Qt.renderReasoning){if(!ee)return;ut=Qt.renderReasoning({message:R,defaultRenderer:()=>ml(R,o),config:o})}else if(R.variant==="tool"&&R.toolCall&&Qt.renderToolCall){if(!ce)return;ut=Qt.renderToolCall({message:R,defaultRenderer:()=>yl(R,o),config:o})}else Qt.renderMessage&&(ut=Qt.renderMessage({message:R,defaultRenderer:()=>{let _e=gl(R,m,Lt,o.messageActions,Ee,{loadingIndicatorRenderer:L,widgetConfig:o});return R.role!=="user"&&Sl(_e,R,o,_),_e},config:o}));if(!ut&&Me){let _e=Tu(R);if(_e){let Ft=yo.get(R.id),Nt=Ft!==pt,wt=o.wrapComponentDirectiveInBubble!==!1&&On.getOptions(_e.component)?.bubbleChrome!==!1,lt=null;if(Nt){let ft=Au(_e,{config:o,message:R,transform:m});if(ft&&_e.component==="PersonaArtifactInline"){let Ze=ft.hasAttribute("data-artifact-inline")?ft:ft.querySelector("[data-artifact-inline]"),De=Ze?.getAttribute("data-artifact-inline")??"",mt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(De):De,Ot=De?i.querySelector(`#wrapper-${R.id}`)?.querySelector(`[data-artifact-inline="${mt}"]`)??null:null;Ze&&Ot&&Ot!==Ze&&Sp(Ot)&&(Ze===ft?ft=Ot:Ze.replaceWith(Ot))}if(ft)if(wt){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${R.id}`,Ze.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}),Ze.appendChild(De)}Ze.appendChild(ft),lt=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${R.id}`,Ze.setAttribute("data-message-id",R.id),Ze.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}),Ze.appendChild(De)}Ze.appendChild(ft),lt=Ze}}if(lt||Ft!=null){let ft=wo(R.id,R.role);ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),b.appendChild(ft),xe.push({messageId:R.id,fingerprint:pt,bubble:lt});return}}}if(!ut)if(R.variant==="reasoning"&&R.reasoning){if(!ee)return;ut=ml(R,o)}else if(R.variant==="tool"&&R.toolCall){if(!ce)return;ut=yl(R,o)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;ut=Qa(R,o)}else{let _e=o.layout?.messages;_e?.renderUserMessage&&R.role==="user"?ut=_e.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):_e?.renderAssistantMessage&&R.role==="assistant"?ut=_e.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):ut=gl(R,m,_e,o.messageActions,Ee,{loadingIndicatorRenderer:L,widgetConfig:o}),R.role!=="user"&&ut&&Sl(ut,R,o,_)}let Re=wo(R.id,R.role);Re.appendChild(ut),Rp(ho,R.id,pt,Re),b.appendChild(Re)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let Oe=Ie.getAttribute("data-persona-ask-sheet-for");Oe&&!oe.has(Oe)&&Yo(Le.composerOverlay,Oe)}),o.features?.toolCallDisplay?.grouped){let R=[],Ie=[],Oe=o.features.toolCallDisplay.groupedMode==="summary";g.forEach(Me=>{if(Me.variant==="tool"&&Me.toolCall&&ce){Ie.push(Me);return}Me.variant==="reasoning"&&!ee||((Ie.length>1||Oe&&Ie.length>0)&&R.push(Ie),Ie=[])}),(Ie.length>1||Oe&&Ie.length>0)&&R.push(Ie),R.forEach(Me=>{let At=Me.map(_e=>Array.from(b.children).find(Ft=>Ft instanceof HTMLElement&&Ft.getAttribute("data-wrapper-id")===_e.id)).filter(_e=>!!_e);if(At.length<(Oe?1:2))return;let pt=wo(`tool-group-${Me[0].id}`,"assistant");pt.setAttribute("data-persona-tool-group-row","true");let qt=document.createElement("div");qt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",qt.setAttribute("data-persona-tool-group","true");let ut=document.createElement("div");ut.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ut.id=`tool-group-summary-${Me[0].id}`;let Qt=`Called ${Me.length} ${Me.length===1?"tool":"tools"}`,Lt=o.toolCall?.renderGroupedSummary?.({messages:Me,toolCalls:Me.map(_e=>_e.toolCall).filter(_e=>!!_e),defaultSummary:Qt,config:o});Q(ut,Lt)||(ut.textContent=Qt);let Re=document.createElement("div");Re.className="persona-tool-group-stack persona-flex persona-flex-col",Re.id=`tool-group-stack-${Me[0].id}`,Re.setAttribute("data-persona-tool-group-stack","true"),qt.appendChild(ut),Oe||qt.appendChild(Re),pt.appendChild(qt),At[0].before(pt),At.forEach((_e,Ft)=>{if(Oe){_e.remove();return}_e.style.setProperty("--persona-message-row-max-width","100%");let Nt=document.createElement("div");Nt.className="persona-tool-group-item persona-relative",Nt.setAttribute("data-persona-tool-group-item","true"),Ft<At.length-1&&Nt.setAttribute("data-persona-tool-group-connector","true"),Nt.appendChild(_e),Re.appendChild(Nt)})})}Wp(ho,N);let en=g.some(R=>R.role==="assistant"&&R.streaming),Ct=g[g.length-1],kt=Ct?.role==="assistant"&&!Ct.streaming&&Ct.variant!=="approval";if(mn&&g.some(R=>R.role==="user")&&!en&&!kt){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:us},Ie=r.find(Me=>Me.renderLoadingIndicator),Oe=null;if(Ie?.renderLoadingIndicator&&(Oe=Ie.renderLoadingIndicator(R)),Oe===null&&o.loadingIndicator?.render&&(Oe=o.loadingIndicator.render(R)),Oe===null&&(Oe=us()),Oe){let Me=document.createElement("div"),At=o.loadingIndicator?.showBubble!==!1;Me.className=At?["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(" "),Me.setAttribute("data-typing-indicator","true"),Me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Me.appendChild(Oe);let pt=wo("typing-indicator","assistant");pt.appendChild(Me),b.appendChild(pt)}}if(!mn&&g.length>0){let R=g[g.length-1],Ie={config:o,lastMessage:R,messageCount:g.length},Oe=r.find(At=>At.renderIdleIndicator),Me=null;if(Oe?.renderIdleIndicator&&(Me=Oe.renderIdleIndicator(Ie)),Me===null&&o.loadingIndicator?.renderIdle&&(Me=o.loadingIndicator.renderIdle(Ie)),Me){let At=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1;At.className=pt?["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(" "),At.setAttribute("data-idle-indicator","true"),At.appendChild(Me);let qt=wo("idle-indicator","assistant");qt.appendChild(At),b.appendChild(qt)}}if(ld(b),Pa(i,b),Ii(i),ne.length>0)for(let{messageId:R,fingerprint:Ie,bubble:Oe}of ne){let Me=i.querySelector(`#wrapper-${R}`);Me&&(_s(Me,G.get(R)??"assistant"),Oe!==null&&(Me.replaceChildren(Oe),Me.setAttribute("data-bubble-fp",Ie),Oo.set(R,Ie)))}if(Oo.size>0)for(let R of Oo.keys())N.has(R)||Oo.delete(R);if(xe.length>0)for(let{messageId:R,fingerprint:Ie,bubble:Oe}of xe){let Me=i.querySelector(`#wrapper-${R}`);Me&&(_s(Me,G.get(R)??"assistant"),Oe!==null&&(Me.replaceChildren(Oe),Me.setAttribute("data-bubble-fp",Ie),yo.set(R,Ie)))}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:Ie,bubble:Oe}of tt){let Me=i.querySelector(`#wrapper-${R}`);Me&&(_s(Me,G.get(R)??"assistant"),Oe!==null&&(Me.replaceChildren(Oe),Me.setAttribute("data-bubble-fp",Ie),jn.set(R,Ie)))}if(jn.size>0)for(let R of jn.keys())N.has(R)||jn.delete(R)},kr=(i,g,m)=>{df(i,g,m),Xl()},Lr=null,pf=()=>{if(Lr)return;let i=m=>{let b=m.composedPath();b.includes(Be)||Ke&&b.includes(Ke)||ct(!1,"user")};Lr=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},gc=()=>{if(!Lr)return;(t.ownerDocument??document).removeEventListener("pointerdown",Lr,!0),Lr=null};Ue.push(()=>gc());let Pr=null,uf=()=>{if(Pr)return;let i=m=>{m.key==="Escape"&&(m.isComposing||ct(!1,"user"))};Pr=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},mc=()=>{if(!Pr)return;(t.ownerDocument??document).removeEventListener("keydown",Pr,!0),Pr=null};Ue.push(()=>mc());let Ir=!1,hc=new Set,ff=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},$o=()=>{if(!J())return;let i=Le.peekBanner,g=Le.peekTextNode;if(!i||!g)return;if(F){i.classList.remove("persona-pill-peek--visible");return}let m=_?.getMessages()??[],b;for(let Ct=m.length-1;Ct>=0;Ct--){let kt=m[Ct];if(kt.role==="assistant"&&kt.content){b=kt;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let A=b.content,L=!!b.streaming,Q=ff(),N=Ha(Q),G=N.type!=="none"?cr(N.type,Q?.plugins):null,oe=G?.isAnimating?.(b)===!0,fe=G!==null&&(L||oe);fe&&G&&!hc.has(G.name)&&(Fa(G,t),hc.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 je=fe?Ba(A,N.buffer,G,b,L):A;if(fe&&N.placeholder==="skeleton"&&L&&(!je||!je.trim())){let Ct=document.createElement("div"),kt=is();kt.classList.add("persona-pill-peek__skeleton"),Ct.appendChild(kt),Pa(g,Ct)}else{let Ct=Math.max(0,je.length-100),kt=je.length>100?je.slice(-100):je,R=Zn(kt);if(!fe||!G){let Ie=je.length>100?`\u2026${kt}`:kt;g.textContent!==Ie&&(g.textContent=Ie)}else{let Ie=R;(G.wrap==="char"||G.wrap==="word")&&(Ie=as(R,G.wrap,`peek-${b.id}`,{skipTags:G.skipTags,startIndex:Ct}));let Oe=document.createElement("div");if(Oe.innerHTML=Ie,G.useCaret&&kt.length>0){let Me=Da(),At=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),pt=At[At.length-1];pt?.parentNode?pt.parentNode.insertBefore(Me,pt.nextSibling):Oe.appendChild(Me)}Pa(g,Oe),G.onAfterRender?.({container:g,bubble:i,messageId:b.id,message:b,speed:N.speed,duration:N.duration})}}let en=mn||Ir;i.classList.toggle("persona-pill-peek--visible",en)};if(J()){let i=Le.peekBanner;if(i){let b=A=>{A.preventDefault(),A.stopPropagation(),ct(!0,"user")};i.addEventListener("pointerdown",b),Ue.push(()=>{i.removeEventListener("pointerdown",b)})}let g=()=>{Ir||(Ir=!0,$o())},m=()=>{Ir&&(Ir=!1,$o())};me.addEventListener("pointerenter",g),me.addEventListener("pointerleave",m),Ue.push(()=>{me.removeEventListener("pointerenter",g),me.removeEventListener("pointerleave",m)}),Ke&&(Ke.addEventListener("pointerenter",g),Ke.addEventListener("pointerleave",m),Ue.push(()=>{Ke.removeEventListener("pointerenter",g),Ke.removeEventListener("pointerleave",m)}))}let gf=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=Be.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",Ke){let xe=Ke.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}},Rr=()=>{if(!D())return;if(J()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=F?"expanded":"collapsed";Be.dataset.state=fe,Be.dataset.expandedSize=oe,Ke&&(Ke.dataset.state=fe,Ke.dataset.expandedSize=oe),Be.style.removeProperty("display"),Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),gf(F),ue.style.display=F?"flex":"none",Ls(),F?(pf(),uf()):(gc(),mc()),$o();return}let i=Wt(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?(Be.style.removeProperty("display"),Be.style.display=i?"flex":"",Be.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"),Ht?Ht.element.style.display="none":jt&&(jt.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!L?(Be.style.removeProperty("display"),Be.style.display="flex",Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Be.style.setProperty("display","none","important"),Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Be.style.display="",Be.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")),Ht?Ht.element.style.display=i?"none":"":jt&&(jt.style.display=i?"none":""))},ct=(i,g="user")=>{if(!D()||F===i)return;let m=F;F=i,Rr();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=Wt(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=ll(Q,o.launcher?.zIndex??zt))}Cn||(Cn=cl(t.ownerDocument))}else F||(xn?.(),xn=null,Cn?.(),Cn=null);F&&(Br(),pc()||(Ut()==="follow"?Gn(!0):cc()));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:Ge.active,streaming:_.isStreaming()})},hi=i=>{rt(i?"stop":"send"),V&&(V.disabled=i),Is.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)})},yi=()=>{Ge.active||ve&&ve.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>yi(),200)});let yc=()=>{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=ae.querySelector("[data-persona-intro-card]");if(i){let m=o.copy?.showWelcomeCard!==!1;i.style.display=m?"":"none",m?(ae.classList.remove("persona-gap-3"),ae.classList.add("persona-gap-6")):(ae.classList.remove("persona-gap-6"),ae.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 xo=null,mf=()=>{xo==null&&(xo=setInterval(()=>{let i=be.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(xo),xo=null;return}let g=Date.now();i.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=la(g-b))})},100))},bi=(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)=>bi(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)&&bi(m[Q],b[Q]))},bc=i=>{let{content:g,rawContent:m,llmContent:b,...A}=i;return A},vi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Pl(i),hf=(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))&&vi(b)&&vi(A)&&bi(bc(b),bc(A))},vc=null,zo=null,Co=null,Ln=null,$s=i=>{vc=i;let g,m;zo=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),!zo&&vi(L)&&(zo={index:A,id:L.id}),g&&m&&zo)break}kr(be,i,we),nl(be,fn.artifacts,{suppressTransition:mn}),mf(),ii(i),Gn(!mn),cf(i),i.length===0&&(Er(),Sr=!0,Hs=!1,Bs=null,Ds=!1),!ci||Ws?(ci=!0,Ar=g?.id??null,di=m?.id??null):g&&g.id!==Ar?(Ar=g.id,sf(g.id)):m&&m.id!==di&&af(),m&&(di=m.id),lf(i);let b=Ge.lastUserMessageId;g&&g.id!==b&&(Ge.lastUserMessageId=g.id,l.emit("user:message",g)),Ge.lastUserMessageWasVoice=!!g?.viaVoice,fi(i),$o()},wi=()=>{Ln!==null&&(cancelAnimationFrame(Ln),Ln=null);let i=Co;Co=null,i&&$s(i)},wc=()=>{Ln!==null&&cancelAnimationFrame(Ln),Ln=null,Co=null},yf=i=>{let g=Co??vc;if(mn&&g&&zo&&hf(g,i,zo)){Co=i,Ln===null&&(Ln=requestAnimationFrame(()=>{Ln=null;let m=Co;Co=null,m&&$s(m)}));return}if(i.length===0){wc(),$s(i);return}wi(),$s(i)};_=new ha(o,{onMessagesChanged(i){yf(i)},onStatusChanged(i){let g=o.statusIndicator??{};St(T,(b=>b==="idle"?g.idleText??Pt.idle:b==="connecting"?g.connectingText??Pt.connecting:b==="connected"?g.connectedText??Pt.connected:b==="error"?g.errorText??Pt.error:b==="paused"?g.pausedText??Pt.paused:b==="resuming"?g.resumingText??Pt.resuming:Pt[b])(i),g,i)},onStreamingChanged(i){i||(_?.getMessages().length===0?wc():wi()),mn=i,hi(i),_&&kr(be,_.getMessages(),we),i||Gn(!0),Zt(),zl(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(),jo();break;case"processing":Pn(),kf();break;case"speaking":Pn(),Lf();break;default:i==="idle"&&_.isBargeInActive()?(Pn(),jo(),V?.setAttribute("aria-label","End voice session")):(Ge.active=!1,Pn(),kn("system"),yn());break}},onArtifactsState(i){fn=i,i.artifacts.length===0&&(Do=!1),nl(be,i.artifacts,{suppressTransition:mn}),En(),fi()},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})}}),it.current=_,Ue.push(()=>_.cancel());let xi=null;if(_.onReadAloudChange((i,g)=>{Gl=i,Ql=g,Xl();let m=i??xi;i&&(xi=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"&&(xi=null)}),ci=!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),$e?.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 xc=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=Il(i.metadata),k.syncFromMetadata()),i.messages?.length){Ws=!0;try{_.hydrateMessages(i.messages)}finally{Ws=!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(()=>xc()):xc();let Cc=()=>{!J()||F||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ct(!0,"auto")},bf=(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),Wy(A)}}:i:g,vf=()=>{let g=ve.getInlineMessageFields?.();return g&&g.contentSegments.some(b=>b.kind==="mention")?g.contentSegments:void 0},Wr=!1,wf=async i=>{let g=ve.value.trim(),m=xt?.hasAttachments()??!1,b=g?await(Jt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(b?.kind==="action"){ve.value="",ve.style.height="auto",Hr(),Jt?.clear();return}let A=Jt?.collectForSubmit()??null,L=b?.kind==="server"?b.mentions:null,Q=bf(A,L),N=b?.kind==="prompt"?b.sendText:g,G=!!A&&A.refs.length>0;if(!N&&!m&&!G&&!L)return;Cc();let oe;m&&(oe=[],oe.push(...xt.getContentParts()),N&&oe.push(er(N)));let fe=b?.kind==="prompt"?void 0:vf();ve.value="",ve.style.height="auto",Hr(),_.sendMessage(N,{contentParts:oe,mentions:Q??void 0,contentSegments:fe,viaVoice:i?.viaVoice}),m&&xt.clearAttachments(),A&&Jt?.clear()},Ci=async i=>{if(!Wr){Wr=!0;try{await wf(i)}finally{Wr=!1}}},Ac=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),$e?.reset(),Fe?.update();return}Wr||Ci()},xf=()=>o.features?.composerHistory!==!1,Ai={...sl},Si=!1,Hr=()=>{Ai={...sl}},Cf=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Af=i=>{if(!ve)return;Si=!0,ve.value=i,ve.dispatchEvent(new Event("input",{bubbles:!0})),Si=!1;let g=ve.value.length;ve.setSelectionRange(g,g)},Sf=i=>{Si||(i.isComposing||Jt?.handleInput(i.inputType??void 0),Hr())},Tf=i=>{if(ve&&!(!i.isComposing&&Jt?.handleKeydown(i))){if(xf()&&(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=kp({direction:i.key==="ArrowUp"?"up":"down",history:Cf(),currentValue:ve.value,atStart:g,state:Ai});if(Ai=m.state,m.handled){i.preventDefault(),m.value!==void 0&&Af(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(_.isStreaming()){i.preventDefault();return}if(Wr){i.preventDefault();return}Hr(),i.preventDefault(),de.click()}}},Sc=i=>{i.key!=="Escape"||i.isComposing||_.isStreaming()&&i.composedPath().includes(ue)&&(_.cancel(),$e?.reset(),Fe?.update(),Hr(),i.preventDefault(),i.stopImmediatePropagation())},Mf=async i=>{if(o.attachments?.enabled!==!0||!xt)return;let g=Ly(i.clipboardData);g.length!==0&&(i.preventDefault(),await xt.handleFiles(g))},an=null,An=!1,Uo=null,vt=null,Tc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,zs=(i="user")=>{if(An||_.isStreaming())return;let g=Tc();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,Uo&&clearTimeout(Uo),(Q||N)&&(Uo=window.setTimeout(()=>{ve.value.trim()&&an&&An&&(Qn(),Ci({viaVoice:!0}))},b))},an.onerror=L=>{L.error!=="no-speech"&&Qn()},an.onend=()=>{if(An){let L=ve.value.trim();L&&L!==A.trim()&&Ci({viaVoice:!0}),Qn()}};try{if(an.start(),An=!0,Ge.active=!0,i!=="system"&&(Ge.manuallyDeactivated=!1),kn(i),yn(),V){let L=o.voiceRecognition??{};vt={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,Uo&&(clearTimeout(Uo),Uo=null),an){try{an.stop()}catch{}an=null}if(Ge.active=!1,kn(i),yn(),V){if(V.classList.remove("persona-voice-recording"),vt){V.style.backgroundColor=vt.backgroundColor,V.style.color=vt.color,V.style.borderColor=vt.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",vt.color||"currentColor"),vt=null}V.setAttribute("aria-label","Start voice recognition")}}},Ef=(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,je=i?.backgroundColor??g?.backgroundColor,dt=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",dt?N.style.color=dt:N.style.color="var(--persona-text, #111827)";let en=re(oe,xe,dt||"currentColor",1.5);en?N.appendChild(en):N.textContent="\u{1F3A4}",je?N.style.backgroundColor=je: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 Ct=i?.showTooltip??!1;return Dt({anchor:N,trigger:Q,text:()=>N.getAttribute("aria-label")??G,enabled:Ct}),{micButton:N,micButtonWrapper:Q}},Ti=()=>{if(!V||vt)return;let i=o.voiceRecognition??{};vt={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}},Mi=(i,g)=>{if(!V)return;let m=V.querySelector("svg");m&&m.remove();let b=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=re(i,b,g,1.5);A&&V.appendChild(A)},Us=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},jo=()=>{if(!V)return;Ti();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,m=i.recordingIconColor,b=i.recordingBorderColor;if(Us(),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")},kf=()=>{if(!V)return;Ti();let i=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),m=i.processingIconName??"loader",b=i.processingIconColor??vt?.color??"",A=i.processingBackgroundColor??vt?.backgroundColor??"",L=i.processingBorderColor??vt?.borderColor??"";Us(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=A,V.style.borderColor=L;let Q=b||"currentColor";V.style.color=Q,Mi(m,Q),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},Lf=()=>{if(!V)return;Ti();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??vt?.color??"":vt?.color??""),L=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),Q=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":vt?.borderColor??"");Us(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=L,V.style.borderColor=Q;let N=A||"currentColor";V.style.color=N,Mi(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&&(Us(),vt&&(V.style.backgroundColor=vt.backgroundColor??"",V.style.color=vt.color??"",V.style.borderColor=vt.borderColor??"",Mi(vt.iconName,vt.color||"currentColor"),vt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},js=()=>{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(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,yn(),kn("user"),Pn()});return}_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),Ge.manuallyDeactivated=!_.isVoiceActive(),yn(),kn("user"),_.isVoiceActive()?jo():Pn()});return}if(An){let i=ve.value.trim();Ge.manuallyDeactivated=!0,yn(),Qn("user"),i&&(ve.value="",ve.style.height="auto",_.sendMessage(i))}else Ge.manuallyDeactivated=!1,yn(),zs("user")};jl=js,V&&(V.addEventListener("click",js),Ue.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Pn()):Qn("system"),V&&V.removeEventListener("click",js)}));let Pf=l.on("assistant:complete",()=>{oc&&(Ge.active||Ge.manuallyDeactivated||oc==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),kn("auto"),_.isVoiceActive()&&jo()}):zs("auto"))},600))});Ue.push(Pf);let If=l.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});Ue.push(If);let Mc=()=>{ct(!F,"user")},Ht=null,jt=null;if(M&&!J()){let{instance:i,element:g}=pl({config:o,plugins:r,onToggle:Mc});Ht=i,i||(jt=g)}Ht?t.appendChild(Ht.element):jt&&t.appendChild(jt),Rr(),ii(),yc(),hi(_.isStreaming()),pc()||(Ut()==="follow"?Gn(!0):cc()),Zu(),z&&(!M||J()?setTimeout(()=>yi(),0):F&&setTimeout(()=>yi(),200));let Br=()=>{if(J()){Bo(),Rr();return}let i=Wt(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){vr(),wr=ks();return}let G=!1;j&&(j=!1,vr(),G=!0);let oe=ks();if(!G&&oe!==wr&&(vr(),G=!0),wr=oe,G&&si(),!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(Es(),!m){let fe=b.innerHeight,ne=64,xe=o.launcher?.heightOffset??0,je=Math.max(200,fe-ne),dt=Math.min(640,je),tt=Math.max(200,dt-xe);me.style.height=`${tt}px`}}finally{if(Bo(),Rr(),F&&M){let oe=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),fe=o.launcher?.sidebarMode??!1,ne=o.launcher?.mobileFullscreen??!0,xe=Wt(o)&&ne&&oe,je=fe||ne&&oe&&M||xe;if(je&&!Cn){let dt=t.getRootNode(),tt=dt instanceof ShadowRoot?dt.host:t.closest(".persona-host");tt&&!xn&&(xn=ll(tt,o.launcher?.zIndex??zt)),Cn=cl(t.ownerDocument)}else je||(xn?.(),xn=null,Cn?.(),Cn=null)}}};Br();let Ec=t.ownerDocument.defaultView??window;if(Ec.addEventListener("resize",Br),Ue.push(()=>Ec.removeEventListener("resize",Br)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Bo()});i.observe($),Ue.push(()=>i.disconnect())}rn=ae.scrollTop;let kc=Tn(ae),Lc=()=>{let i=ae.scrollTop,g=Tn(ae),m=g<kc;if(kc=g,!_n()){rn=i,Zt();return}let{action:b,nextLastScrollTop:A}=Ra({following:Yt.isFollowing(),currentScrollTop:i,lastScrollTop:rn,nearBottom:ao(ae,Fs),userScrollThreshold:Ju,isAutoScrolling:sn||Rs||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rn=A,b==="resume"){Os()||Kn();return}b==="pause"&&Mr()};if(ae.addEventListener("scroll",Lc,{passive:!0}),Ue.push(()=>ae.removeEventListener("scroll",Lc)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{rf(),Ii(be)});i.observe(be),i.observe(ae),Ue.push(()=>i.disconnect())}let Pc=()=>{_n()&&Yt.isFollowing()&&Os()&&Mr()},Ic=ae.ownerDocument;Ic.addEventListener("selectionchange",Pc),Ue.push(()=>{Ic.removeEventListener("selectionchange",Pc)});let Rf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Rc=i=>{Rf.has(i.key)&&(vo(),Ol()&&_n()&&Yt.isFollowing()&&Mr())},Wc=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(vo(),Ol()&&_n()&&Yt.isFollowing()&&Mr())};ae.addEventListener("keydown",Rc),ae.addEventListener("focusin",Wc),Ue.push(()=>{ae.removeEventListener("keydown",Rc),ae.removeEventListener("focusin",Wc)});let Hc=i=>{if(i.deltaY!==0&&vo(),!_n())return;let g=Wa({following:Yt.isFollowing(),deltaY:i.deltaY,nearBottom:ao(ae,Fs),resumeWhenNearBottom:!0});g==="pause"?Mr():g==="resume"&&!Os()&&Kn()};ae.addEventListener("wheel",Hc,{passive:!0}),ae.addEventListener("touchmove",vo,{passive:!0}),ae.addEventListener("pointerdown",vo,{passive:!0}),Ue.push(()=>{ae.removeEventListener("touchmove",vo),ae.removeEventListener("pointerdown",vo)}),Ue.push(()=>ae.removeEventListener("wheel",Hc)),Mt.addEventListener("click",()=>{Er(),ae.scrollTop=ae.scrollHeight,rn=ae.scrollTop,Kn(),Gn(!0),Zt()}),Ue.push(()=>Mt.remove()),Ue.push(()=>{ac(),Er()});let Bc=()=>{S&&(mo&&(S.removeEventListener("click",mo),mo=null),D()?(S.style.display="",mo=()=>{ct(!1,"user")},S.addEventListener("click",mo)):S.style.display="none")};Bc(),(()=>{let{clearChatButton:i}=Le;i&&i.addEventListener("click",()=>{_.clearMessages(),ho.clear(),Kn(),Yo(Le.composerOverlay);try{localStorage.removeItem(fr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${fr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==fr)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&&ui(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},k.syncFromMetadata(),Ae?.clear(),$e?.reset(),Fe?.update()})})(),X&&X.addEventListener("submit",Ac);let Dc=[["keydown",Tf],["input",Sf],["paste",Mf],["focus",Vu]],Fc=i=>{if(i)for(let[g,m]of Dc)i.addEventListener(g,m)},Nc=i=>{if(i)for(let[g,m]of Dc)i.removeEventListener(g,m)};Fc(ve),Jt?.onComposerSwap((i,g)=>{Nc(g),ve=i,Fc(i)});let Oc=t.ownerDocument??document;Oc.addEventListener("keydown",Sc,!0);let _c="persona-attachment-drop-active",Dr=0,Ei=()=>{Dr=0,ue.classList.remove(_c)},qo=()=>o.attachments?.enabled===!0&&xt!==null,$c=i=>{!Ja(i.dataTransfer)||!qo()||(Dr++,Dr===1&&ue.classList.add(_c))},zc=i=>{!Ja(i.dataTransfer)||!qo()||(Dr--,Dr<=0&&Ei())},Uc=i=>{!Ja(i.dataTransfer)||!qo()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},jc=i=>{if(!Ja(i.dataTransfer)||!qo())return;i.preventDefault(),i.stopPropagation(),Ei();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&xt.handleFiles(g)},Xn=!0;ue.addEventListener("dragenter",$c,Xn),ue.addEventListener("dragleave",zc,Xn),t.addEventListener("dragover",Uc,Xn),t.addEventListener("drop",jc,Xn);let qs=t.ownerDocument,qc=i=>{qo()&&i.preventDefault()},Vc=i=>{qo()&&i.preventDefault()};qs.addEventListener("dragover",qc),qs.addEventListener("drop",Vc),Ue.push(()=>{X&&X.removeEventListener("submit",Ac),Nc(ve),Oc.removeEventListener("keydown",Sc,!0),Jt?.destroy()}),Ue.push(()=>{ue.removeEventListener("dragenter",$c,Xn),ue.removeEventListener("dragleave",zc,Xn),t.removeEventListener("dragover",Uc,Xn),t.removeEventListener("drop",jc,Xn),qs.removeEventListener("dragover",qc),qs.removeEventListener("drop",Vc),Ei()}),Ue.push(()=>{_.cancel()}),Ht?Ue.push(()=>{Ht?.destroy()}):jt&&Ue.push(()=>{jt?.remove()});let Et={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=vu(o,i),Ls(),es(t,o),hs(t,o),ys(t,o),En(),o.colorScheme!==A&&nc();let xe=Ml.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,ie=o.features?.scrollToBottom??{};let je=Ut();Z=o.features?.scrollBehavior??{},je!==Ut()&&(Er(),Kn()),Ul(),Zt();let dt=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!dt){if(Ae||(pe=new gs(ye),Ae=new fs(Te,pe),$e=$e??new ms,pe.open().then(()=>Ae?.restore()).catch(()=>{}),_.setSSEEventCallback((te,Ve)=>{o.onSSEEvent?.(te,Ve),$e?.processEvent(te,Ve),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Ve)})})),!et&&H){let te=o.features?.eventStream?.classNames,Ve="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",Ve),et.style.width="28px",et.style.height="28px",et.style.color=Kt.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let gt=re("activity","18px","currentColor",1.5);gt&&et.appendChild(gt);let nt=Le.clearChatButtonWrapper,st=Le.closeButtonWrapper,_t=nt||st;_t&&_t.parentNode===H?H.insertBefore(et,_t):H.appendChild(et),et.addEventListener("click",()=>{ot?yr():ti()})}}else!Y&&dt&&(yr(),et&&(et.remove(),et=null),Ae?.clear(),pe?.destroy(),Ae=null,pe=null,$e?.reset(),$e=null);if(o.launcher?.enabled===!1&&Ht&&(Ht.destroy(),Ht=null),o.launcher?.enabled===!1&&jt&&(jt.remove(),jt=null),o.launcher?.enabled!==!1&&!Ht&&!jt){let{instance:te,element:Ve}=pl({config:o,plugins:r,onToggle:Mc});Ht=te,te||(jt=Ve),t.appendChild(Ve)}Ht&&Ht.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?_a(o,tt,{showClose:D(),onClose:()=>ct(!1,"user")}):Io({config:o,showClose:D(),onClose:()=>ct(!1,"user")});ht.replaceHeader(te),H=ht.header.element,E=ht.header.iconHolder,W=ht.header.headerTitle,q=ht.header.headerSubtitle,S=ht.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(Le.clearChatButtonWrapper){let te=tt.showClearChat;if(te!==void 0){Le.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Ve}=Le;Ve&&!Ve.classList.contains("persona-absolute")&&(te?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let Ct=o.layout?.showHeader!==!1;H&&(H.style.display=Ct?"":"none");let kt=o.layout?.showFooter!==!1;$&&($.style.display=kt?"":"none"),Bo(),Zt(),M!==x?M?ct(P,"auto"):(F=!0,Rr()):P!==K&&ct(P,"auto"),K=P,x=M,Br(),Bc();let Oe=JSON.stringify(o.toolCall)!==JSON.stringify(g),Me=JSON.stringify(o.messageActions)!==JSON.stringify(m),At=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),pt=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,qt=o.iterationDisplay!==Q,ut=(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);(Oe||Me||At||pt||qt||ut)&&_&&(li++,kr(be,_.getMessages(),we));let Lt=o.features?.streamAnimation?.type;if(Lt!==ne&&Lt&&Lt!=="none"){let te=cr(Lt,o.features?.streamAnimation?.plugins);te&&Fa(te,t)}let Re=o.launcher??{},_e=Re.headerIconHidden??!1,Ft=o.layout?.header?.showIcon,Nt=_e||Ft===!1,wt=Re.headerIconName,lt=Re.headerIconSize??"48px";if(E){let te=ue.querySelector(".persona-border-b-persona-divider"),Ve=te?.querySelector(".persona-flex-col");if(Nt)E.style.display="none",te&&Ve&&!te.contains(Ve)&&te.insertBefore(Ve,te.firstChild);else{if(E.style.display="",E.style.height=lt,E.style.width=lt,te&&Ve&&(te.contains(E)?E.nextSibling!==Ve&&(E.remove(),te.insertBefore(E,Ve)):te.insertBefore(E,Ve)),wt){let nt=parseFloat(lt)||24,st=re(wt,nt*.6,"currentColor",1);st?E.replaceChildren(st):E.textContent=Re.agentIconText??"\u{1F4AC}"}else if(Re.iconUrl){let nt=E.querySelector("img");if(nt)nt.src=Re.iconUrl,nt.style.height=lt,nt.style.width=lt;else{let st=document.createElement("img");st.src=Re.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=lt,st.style.width=lt,E.replaceChildren(st)}}else{let nt=E.querySelector("svg"),st=E.querySelector("img");(nt||st)&&E.replaceChildren(),E.textContent=Re.agentIconText??"\u{1F4AC}"}let gt=E.querySelector("img");gt&&(gt.style.height=lt,gt.style.width=lt)}}let ft=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(W&&(W.style.display=ft===!1?"none":""),q&&(q.style.display=Ze===!1?"none":""),S){let te=D()&&o.layout?.header?.showCloseButton!==!1;S.style.display=te?"":"none";let Ve=Re.closeButtonSize??"32px",gt=Re.closeButtonPlacement??"inline";S.style.height=Ve,S.style.width=Ve;let{closeButtonWrapper:nt}=Le,st=gt==="top-right",_t=nt?.classList.contains("persona-absolute");if(nt&&st!==_t)if(nt.remove(),st)nt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(nt);else{let Yn=Re.clearChat?.placement??"inline",Or=Re.clearChat?.enabled??!0;nt.className=Or&&Yn==="inline"?"":"persona-ml-auto";let Kc=ue.querySelector(".persona-border-b-persona-divider");Kc&&Kc.appendChild(nt)}if(S.style.color=Re.closeButtonColor||Kt.actionIconColor,Re.closeButtonBackgroundColor?(S.style.backgroundColor=Re.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),Re.closeButtonBorderWidth||Re.closeButtonBorderColor){let Yn=Re.closeButtonBorderWidth||"0px",Or=Re.closeButtonBorderColor||"transparent";S.style.border=`${Yn} solid ${Or}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");Re.closeButtonBorderRadius?(S.style.borderRadius=Re.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),Re.closeButtonPaddingX?(S.style.paddingLeft=Re.closeButtonPaddingX,S.style.paddingRight=Re.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),Re.closeButtonPaddingY?(S.style.paddingTop=Re.closeButtonPaddingY,S.style.paddingBottom=Re.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let tn=Re.closeButtonIconName??"x",bn=Re.closeButtonIconText??"\xD7";S.innerHTML="";let Bt=re(tn,"28px","currentColor",1);Bt?(Bt.style.display="block",S.appendChild(Bt)):S.textContent=bn;let $t=Re.closeButtonTooltipText??"Close chat",Rn=Re.closeButtonShowTooltip??!0;S.setAttribute("aria-label",$t),nt&&Dt({anchor:S,trigger:nt,text:()=>S?.getAttribute("aria-label")??$t,enabled:Rn})}let{clearChatButton:De,clearChatButtonWrapper:mt}=Le;if(De){let te=Re.clearChat??{},Ve=te.enabled??!0,gt=o.layout?.header?.showClearChat,nt=gt!==void 0?gt:Ve,st=te.placement??"inline";if(mt){mt.style.display=nt?"":"none";let{closeButtonWrapper:_t}=Le;!J()&&_t&&!_t.classList.contains("persona-absolute")&&(nt?_t.classList.remove("persona-ml-auto"):_t.classList.add("persona-ml-auto"));let tn=st==="top-right",bn=mt.classList.contains("persona-absolute");if(!J()&&tn!==bn&&nt){if(mt.remove(),tn)mt.className="persona-absolute persona-top-4 persona-z-50",mt.style.right="48px",ue.style.position="relative",ue.appendChild(mt);else{mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",mt.style.right="";let $t=ue.querySelector(".persona-border-b-persona-divider"),Rn=Le.closeButtonWrapper;$t&&Rn&&Rn.parentElement===$t?$t.insertBefore(mt,Rn):$t&&$t.appendChild(mt)}let Bt=Le.closeButtonWrapper;Bt&&!Bt.classList.contains("persona-absolute")&&(tn?Bt.classList.add("persona-ml-auto"):Bt.classList.remove("persona-ml-auto"))}}if(nt){if(!J()){let Yn=te.size??"32px";De.style.height=Yn,De.style.width=Yn}let _t=te.iconName??"refresh-cw",tn=te.iconColor??"";De.style.color=tn||Kt.actionIconColor,De.innerHTML="";let bn=J()?"14px":"20px",Bt=re(_t,bn,"currentColor",1);if(Bt&&(Bt.style.display="block",De.appendChild(Bt)),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",Or=te.borderColor||"transparent";De.style.border=`${Yn} solid ${Or}`,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),mt&&Dt({anchor:De,trigger:mt,text:()=>De?.getAttribute("aria-label")??$t,enabled:Rn})}}let Ot=o.actionParsers&&o.actionParsers.length?o.actionParsers:[kl],cn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[bs.message,bs.messageAndClick];k=Ll({parsers:Ot,handlers:cn,getSessionMetadata:v,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),we=Lu(o,k,Ce),_.updateConfig(o),kr(be,_.getMessages(),we),ii(),yc(),hi(_.isStreaming());let Fr=o.voiceRecognition?.enabled===!0,Vs=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Tt=o.voiceRecognition?.provider?.type==="runtype";if(Fr&&(Vs||Tt))if(!V||!ze){let te=Ef(o.voiceRecognition,o.sendButton);te&&(V=te.micButton,ze=te.micButtonWrapper,qe.insertBefore(ze,un),V.addEventListener("click",js),V.disabled=_.isStreaming())}else{let te=o.voiceRecognition??{},Ve=o.sendButton??{},gt=te.iconName??"mic",nt=Ve.size??"40px",st=te.iconSize??nt,_t=parseFloat(st)||24;V.style.width=st,V.style.height=st,V.style.minWidth=st,V.style.minHeight=st;let tn=te.iconColor??Ve.textColor;V.innerHTML="";let bn=re(gt,_t,tn||"currentColor",1.5);bn?V.appendChild(bn):V.textContent="\u{1F3A4}";let Bt=te.backgroundColor??Ve.backgroundColor;Bt?V.style.backgroundColor=Bt: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),ze&&Dt({anchor:V,trigger:ze,text:()=>V?.getAttribute("aria-label")??$t,enabled:Rn}),ze.style.display="",V.disabled=_.isStreaming()}else V&&ze&&(ze.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():An&&Qn());if(o.attachments?.enabled===!0){if(!We||!Se){let te=o.attachments??{},gt=(o.sendButton??{}).size??"40px";Je||(Je=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Je.style.display="none",X.insertBefore(Je,ve)),Pe||(Pe=document.createElement("input"),Pe.type="file",Pe.accept=(te.allowedTypes??Fn).join(","),Pe.multiple=(te.maxFiles??4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),X.insertBefore(Pe,ve)),We=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",st=gt,_t=parseFloat(st)||40,tn=Math.round(_t*.6);Se.style.width=st,Se.style.height=st,Se.style.minWidth=st,Se.style.minHeight=st,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(),Pe?.click()}),We.appendChild(Se);let Bt=te.buttonTooltipText??"Attach file";Dt({anchor:Se,trigger:We,text:()=>Se?.getAttribute("aria-label")??Bt}),ke?ke.append(We):X.appendChild(We),!xt&&Pe&&Je&&(xt=Jr.fromConfig(te),xt.setPreviewsContainer(Je),Pe.addEventListener("change",async()=>{xt&&Pe?.files&&(await xt.handleFileSelect(Pe.files),Pe.value="")}))}else{We.style.display="";let te=o.attachments??{};Pe&&(Pe.accept=(te.allowedTypes??Fn).join(","),Pe.multiple=(te.maxFiles??4)>1),xt&&xt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Pu(o.attachments?.dropOverlay)),Se){let te=o.attachments??{},Ve=te.buttonTooltipText??"Attach file";Se.setAttribute("aria-label",Ve),Se.textContent="";let gt=parseFloat(o.sendButton?.size??"40px")||40,nt=re(te.buttonIconName??"paperclip",Math.round(gt*.6),"currentColor",1.5);nt?Se.appendChild(nt):Se.textContent="\u{1F4CE}",We&&Dt({anchor:Se,trigger:We,text:()=>Se?.getAttribute("aria-label")??Ve})}}else We&&(We.style.display="none"),xt&&xt.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Rt=o.sendButton??{},Nr=Rt.useIcon??!1,Gs=Rt.iconText??"\u2191",Vo=Rt.iconName,Qs=Rt.tooltipText??"Send message",ki=Rt.showTooltip??!1,Ao=Rt.size??"40px",In=Rt.backgroundColor,So=Rt.textColor;if(Nr){if(de.style.width=Ao,de.style.height=Ao,de.style.minWidth=Ao,de.style.minHeight=Ao,de.style.fontSize="18px",de.style.lineHeight="1",So?de.style.color=So:de.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(de.innerHTML="",Vo){let te=parseFloat(Ao)||24,Ve=So?.trim()||"currentColor",gt=re(Vo,te,Ve,2);gt?de.appendChild(gt):de.textContent=Gs}else de.textContent=Gs;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"),So?de.style.color=So:de.classList.add("persona-text-white");Rt.borderWidth?(de.style.borderWidth=Rt.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),Rt.borderColor?de.style.borderColor=Rt.borderColor:de.style.borderColor="",Rt.paddingX?(de.style.paddingLeft=Rt.paddingX,de.style.paddingRight=Rt.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Rt.paddingY?(de.style.paddingTop=Rt.paddingY,de.style.paddingBottom=Rt.paddingY):(de.style.paddingTop="",de.style.paddingBottom=""),_.isStreaming()||de.setAttribute("aria-label",Qs),un&&Dt({anchor:de,trigger:un,text:()=>de.getAttribute("aria-label")??Qs,enabled:ki});let Xs=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Xs?(be.style.maxWidth=Xs,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",X&&(X.style.maxWidth=Xs,X.style.marginLeft="auto",X.style.marginRight="auto"),yt&&(yt.style.maxWidth=Xs,yt.style.marginLeft="auto",yt.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=""),yt&&(yt.style.maxWidth="",yt.style.marginLeft="",yt.style.marginRight=""));let Jn=o.statusIndicator??{},Wf=Jn.visible??!0;if(T.style.display=Wf?"":"none",_){let te=_.getStatus();St(T,(gt=>gt==="idle"?Jn.idleText??Pt.idle:gt==="connecting"?Jn.connectingText??Pt.connecting:gt==="connected"?Jn.connectedText??Pt.connected:gt==="error"?Jn.errorText??Pt.error:Pt[gt])(te),Jn,te)}T.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Hf=Jn.align==="left"?"persona-text-left":Jn.align==="center"?"persona-text-center":"persona-text-right";T.classList.add(Hf)},open(){D()&&ct(!0,"api")},close(){D()&&ct(!1,"api")},toggle(){D()&&ct(!F,"api")},reconnect(){_.reconnectNow()},clearChat(){Mn=!1,_.clearMessages(),ho.clear(),Kn();try{localStorage.removeItem(fr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${fr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==fr)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&&ui(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},k.syncFromMetadata(),Ae?.clear(),$e?.reset(),Fe?.update()},setMessage(i){return!ve||_.isStreaming()?!1:(!F&&D()&&ct(!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()&&ct(!0,"system"),ve.value="",ve.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!F&&D()&&ct(!0,"system"),Ge.manuallyDeactivated=!1,yn(),_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),kn("user"),_.isVoiceActive()&&jo()})),!0):An?!0:Tc()?(!F&&D()&&ct(!0,"system"),Ge.manuallyDeactivated=!1,yn(),zs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,yn(),kn("user"),Pn()}),!0):!1:An?(Ge.manuallyDeactivated=!0,yn(),Qn("user"),!0):!1},injectMessage(i){return!F&&D()&&ct(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!F&&D()&&ct(!0,"system");let g=_.injectAssistantMessage(i);return le&&(le=!1,ge&&(clearTimeout(ge),ge=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(i){return!F&&D()&&ct(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!F&&D()&&ct(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!F&&D()&&ct(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!F&&D()&&ct(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!F&&D()&&ct(!0,"system"),_.injectTestEvent(i)},async connectStream(i,g){return _.connectStream(i,g)},__pushEventStreamEvent(i){Ae&&($e?.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||ti()},hideEventStream(){ot&&yr()},isEventStreamVisible(){return ot},showArtifacts(){Gt(o)&&(Mn=!1,Do=!0,En(),Ye?.setMobileOpen(!0))},hideArtifacts(){Gt(o)&&(Mn=!0,En())},upsertArtifact(i){return Gt(o)?(To(o.features?.artifacts,i.artifactType)==="panel"&&(Mn=!1,Do=!0),_.upsertArtifact(i)):null},selectArtifact(i){Gt(o)&&_.selectArtifact(i)},clearArtifacts(){Gt(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 Ge.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:Ge.active,streaming:_.isStreaming()}},showCSATFeedback(i){!F&&D()&&ct(!0,"system");let g=be.querySelector(".persona-feedback-container");g&&g.remove();let m=Mu({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()&&ct(!0,"system");let g=be.querySelector(".persona-feedback-container");g&&g.remove();let m=Eu({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(){wi(),xo!=null&&(clearInterval(xo),xo=null),Ue.forEach(i=>i()),Be.remove(),Ke?.remove(),Ht?.destroy(),jt?.remove(),mo&&S.removeEventListener("click",mo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:Et,getMessages:Et.getMessages,getStatus:Et.getStatus,getMetadata:Et.getPersistentMetadata,updateMetadata:Et.updatePersistentMetadata,clearHistory:()=>Et.clearChat(),setVoiceActive:m=>m?Et.startVoiceRecognition():Et.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ue.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)&&Et.focusInput()};if(window.addEventListener("persona:focusInput",g),Ue.push(()=>{window.removeEventListener("persona:focusInput",g)}),Y){let N=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&Et.showEventStream()},G=oe=>{let fe=oe.detail;(!fe?.instanceId||fe.instanceId===i)&&Et.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",G),Ue.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",G)})}let m=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===i)&&Et.showArtifacts()},b=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===i)&&Et.hideArtifacts()},A=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==i||G?.artifact&&Et.upsertArtifact(G.artifact)},L=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==i||typeof G?.id=="string"&&Et.selectArtifact(G.id)},Q=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===i)&&Et.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),Ue.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=Py(o.persistState);if(ln&&D()){let i=Iy(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(()=>{Et.open(),setTimeout(()=>{if(L||Q)Et.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),Ue.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(w&&D()&&setTimeout(()=>{Et.open()},0),$o(),!Xu){let i=Ys(()=>{_&&(li++,ho.clear(),kr(be,_.getMessages(),we))});Ue.push(i)}return Et};var Ru=(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},Hy=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},By=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Dy=(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.")},Wu=(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"},Bl=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=""},Hu=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Bl(t)},Rl=t=>{t.style.transition=""},Wl=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=""},Hl=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Ya=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},Fy=(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))},Ny=(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)},Oy=t=>{let e=rr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Vt(e,r)??r;return{inset:o(n?.inset,wa),canvasBackground:o(n?.canvasBackground,xa)}},Bu=(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},_y=(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??"";Fy(t,e,n,o,d),Ny(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"),Wl(e),Rl(o),Hu(o),Hl(n),Ya(r,o),Bu(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"),Hu(o),Hy(o,p.maxHeight),Bu(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",Wl(e),Rl(o),Hl(n),Ya(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",Rl(o),Bl(o),Ya(r,o);let k=Ru(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="",Wl(e),Bl(o),Hl(n),Ya(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",By(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(${Ru(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"}}},$y=(t,e)=>{let n=t.ownerDocument.createElement("div");return Wu(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Wu(n,o)},destroy(){n.remove()}}},zy=(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?Oy(e):null};C();let I=()=>{_y(a,l,p,d,c,e,u,v)},B=null,k=()=>{B?.(),B=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(B=Ca(()=>{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,Dy(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()}}},Du=(t,e)=>Wt(e)?zy(t,e):$y(t,e);var vs={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Fu=.15,Nu=1.5,Dl="persona-preview-shell-theme",Uy={load:()=>null,save:()=>{},clear:()=>{}},jy=["How do I get started?","Pricing & plans","Talk to support"];function Fl(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qy(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 Ou(t){let e=qy(t);return`* { box-sizing: border-box; }
139
+ ${vt?"background: transparent !important;":""}
140
+ `}if(!b&&!i){let St="max-height: -moz-available !important; max-height: stretch !important;",Yt=g?"":"padding-top: 1.25em !important;",oa=g?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;He.style.cssText+=St+Yt+oa}pn()};Os(),cs(e,o),Ts(e,o),Ms(e,o),Er=()=>{Os(),cs(e,o),Ts(e,o),Ms(e,o),Rs?e.style.setProperty("--persona-artifact-welded-outer-radius",Rs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let ze=[];ze.push(()=>{document.removeEventListener("keydown",fc)}),ze.push(()=>{Sr!==null&&clearTimeout(Sr)});let An=null,Sn=null;ze.push(()=>{An?.(),An=null,Sn?.(),Sn=null}),Mr&&ze.push(()=>{Mr?.disconnect(),Mr=null}),ze.push(()=>{Pr?.(),Pr=null,yi(),yt&&(yt.remove(),yt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),le&&ze.push(()=>{Te!==null&&(cancelAnimationFrame(Te),Te=null),Qe?.destroy(),Qe=null,Me?.destroy(),Me=null,ve=null});let bo=null,hc=()=>{bo&&(bo(),bo=null),o.colorScheme==="auto"&&(bo=Ia(()=>{cs(e,o)}))};hc(),ze.push(()=>{bo&&(bo(),bo=null)}),ze.push(l);let _s=o.features?.streamAnimation;if(_s?.type&&_s.type!=="none"){let i=mr(_s.type,_s.plugins);i&&(qa(i,e),ze.push(()=>eu(e)))}let $s=vu(it),vo=null,O,bi=i=>{if(!O)return;let g=i??O.getMessages(),m=o.features?.suggestReplies?.enabled!==!1?zd(g):null;m?$s.render(m,O,ue,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(b=>b.role==="user")?$s.render([],O,ue,g):$s.render(o.suggestionChips,O,ue,g,o.suggestionChipsConfig)},yn=!1,wo=Up(),Uo=new Map,xo=new Map,Gn=new Map,vi=0,hf=Fn()!==null,en=_a(),an=0,Qn=null,ln=!1,zs=!1,Xn=0,bn=null,Co=null,wi=!1,js=!1,Ir=null,Rr=!0,Us=!1,Vs=null,qs=!1,Ao=()=>{qs=!0},xi=null,yf=4,Ks=24,bf=80,Ci=new Map,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},yc=o.voiceRecognition?.autoResume??!1,In=i=>{p.emit("voice:state",{active:Ge.active,source:i,timestamp:Date.now()})},vn=()=>{R(i=>({...i,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},vf=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Vl(u.voiceState),g=!!i.active,m=Number(i.timestamp??0);Ge.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-m<rb&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("restore"),O.isVoiceActive()&&Qo()}):Ys("restore"))},1e3)},wf=()=>O?Ku(O.getMessages()).filter(i=>!i.__skipPersist):[],Gs=null,bc=(i,g)=>{typeof console<"u"&&console.error(i,g)},Ai=(i,g)=>{let m=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(N=>{bc(g,N)})}catch(Q){return bc(g,Q),null}},b=Gs,A=b?b.then(()=>m()??void 0):m();if(!A)return;let k=A.finally(()=>{Gs===k&&(Gs=null)});Gs=k};function Si(i){if(!c?.save)return;let m={messages:i?Ku(i):O?wf():[],metadata:u,artifacts:mn.artifacts,selectedArtifactId:mn.selectedId};Ai(()=>c.save(m),"[AgentWidget] Failed to persist state:")}let Vo=null,vc=()=>He.querySelector("#persona-scroll-container")||se,Wr=()=>{Vo!==null&&(cancelAnimationFrame(Vo),Vo=null),ln=!1},wc=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),zs=!1,Wr()},xf=()=>yn&&Mi()&&(sn()!=="anchor-top"||ec()),Ti=()=>{let i=go()||"Jump to latest",g=xf();Tt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Xn>0?(mo.textContent=String(Xn),mo.style.display="",Tt.setAttribute("aria-label",`${i} (${Xn} new)`)):(mo.textContent="",mo.style.display="none",Tt.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},xc=()=>{Xn!==0&&(Xn=0,Ti())},Mi=()=>Un()?!en.isFollowing():!uo(se,Ks),tn=()=>{if(!Ps()||Ve){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==fe&&fe.appendChild(Tt),_o();let g=En(se)>0&&Mi();g?Ti():xc(),Tt.style.display=g?"":"none"},Hr=()=>{en.pause()&&(wc(),tn())},Jn=()=>{en.resume(),xc(),tn()},Yn=(i=!1)=>{Un()&&en.isFollowing()&&(!i&&!yn||(Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),zs=!0,Qn=requestAnimationFrame(()=>{Qn=null,zs=!1,en.isFollowing()&&Cf(vc(),i?220:140)})))},Cc=(i,g,m,b=()=>!0)=>{let A=i.scrollTop,k=g(),Q=k-A;if(Wr(),Math.abs(Q)<1){ln=!0,i.scrollTop=k,an=i.scrollTop,ln=!1;return}let N=performance.now();ln=!0;let K=ge=>1-Math.pow(1-ge,3),ae=ge=>{if(!b()){Wr();return}let re=g();re!==k&&(k=re,Q=k-A);let we=ge-N,Ue=Math.min(we/m,1),pt=K(Ue),nt=A+Q*pt;i.scrollTop=nt,an=i.scrollTop,Ue<1?Vo=requestAnimationFrame(ae):(i.scrollTop=k,an=i.scrollTop,Vo=null,ln=!1)};Vo=requestAnimationFrame(ae)},Cf=(i,g=500)=>{let m=En(i)-i.scrollTop;if(Math.abs(m)<1){an=i.scrollTop;return}if(Math.abs(m)>=bf){Wr(),ln=!0,i.scrollTop=En(i),an=i.scrollTop,ln=!1;return}Cc(i,()=>En(i),g,()=>en.isFollowing())},Ac=()=>{let i=vc();ln=!0,i.scrollTop=En(i),an=i.scrollTop,ln=!1,tn()},Sc=i=>{let g=0,m=i;for(;m&&m!==se;)g+=m.offsetTop,m=m.offsetParent;return g},Af=()=>{let i=se.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??se.ownerDocument.getSelection()},Qs=()=>Qp(Af(),se),Tc=()=>{if(cf()!=="last-user-turn")return!1;let i=O?.getMessages()??[];if(i.length<2)return!1;let g=[...i].reverse().find(k=>k.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=se.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let A=Math.min(Math.max(0,Sc(b)-Yl()),En(se));return ln=!0,se.scrollTop=A,an=se.scrollTop,ln=!1,sn()==="follow"&&!uo(se,Ks)&&en.pause(),tn(),!0},Mc=i=>{Vn.style.height=`${Math.max(0,Math.round(i))}px`,bn&&(bn.spacerHeight=Math.max(0,i))},Br=()=>{Co!==null&&(cancelAnimationFrame(Co),Co=null),Wr(),bn=null,Vn.style.height="0px"},Ec=i=>{Co!==null&&cancelAnimationFrame(Co),Co=requestAnimationFrame(()=>{Co=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=se.querySelector(`[data-message-id="${g}"]`);if(!m)return;let b=Sc(m),A=bn?.spacerHeight??0,k=se.scrollHeight-A,{targetScrollTop:Q,spacerHeight:N}=Xp({anchorOffsetTop:b,topOffset:Yl(),viewportHeight:se.clientHeight,contentHeight:k});bn={initialSpacerHeight:N,contentHeightAtAnchor:k,spacerHeight:N},Mc(N),Cc(se,()=>Q,220)})},Sf=()=>{if(Un()){if(!en.isFollowing()||uo(se,1))return;Yn(!yn);return}if(bn&&bn.initialSpacerHeight>0){let i=se.scrollHeight-bn.spacerHeight,g=Jp({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:i});g!==bn.spacerHeight&&Mc(g)}tn()},Tf=i=>{let g=sn();g==="follow"?(Jn(),Yn(!0)):g==="anchor-top"&&(Rr=!1,Us=!0,qs=!1,Vs=i,Ec(i))},Mf=()=>{if(sn()==="anchor-top"){if(Us){Rr=!1;return}Rr=!0,Br(),Jn(),Yn(!0)}},Ef=i=>{if(sn()!=="anchor-top"||!Us||qs||Qs())return;let g=Ir===null;for(let m of i){if(!g){m.id===Ir&&(g=!0);continue}if(Gp(m)){if(m.id===Vs)return;Vs=m.id,Ec(m.id);return}}},kf=i=>{let g=new Map;i.forEach(m=>{let b=Ci.get(m.id);g.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(p.emit("assistant:message",m),!js&&(sn()!=="anchor-top"||ec())&&Mi()&&(Xn+=1,Ti(),tn(),nc(Xn===1?"1 new message below.":`${Xn} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&p.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&p.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):p.emit("approval:requested",{approval:m.approval,message:m}))}),Ci.clear(),g.forEach((m,b)=>{Ci.set(b,m)})},Xs=(i,g)=>{let m=g==="user"?"user":"assistant",b=o.layout?.messages?.[m],A=b?.width??"content",k=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",k)},So=(i,g)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),Xs(m,g),m},Lf=(i,g,m)=>{let b=document.createElement("div"),k=(()=>{let W=s.find(Ee=>Ee.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(W,Ee)=>Ee==null?!1:typeof Ee=="string"?(W.textContent=Ee,!0):(W.appendChild(Ee),!0),N=new Set,K=new Map,ae=new Set,ge=s.some(W=>W.renderAskUserQuestion),re=[],we=[],Ue=o.enableComponentStreaming!==!1,pt=o.approval!==!1,nt=[];if(g.forEach(W=>{N.add(W.id),K.set(W.id,W.role);let Ee=ge&&Lo(W),Ne=pt&&W.variant==="approval"&&!!W.approval,Se=!Ee&&W.role==="assistant"&&!W.variant&&Ue&&Ul(W);!Ne&&Gn.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(W.id)),!Se&&xo.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),xo.delete(W.id));let wt=Lo(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=jp(W,vi)+wt,Bt=Ee||Ne||Se?null:Vp(wo,W.id,ut);if(Bt){b.appendChild(Bt.cloneNode(!0)),Lo(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}let ft=null,Jt=s.find(Oe=>!!(W.variant==="reasoning"&&Oe.renderReasoning||W.variant==="tool"&&Oe.renderToolCall||!W.variant&&Oe.renderMessage)),kt=o.layout?.messages;if(Lo(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Uo.delete(W.id),i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(Yi(W)&&o.features?.suggestReplies?.enabled!==!1)return;if(Lo(W)&&o.features?.askUserQuestion?.enabled!==!1){let Oe=s.find(_t=>typeof _t.renderAskUserQuestion=="function");if(Oe&&lt.current){let _t=Uo.get(W.id),$t=_t!==ut,vt=null;if($t){let{payload:Ze,complete:We}=nr(W),ht=W.id,zt=()=>lt.current?.getMessages().find(pn=>pn.id===ht);vt=Oe.renderAskUserQuestion({message:W,payload:Ze,complete:We,resolve:pn=>{let Vr=zt();Vr&&lt.current?.resolveAskUserQuestion(Vr,pn)},dismiss:()=>{let pn=zt();pn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(pn),lt.current?.resolveAskUserQuestion(pn,"(dismissed)"))},config:o})}let ct=_t!=null;if($t&&vt===null&&!ct){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}let gt=So(W.id,W.role);gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),re.push({messageId:W.id,fingerprint:ut,bubble:vt});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}}else if(Ne){let Oe=s.find(ct=>typeof ct.renderApproval=="function")??a,$t=Gn.get(W.id)!==ut,vt=null;if($t&&Oe?.renderApproval){let ct=W.id,gt=(Ze,We)=>{let ht=lt.current?.getMessages().find(zt=>zt.id===ct);ht?.approval&&(ht.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(ht.id,Ze):lt.current?.resolveApproval(ht.approval,Ze,We))};vt=Oe.renderApproval({message:W,defaultRenderer:()=>ri(W,o),config:o,approve:Ze=>gt("approved",Ze),deny:Ze=>gt("denied",Ze)})}if($t&&vt===null)i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(W.id),ft=ri(W,o);else{let ct=So(W.id,W.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),b.appendChild(ct),nt.push({messageId:W.id,fingerprint:ut,bubble:vt});return}}else if(Jt)if(W.variant==="reasoning"&&W.reasoning&&Jt.renderReasoning){if(!ce)return;ft=Jt.renderReasoning({message:W,defaultRenderer:()=>El(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&Jt.renderToolCall){if(!ee)return;ft=Jt.renderToolCall({message:W,defaultRenderer:()=>Ll(W,o),config:o})}else Jt.renderMessage&&(ft=Jt.renderMessage({message:W,defaultRenderer:()=>{let Oe=Ml(W,m,kt,o.messageActions,Xe,{loadingIndicatorRenderer:k,widgetConfig:o});return W.role!=="user"&&Nl(Oe,W,o,O),Oe},config:o}));if(!ft&&Se){let Oe=Uu(W);if(Oe){let _t=xo.get(W.id),$t=_t!==ut,vt=o.wrapComponentDirectiveInBubble!==!1&&zn.getOptions(Oe.component)?.bubbleChrome!==!1,ct=null;if($t){let gt=zu(Oe,{config:o,message:W,transform:m});if(gt&&Oe.component==="PersonaArtifactInline"){let Ze=gt.hasAttribute("data-artifact-inline")?gt:gt.querySelector("[data-artifact-inline]"),We=Ze?.getAttribute("data-artifact-inline")??"",ht=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,zt=We?i.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${ht}"]`)??null:null;Ze&&zt&&zt!==Ze&&Np(zt)&&(Ze===gt?gt=zt:Ze.replaceWith(zt))}if(gt)if(vt){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${W.id}`,Ze.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ze.appendChild(We)}Ze.appendChild(gt),ct=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${W.id}`,Ze.setAttribute("data-message-id",W.id),Ze.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ze.appendChild(We)}Ze.appendChild(gt),ct=Ze}}if(ct||_t!=null){let gt=So(W.id,W.role);gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),we.push({messageId:W.id,fingerprint:ut,bubble:ct});return}}}if(!ft)if(W.variant==="reasoning"&&W.reasoning){if(!ce)return;ft=El(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!ee)return;ft=Ll(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;ft=ri(W,o)}else{let Oe=o.layout?.messages;Oe?.renderUserMessage&&W.role==="user"?ft=Oe.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):Oe?.renderAssistantMessage&&W.role==="assistant"?ft=Oe.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):ft=Ml(W,m,Oe,o.messageActions,Xe,{loadingIndicatorRenderer:k,widgetConfig:o}),W.role!=="user"&&ft&&Nl(ft,W,o,O)}let ke=So(W.id,W.role);ke.appendChild(ft),qp(wo,W.id,ut,ke),b.appendChild(ke)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let Ne=Ee.getAttribute("data-persona-ask-sheet-for");Ne&&!ae.has(Ne)&&rr(Ie.composerOverlay,Ne)}),o.features?.toolCallDisplay?.grouped){let W=[],Ee=[],Ne=o.features.toolCallDisplay.groupedMode==="summary";g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&ee){Ee.push(Se);return}Se.variant==="reasoning"&&!ce||((Ee.length>1||Ne&&Ee.length>0)&&W.push(Ee),Ee=[])}),(Ee.length>1||Ne&&Ee.length>0)&&W.push(Ee),W.forEach(Se=>{let wt=Se.map(Oe=>Array.from(b.children).find(_t=>_t instanceof HTMLElement&&_t.getAttribute("data-wrapper-id")===Oe.id)).filter(Oe=>!!Oe);if(wt.length<(Ne?1:2))return;let ut=So(`tool-group-${Se[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let Bt=document.createElement("div");Bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Bt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Se[0].id}`;let Jt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,kt=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Oe=>Oe.toolCall).filter(Oe=>!!Oe),defaultSummary:Jt,config:o});Q(ft,kt)||(ft.textContent=Jt);let ke=document.createElement("div");ke.className="persona-tool-group-stack persona-flex persona-flex-col",ke.id=`tool-group-stack-${Se[0].id}`,ke.setAttribute("data-persona-tool-group-stack","true"),Bt.appendChild(ft),Ne||Bt.appendChild(ke),ut.appendChild(Bt),wt[0].before(ut),wt.forEach((Oe,_t)=>{if(Ne){Oe.remove();return}Oe.style.setProperty("--persona-message-row-max-width","100%");let $t=document.createElement("div");$t.className="persona-tool-group-item persona-relative",$t.setAttribute("data-persona-tool-group-item","true"),_t<wt.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Oe),ke.appendChild($t)})})}Kp(wo,N);let nn=g.some(W=>W.role==="assistant"&&W.streaming),At=g[g.length-1],Et=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(yn&&g.some(W=>W.role==="user")&&!nn&&!Et){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:xs},Ee=s.find(Se=>Se.renderLoadingIndicator),Ne=null;if(Ee?.renderLoadingIndicator&&(Ne=Ee.renderLoadingIndicator(W)),Ne===null&&o.loadingIndicator?.render&&(Ne=o.loadingIndicator.render(W)),Ne===null&&(Ne=xs()),Ne){let Se=document.createElement("div"),wt=o.loadingIndicator?.showBubble!==!1,ut=o.layout?.messages?.layout??"bubble";Se.className=wt?Tl("assistant",ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Se.setAttribute("data-typing-indicator","true"),wt&&(Se.style.color="var(--persona-message-assistant-text, var(--persona-text))",ut!=="flat"&&(Se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Se.appendChild(Ne);let Bt=So("typing-indicator","assistant");Bt.appendChild(Se),b.appendChild(Bt)}}if(!yn&&g.length>0){let W=g[g.length-1],Ee={config:o,lastMessage:W,messageCount:g.length},Ne=s.find(wt=>wt.renderIdleIndicator),Se=null;if(Ne?.renderIdleIndicator&&(Se=Ne.renderIdleIndicator(Ee)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(Ee)),Se){let wt=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;wt.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(" "),wt.setAttribute("data-idle-indicator","true"),wt.appendChild(Se);let Bt=So("idle-indicator","assistant");Bt.appendChild(wt),b.appendChild(Bt)}}if(Cd(b),Oa(i,b),zi(i),re.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of re){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),Uo.set(W,Ee)))}if(Uo.size>0)for(let W of Uo.keys())N.has(W)||Uo.delete(W);if(we.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of we){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),xo.set(W,Ee)))}if(xo.size>0)for(let W of xo.keys())N.has(W)||xo.delete(W);if(nt.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of nt){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),Gn.set(W,Ee)))}if(Gn.size>0)for(let W of Gn.keys())N.has(W)||Gn.delete(W)},Dr=(i,g,m)=>{Lf(i,g,m),dc()},Fr=null,Pf=()=>{if(Fr)return;let i=m=>{let b=m.composedPath();b.includes(He)||et&&b.includes(et)||dt(!1,"user")};Fr=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},kc=()=>{if(!Fr)return;(e.ownerDocument??document).removeEventListener("pointerdown",Fr,!0),Fr=null};ze.push(()=>kc());let Nr=null,If=()=>{if(Nr)return;let i=m=>{m.key==="Escape"&&(m.isComposing||dt(!1,"user"))};Nr=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Lc=()=>{if(!Nr)return;(e.ownerDocument??document).removeEventListener("keydown",Nr,!0),Nr=null};ze.push(()=>Lc());let Or=!1,Pc=new Set,Rf=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},qo=()=>{if(!F())return;let i=Ie.peekBanner,g=Ie.peekTextNode;if(!i||!g)return;if(X){i.classList.remove("persona-pill-peek--visible");return}let m=O?.getMessages()??[],b;for(let At=m.length-1;At>=0;At--){let Et=m[At];if(Et.role==="assistant"&&Et.content){b=Et;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let A=b.content,k=!!b.streaming,Q=Rf(),N=ja(Q),K=N.type!=="none"?mr(N.type,Q?.plugins):null,ae=K?.isAnimating?.(b)===!0,ge=K!==null&&(k||ae);ge&&K&&!Pc.has(K.name)&&(qa(K,e),Pc.add(K.name));let re=ge&&K?.containerClass?K.containerClass:null,we=g.dataset.personaPeekStreamClass??null;we&&we!==re&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),re&&we!==re&&(g.classList.add(re),g.dataset.personaPeekStreamClass=re),ge?(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=ge?Ua(A,N.buffer,K,b,k):A;if(ge&&N.placeholder==="skeleton"&&k&&(!Ue||!Ue.trim())){let At=document.createElement("div"),Et=hs();Et.classList.add("persona-pill-peek__skeleton"),At.appendChild(Et),Oa(g,At)}else{let At=Math.max(0,Ue.length-100),Et=Ue.length>100?Ue.slice(-100):Ue,W=oo(Et);if(!ge||!K){let Ee=Ue.length>100?`\u2026${Et}`:Et;g.textContent!==Ee&&(g.textContent=Ee)}else{let Ee=W;(K.wrap==="char"||K.wrap==="word")&&(Ee=ms(W,K.wrap,`peek-${b.id}`,{skipTags:K.skipTags,startIndex:At}));let Ne=document.createElement("div");if(Ne.innerHTML=Ee,K.useCaret&&Et.length>0){let Se=Va(),wt=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=wt[wt.length-1];ut?.parentNode?ut.parentNode.insertBefore(Se,ut.nextSibling):Ne.appendChild(Se)}Oa(g,Ne),K.onAfterRender?.({container:g,bubble:i,messageId:b.id,message:b,speed:N.speed,duration:N.duration})}}let nn=yn||Or;i.classList.toggle("persona-pill-peek--visible",nn)};if(F()){let i=Ie.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=()=>{Or||(Or=!0,qo())},m=()=>{Or&&(Or=!1,qo())};de.addEventListener("pointerenter",g),de.addEventListener("pointerleave",m),ze.push(()=>{de.removeEventListener("pointerenter",g),de.removeEventListener("pointerleave",m)}),et&&(et.addEventListener("pointerenter",g),et.addEventListener("pointerleave",m),ze.push(()=>{et.removeEventListener("pointerenter",g),et.removeEventListener("pointerleave",m)}))}let Wf=i=>{let g=o.launcher?.composerBar??{},m=g.expandedSize??"anchored",b=g.bottomOffset??"16px",A=g.collapsedMaxWidth,k=g.expandedMaxWidth??"880px",Q=g.expandedTopOffset??"5vh",N=g.modalMaxWidth??"880px",K=g.modalMaxHeight??"min(90vh, 800px)",ae="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",re=He.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",et){let we=et.style;we.bottom=b,we.width=A??""}if(i&&m!=="fullscreen"){if(m==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=N,re.maxWidth=ae,re.maxHeight=K,re.height=K;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${b} + ${ge})`,re.top=Q,re.width=k,re.maxWidth=ae}},_r=()=>{if(!$())return;if(F()){let ae=(o.launcher?.composerBar??{}).expandedSize??"anchored",ge=X?"expanded":"collapsed";He.dataset.state=ge,He.dataset.expandedSize=ae,et&&(et.dataset.state=ge,et.dataset.expandedSize=ae),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Wf(X),fe.style.display=X?"flex":"none",Os(),X?(Pf(),If()):(kc(),Lc()),qo();return}let i=Dt(o),g=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,A=g.innerWidth<=m,k=b&&A&&M,Q=gn(o).reveal;X?(He.style.removeProperty("display"),He.style.display=i?"flex":"",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Kt&&(Kt.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!k?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.setProperty("display","none","important"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.display="",He.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=i?"none":"":Kt&&(Kt.style.display=i?"none":""))},dt=(i,g="user")=>{if(!$()||X===i)return;let m=X;X=i,_r();let b=(()=>{let k=o.launcher?.sidebarMode??!1,Q=e.ownerDocument.defaultView??window,N=o.launcher?.mobileFullscreen??!0,K=o.launcher?.mobileBreakpoint??640,ae=Q.innerWidth<=K,ge=Dt(o)&&N&&ae,re=F()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||N&&ae&&M||ge||re})();if(X&&b){if(!An){let k=e.getRootNode(),Q=k instanceof ShadowRoot?k.host:e.closest(".persona-host");Q&&(An=vl(Q,o.launcher?.zIndex??Vt))}Sn||(Sn=wl(e.ownerDocument))}else X||(An?.(),An=null,Sn?.(),Sn=null);X&&(jr(),Tc()||(sn()==="follow"?Yn(!0):Ac()));let A={open:X,source:g,timestamp:Date.now()};X&&!m?p.emit("widget:opened",A):!X&&m&&p.emit("widget:closed",A),p.emit("widget:state",{open:X,launcherEnabled:M,voiceActive:Ge.active,streaming:O.isStreaming()})},Ei=i=>{rt(i?"stop":"send"),V&&(V.disabled=i),$s.buttons.forEach(g=>{g.disabled=i}),J.dataset.personaComposerStreaming=i?"true":"false",J.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=i)})},ki=()=>{Ge.active||ue&&ue.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ki(),200)});let Ic=()=>{y.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",P.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",ue.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=se.querySelector("[data-persona-intro-card]");if(i){let m=o.copy?.showWelcomeCard!==!1;i.style.display=m?"":"none",m?(se.classList.remove("persona-gap-3"),se.classList.add("persona-gap-6")):(se.classList.remove("persona-gap-6"),se.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!O?.isStreaming()&&(Ce.textContent=o.copy?.sendButtonLabel??"Send"),ue.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ue.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=u.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{R(g=>({...g,sessionId:i}))}});let To=null,Hf=()=>{To==null&&(To=setInterval(()=>{let i=Pe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(To),To=null;return}let g=Date.now();i.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=ya(g-b))})},100))},Li=(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)=>Li(Q,g[N]));let m=i,b=g,A=Object.keys(m),k=Object.keys(b);return A.length===k.length&&A.every(Q=>Object.prototype.hasOwnProperty.call(b,Q)&&Li(m[Q],b[Q]))},Rc=i=>{let{content:g,rawContent:m,llmContent:b,...A}=i;return A},Pi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Ul(i),Bf=(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))&&Pi(b)&&Pi(A)&&Li(Rc(b),Rc(A))},Wc=null,Ko=null,Mo=null,Rn=null,Js=i=>{Wc=i;let g,m;Ko=null;for(let A=i.length-1;A>=0;A-=1){let k=i[A];if(!g&&k.role==="user"&&(g=k),!m&&k.role==="assistant"&&(m=k),!Ko&&Pi(k)&&(Ko={index:A,id:k.id}),g&&m&&Ko)break}Dr(Pe,i,Z),fl(Pe,mn.artifacts,{suppressTransition:yn}),Hf(),bi(i),Yn(!yn),kf(i),i.length===0&&(Br(),Rr=!0,Us=!1,Vs=null,qs=!1),!wi||js?(wi=!0,Ir=g?.id??null,xi=m?.id??null):g&&g.id!==Ir?(Ir=g.id,Tf(g.id)):m&&m.id!==xi&&Mf(),m&&(xi=m.id),Ef(i);let b=Ge.lastUserMessageId;g&&g.id!==b&&(Ge.lastUserMessageId=g.id,p.emit("user:message",g)),Ge.lastUserMessageWasVoice=!!g?.viaVoice,Si(i),qo()},Ii=()=>{Rn!==null&&(cancelAnimationFrame(Rn),Rn=null);let i=Mo;Mo=null,i&&Js(i)},Hc=()=>{Rn!==null&&cancelAnimationFrame(Rn),Rn=null,Mo=null},Df=i=>{let g=Mo??Wc;if(yn&&g&&Ko&&Bf(g,i,Ko)){Mo=i,Rn===null&&(Rn=requestAnimationFrame(()=>{Rn=null;let m=Mo;Mo=null,m&&Js(m)}));return}if(i.length===0){Hc(),Js(i);return}Ii(),Js(i)};O=new Ta(o,{onMessagesChanged(i){Df(i)},onStatusChanged(i){let g=o.statusIndicator??{};qt(D,(b=>b==="idle"?g.idleText??Lt.idle:b==="connecting"?g.connectingText??Lt.connecting:b==="connected"?g.connectedText??Lt.connected:b==="error"?g.errorText??Lt.error:b==="paused"?g.pausedText??Lt.paused:b==="resuming"?g.resumingText??Lt.resuming:Lt[b])(i),g,i)},onStreamingChanged(i){i||(O?.getMessages().length===0?Hc():Ii()),yn=i,Ei(i),O&&Dr(Pe,O.getMessages(),Z),i||Yn(!0),tn(),nc(i?"Responding\u2026":"Response complete."),qo()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Wn(),Qo();break;case"processing":Wn(),Kf();break;case"speaking":Wn(),Gf();break;default:i==="idle"&&O.isBargeInActive()?(Wn(),Qo(),V?.setAttribute("aria-label","End voice session")):(Ge.active=!1,Wn(),In("system"),vn());break}},onArtifactsState(i){mn=i,i.artifacts.length===0&&($o=!1),fl(Pe,i.artifacts,{suppressTransition:yn}),Pn(),Si()},onReconnect(i){let{executionId:g,lastEventId:m}=i.handle;i.phase==="paused"?p.emit("stream:paused",{executionId:g,after:m}):i.phase==="resuming"?p.emit("stream:resuming",{executionId:g,after:m,attempt:i.attempt??1}):p.emit("stream:resumed",{executionId:g,after:m})}}),lt.current=O,ze.push(()=>O.cancel());let Ri=null;if(O.onReadAloudChange((i,g)=>{lc=i,cc=g,dc();let m=i??Ri;i&&(Ri=i);let b=m?O.getMessages().find(A=>A.id===m)??null:null;p.emit("message:read-aloud",{messageId:m,message:b,state:g,timestamp:Date.now()}),g==="idle"&&(Ri=null)}),wi=!0,o.voiceRecognition?.provider?.type==="runtype")try{O.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&O.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Me||o.onSSEEvent)&&O.setSSEEventCallback((i,g)=>{o.onSSEEvent?.(i,g),De?.processEvent(i,g),Me?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(g)})});let Bc=()=>{o.resume&&typeof o.reconnectStream=="function"&&O.resumeFromHandle(o.resume)};w?w.then(i=>{if(i){if(i.metadata&&(u=Vl(i.metadata),E.syncFromMetadata()),i.messages?.length){js=!0;try{O.hydrateMessages(i.messages)}finally{js=!1}}i.artifacts?.length&&O.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Bc()):Bc();let Dc=()=>{!F()||X||!(o.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},Ff=(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),pb(A)}}:i:g,Nf=()=>{let g=ue.getInlineMessageFields?.();return g&&g.contentSegments.some(b=>b.kind==="mention")?g.contentSegments:void 0},$r=!1,Of=async i=>{let g=ue.value.trim(),m=Ct?.hasAttachments()??!1,b=g?await(Zt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(b?.kind==="action"){ue.value="",ue.style.height="auto",zr(),Zt?.clear();return}let A=Zt?.collectForSubmit()??null,k=b?.kind==="server"?b.mentions:null,Q=Ff(A,k),N=b?.kind==="prompt"?b.sendText:g,K=!!A&&A.refs.length>0;if(!N&&!m&&!K&&!k)return;Dc();let ae;m&&(ae=[],ae.push(...Ct.getContentParts()),N&&ae.push(ar(N)));let ge=b?.kind==="prompt"?void 0:Nf();ue.value="",ue.style.height="auto",zr(),O.sendMessage(N,{contentParts:ae,mentions:Q??void 0,contentSegments:ge,viaVoice:i?.viaVoice}),m&&Ct.clearAttachments(),A&&Zt?.clear()},Wi=async i=>{if(!$r){$r=!0;try{await Of(i)}finally{$r=!1}}},Fc=i=>{if(i.preventDefault(),O.isStreaming()){O.cancel(),De?.reset(),Qe?.update();return}$r||Wi()},_f=()=>o.features?.composerHistory!==!1,Hi={...hl},Bi=!1,zr=()=>{Hi={...hl}},$f=()=>O.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),zf=i=>{if(!ue)return;Bi=!0,ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),Bi=!1;let g=ue.value.length;ue.setSelectionRange(g,g)},jf=i=>{Bi||(i.isComposing||Zt?.handleInput(i.inputType??void 0),zr())},Uf=i=>{if(ue&&!(!i.isComposing&&Zt?.handleKeydown(i))){if(_f()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let g=ue.selectionStart===0&&ue.selectionEnd===0,m=zp({direction:i.key==="ArrowUp"?"up":"down",history:$f(),currentValue:ue.value,atStart:g,state:Hi});if(Hi=m.state,m.handled){i.preventDefault(),m.value!==void 0&&zf(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(O.isStreaming()){i.preventDefault();return}if($r){i.preventDefault();return}zr(),i.preventDefault(),Ce.click()}}},Nc=i=>{i.key!=="Escape"||i.isComposing||O.isStreaming()&&i.composedPath().includes(fe)&&(O.cancel(),De?.reset(),Qe?.update(),zr(),i.preventDefault(),i.stopImmediatePropagation())},Vf=async i=>{if(o.attachments?.enabled!==!0||!Ct)return;let g=ib(i.clipboardData);g.length!==0&&(i.preventDefault(),await Ct.handleFiles(g))},cn=null,Tn=!1,Go=null,bt=null,Oc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ys=(i="user")=>{if(Tn||O.isStreaming())return;let g=Oc();if(!g)return;cn=new g;let b=(o.voiceRecognition??{}).pauseDuration??2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let A=ue.value;cn.onresult=k=>{let Q="",N="";for(let ae=0;ae<k.results.length;ae++){let ge=k.results[ae],re=ge[0].transcript;ge.isFinal?Q+=re+" ":N=re}let K=A+Q+N;ue.value=K,Go&&clearTimeout(Go),(Q||N)&&(Go=window.setTimeout(()=>{ue.value.trim()&&cn&&Tn&&(Zn(),Wi({viaVoice:!0}))},b))},cn.onerror=k=>{k.error!=="no-speech"&&Zn()},cn.onend=()=>{if(Tn){let k=ue.value.trim();k&&k!==A.trim()&&Wi({viaVoice:!0}),Zn()}};try{if(cn.start(),Tn=!0,Ge.active=!0,i!=="system"&&(Ge.manuallyDeactivated=!1),In(i),vn(),V){let k=o.voiceRecognition??{};bt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??o.sendButton?.size??"40")||24};let Q=k.recordingBackgroundColor,N=k.recordingIconColor,K=k.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 ae=V.querySelector("svg");ae&&ae.setAttribute("stroke",N)}K&&(V.style.borderColor=K),V.setAttribute("aria-label","Stop voice recognition")}}catch{Zn("system")}},Zn=(i="user")=>{if(Tn){if(Tn=!1,Go&&(clearTimeout(Go),Go=null),cn){try{cn.stop()}catch{}cn=null}if(Ge.active=!1,In(i),vn(),V){if(V.classList.remove("persona-voice-recording"),bt){V.style.backgroundColor=bt.backgroundColor,V.style.color=bt.color,V.style.borderColor=bt.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",bt.color||"currentColor"),bt=null}V.setAttribute("aria-label","Start voice recognition")}}},qf=(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 K=i?.tooltipText??"Start voice recognition";N.setAttribute("aria-label",K);let ae=i?.iconName??"mic",ge=g?.size??"40px",re=i?.iconSize??ge,we=parseFloat(re)||24,Ue=i?.backgroundColor??g?.backgroundColor,pt=i?.iconColor??g?.textColor;N.style.width=re,N.style.height=re,N.style.minWidth=re,N.style.minHeight=re,N.style.fontSize="18px",N.style.lineHeight="1",pt?N.style.color=pt:N.style.color="var(--persona-text, #111827)";let nn=ie(ae,we,pt||"currentColor",1.5);nn?N.appendChild(nn):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 Ot({anchor:N,trigger:Q,text:()=>N.getAttribute("aria-label")??K,enabled:At}),{micButton:N,micButtonWrapper:Q}},Di=()=>{if(!V||bt)return;let i=o.voiceRecognition??{};bt={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}},Fi=(i,g)=>{if(!V)return;let m=V.querySelector("svg");m&&m.remove();let b=bt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=ie(i,b,g,1.5);A&&V.appendChild(A)},Zs=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qo=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,m=i.recordingIconColor,b=i.recordingBorderColor;if(Zs(),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")},Kf=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=O.getVoiceInterruptionMode(),m=i.processingIconName??"loader",b=i.processingIconColor??bt?.color??"",A=i.processingBackgroundColor??bt?.backgroundColor??"",k=i.processingBorderColor??bt?.borderColor??"";Zs(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=A,V.style.borderColor=k;let Q=b||"currentColor";V.style.color=Q,Fi(m,Q),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},Gf=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=O.getVoiceInterruptionMode(),m=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=i.speakingIconName??m,A=i.speakingIconColor??(g==="barge-in"?i.recordingIconColor??bt?.color??"":bt?.color??""),k=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":bt?.backgroundColor??""),Q=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":bt?.borderColor??"");Zs(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=k,V.style.borderColor=Q;let N=A||"currentColor";V.style.color=N,Fi(b,N);let K=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",K),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},Wn=()=>{V&&(Zs(),bt&&(V.style.backgroundColor=bt.backgroundColor??"",V.style.color=bt.color??"",V.style.borderColor=bt.borderColor??"",Fi(bt.iconName,bt.color||"currentColor"),bt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},ea=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=O.getVoiceStatus(),g=O.getVoiceInterruptionMode();if(g==="none"&&(i==="processing"||i==="speaking"))return;if(g==="cancel"&&(i==="processing"||i==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,vn(),In("user"),Wn()});return}O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),Ge.manuallyDeactivated=!O.isVoiceActive(),vn(),In("user"),O.isVoiceActive()?Qo():Wn()});return}if(Tn){let i=ue.value.trim();Ge.manuallyDeactivated=!0,vn(),Zn("user"),i&&(ue.value="",ue.style.height="auto",O.sendMessage(i))}else Ge.manuallyDeactivated=!1,vn(),Ys("user")};rc=ea,V&&(V.addEventListener("click",ea),ze.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Wn()):Zn("system"),V&&V.removeEventListener("click",ea)}));let Qf=p.on("assistant:complete",()=>{yc&&(Ge.active||Ge.manuallyDeactivated||yc==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("auto"),O.isVoiceActive()&&Qo()}):Ys("auto"))},600))});ze.push(Qf);let Xf=p.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});ze.push(Xf);let _c=()=>{dt(!X,"user")},Ft=null,Kt=null;if(M&&!F()){let{instance:i,element:g}=Cl({config:o,plugins:s,onToggle:_c});Ft=i,i||(Kt=g)}Ft?e.appendChild(Ft.element):Kt&&e.appendChild(Kt),_r(),bi(),Ic(),Ei(O.isStreaming()),Tc()||(sn()==="follow"?Yn(!0):Ac()),vf(),G&&(!M||F()?setTimeout(()=>ki(),0):X&&setTimeout(()=>ki(),200));let jr=()=>{if(F()){_o(),_r();return}let i=Dt(o),g=o.launcher?.sidebarMode??!1,m=i||g||(o.launcher?.fullHeight??!1),b=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640,Q=b.innerWidth<=k,N=A&&Q&&M;try{if(N){Er(),kr=Ns();return}let K=!1;oe&&(oe=!1,Er(),K=!0);let ae=Ns();if(!K&&ae!==kr&&(Er(),K=!0),kr=ae,K&&hi(),!M&&!i){de.style.height="",de.style.width="";return}if(!g&&!i){let re=o?.launcher?.width??o?.launcherWidth??$n;de.style.width=re,de.style.maxWidth=re}if(Fs(),!m){let ge=b.innerHeight,re=64,we=o.launcher?.heightOffset??0,Ue=Math.max(200,ge-re),pt=Math.min(640,Ue),nt=Math.max(200,pt-we);de.style.height=`${nt}px`}}finally{if(_o(),_r(),X&&M){let ae=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ge=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,we=Dt(o)&&re&&ae,Ue=ge||re&&ae&&M||we;if(Ue&&!Sn){let pt=e.getRootNode(),nt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");nt&&!An&&(An=vl(nt,o.launcher?.zIndex??Vt)),Sn=wl(e.ownerDocument)}else Ue||(An?.(),An=null,Sn?.(),Sn=null)}}};jr();let $c=e.ownerDocument.defaultView??window;if($c.addEventListener("resize",jr),ze.push(()=>$c.removeEventListener("resize",jr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{_o()});i.observe(J),ze.push(()=>i.disconnect())}an=se.scrollTop;let zc=En(se),jc=()=>{let i=se.scrollTop,g=En(se),m=g<zc;if(zc=g,!Un()){an=i,tn();return}let{action:b,nextLastScrollTop:A}=$a({following:en.isFollowing(),currentScrollTop:i,lastScrollTop:an,nearBottom:uo(se,Ks),userScrollThreshold:yf,isAutoScrolling:ln||zs||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(an=A,b==="resume"){Qs()||Jn();return}b==="pause"&&Hr()};if(se.addEventListener("scroll",jc,{passive:!0}),ze.push(()=>se.removeEventListener("scroll",jc)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Sf(),zi(Pe)});i.observe(Pe),i.observe(se),ze.push(()=>i.disconnect())}let Uc=()=>{Un()&&en.isFollowing()&&Qs()&&Hr()},Vc=se.ownerDocument;Vc.addEventListener("selectionchange",Uc),ze.push(()=>{Vc.removeEventListener("selectionchange",Uc)});let Jf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),qc=i=>{Jf.has(i.key)&&(Ao(),Zl()&&Un()&&en.isFollowing()&&Hr())},Kc=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ao(),Zl()&&Un()&&en.isFollowing()&&Hr())};se.addEventListener("keydown",qc),se.addEventListener("focusin",Kc),ze.push(()=>{se.removeEventListener("keydown",qc),se.removeEventListener("focusin",Kc)});let Gc=i=>{if(i.deltaY!==0&&Ao(),!Un())return;let g=za({following:en.isFollowing(),deltaY:i.deltaY,nearBottom:uo(se,Ks),resumeWhenNearBottom:!0});g==="pause"?Hr():g==="resume"&&!Qs()&&Jn()};se.addEventListener("wheel",Gc,{passive:!0}),se.addEventListener("touchmove",Ao,{passive:!0}),se.addEventListener("pointerdown",Ao,{passive:!0}),ze.push(()=>{se.removeEventListener("touchmove",Ao),se.removeEventListener("pointerdown",Ao)}),ze.push(()=>se.removeEventListener("wheel",Gc)),Tt.addEventListener("click",()=>{Br(),se.scrollTop=se.scrollHeight,an=se.scrollTop,Jn(),Yn(!0),tn()}),ze.push(()=>Tt.remove()),ze.push(()=>{wc(),Br()});let Qc=()=>{T&&(vo&&(T.removeEventListener("click",vo),vo=null),$()?(T.style.display="",vo=()=>{dt(!1,"user")},T.addEventListener("click",vo)):T.style.display="none")};Qc(),(()=>{let{clearChatButton:i}=Ie;i&&i.addEventListener("click",()=>{O.clearMessages(),wo.clear(),Jn(),rr(Ie.composerOverlay);try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)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),c?.clear&&Ai(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),Me?.clear(),De?.reset(),Qe?.update()})})(),S&&S.addEventListener("submit",Fc);let Xc=[["keydown",Uf],["input",jf],["paste",Vf],["focus",uf]],Jc=i=>{if(i)for(let[g,m]of Xc)i.addEventListener(g,m)},Yc=i=>{if(i)for(let[g,m]of Xc)i.removeEventListener(g,m)};Jc(ue),Zt?.onComposerSwap((i,g)=>{Yc(g),ue=i,Jc(i)});let Zc=e.ownerDocument??document;Zc.addEventListener("keydown",Nc,!0);let ed="persona-attachment-drop-active",Ur=0,Ni=()=>{Ur=0,fe.classList.remove(ed)},Xo=()=>o.attachments?.enabled===!0&&Ct!==null,td=i=>{!li(i.dataTransfer)||!Xo()||(Ur++,Ur===1&&fe.classList.add(ed))},nd=i=>{!li(i.dataTransfer)||!Xo()||(Ur--,Ur<=0&&Ni())},od=i=>{!li(i.dataTransfer)||!Xo()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},rd=i=>{if(!li(i.dataTransfer)||!Xo())return;i.preventDefault(),i.stopPropagation(),Ni();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&Ct.handleFiles(g)},eo=!0;fe.addEventListener("dragenter",td,eo),fe.addEventListener("dragleave",nd,eo),e.addEventListener("dragover",od,eo),e.addEventListener("drop",rd,eo);let ta=e.ownerDocument,sd=i=>{Xo()&&i.preventDefault()},ad=i=>{Xo()&&i.preventDefault()};ta.addEventListener("dragover",sd),ta.addEventListener("drop",ad),ze.push(()=>{S&&S.removeEventListener("submit",Fc),Yc(ue),Zc.removeEventListener("keydown",Nc,!0),Zt?.destroy()}),ze.push(()=>{fe.removeEventListener("dragenter",td,eo),fe.removeEventListener("dragleave",nd,eo),e.removeEventListener("dragover",od,eo),e.removeEventListener("drop",rd,eo),ta.removeEventListener("dragover",sd),ta.removeEventListener("drop",ad),Ni()}),ze.push(()=>{O.cancel()}),Ft?ze.push(()=>{Ft?.destroy()}):Kt&&ze.push(()=>{Kt?.remove()});let Mt={update(i){let g=o.toolCall,m=o.messageActions,b=o.layout?.messages,A=o.colorScheme,k=o.loadingIndicator,Q=o.iterationDisplay,N=o.features?.showReasoning,K=o.features?.showToolCalls,ae=o.features?.toolCallDisplay,ge=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=Nu({...o,features:r},i),r=o.features,o=Dl(o),Os(),cs(e,o),Ts(e,o),Ms(e,o),Pn(),o.colorScheme!==A&&hc();let we=_l.getForInstance(o.plugins);s.length=0,s.push(...we),M=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,ce=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,Y=o.features?.scrollToBottom??{};let Ue=sn();pe=o.features?.scrollBehavior??{},Ue!==sn()&&(Br(),Jn()),oc(),tn();let pt=le;if(le=o.features?.showEventStreamToggle??!1,le&&!pt){if(Me||(ve=new As(ye),Me=new Cs(je,ve),De=De??new Ss,ve.open().then(()=>Me?.restore()).catch(()=>{}),O.setSSEEventCallback((ne,Ke)=>{o.onSSEEvent?.(ne,Ke),De?.processEvent(ne,Ke),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Ke)})})),!tt&&z){let ne=o.features?.eventStream?.classNames,Ke="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne?.toggleButton?" "+ne.toggleButton:"");tt=h("button",Ke),tt.style.width="28px",tt.style.height="28px",tt.style.color=Qt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let mt=ie("activity","18px","currentColor",1.5);mt&&tt.appendChild(mt);let ot=Ie.clearChatButtonWrapper,st=Ie.closeButtonWrapper,jt=ot||st;jt&&jt.parentNode===z?z.insertBefore(tt,jt):z.appendChild(tt),tt.addEventListener("click",()=>{Ve?Tr():ui()})}}else!le&&pt&&(Tr(),tt&&(tt.remove(),tt=null),Me?.clear(),ve?.destroy(),Me=null,ve=null,De?.reset(),De=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Kt&&(Kt.remove(),Kt=null),o.launcher?.enabled!==!1&&!Ft&&!Kt){let{instance:ne,element:Ke}=Cl({config:o,plugins:s,onToggle:_c});Ft=ne,ne||(Kt=Ke),e.appendChild(Ke)}Ft&&Ft.update(o),q&&o.launcher?.title!==void 0&&(q.textContent=o.launcher.title),H&&o.launcher?.subtitle!==void 0&&(H.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==U&&z){let ne=nt?Qa(o,nt,{showClose:$(),onClose:()=>dt(!1,"user")}):Ho({config:o,showClose:$(),onClose:()=>dt(!1,"user")});xt.replaceHeader(ne),z=xt.header.element,I=xt.header.iconHolder,q=xt.header.headerTitle,H=xt.header.headerSubtitle,T=xt.header.closeButton,U=nt?.layout}else if(nt){if(I&&(I.style.display=nt.showIcon===!1?"none":""),q&&(q.style.display=nt.showTitle===!1?"none":""),H&&(H.style.display=nt.showSubtitle===!1?"none":""),T){let ne=$()&&nt.showCloseButton!==!1;T.style.display=ne?"":"none"}if(Ie.clearChatButtonWrapper){let ne=nt.showClearChat;if(ne!==void 0){Ie.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Ke}=Ie;Ke&&!Ke.classList.contains("persona-absolute")&&(ne?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;z&&(z.style.display=At?"":"none");let Et=o.layout?.showFooter!==!1;J&&(J.style.display=Et?"":"none"),_o(),tn(),M!==j?M?dt(_,"auto"):(X=!0,_r()):_!==x&&dt(_,"auto"),x=_,j=M,jr(),Qc();let Ne=JSON.stringify(o.toolCall)!==JSON.stringify(g),Se=JSON.stringify(o.messageActions)!==JSON.stringify(m),wt=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),ut=o.loadingIndicator?.render!==k?.render||o.loadingIndicator?.renderIdle!==k?.renderIdle||o.loadingIndicator?.showBubble!==k?.showBubble,Bt=o.iterationDisplay!==Q,ft=(o.features?.showReasoning??!0)!==(N??!0)||(o.features?.showToolCalls??!0)!==(K??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ge);(Ne||Se||wt||ut||Bt||ft)&&O&&(vi++,Dr(Pe,O.getMessages(),Z));let kt=o.features?.streamAnimation?.type;if(kt!==re&&kt&&kt!=="none"){let ne=mr(kt,o.features?.streamAnimation?.plugins);ne&&qa(ne,e)}let ke=o.launcher??{},Oe=ke.headerIconHidden??!1,_t=o.layout?.header?.showIcon,$t=Oe||_t===!1,vt=ke.headerIconName,ct=ke.headerIconSize??"48px";if(I){let ne=fe.querySelector(".persona-border-b-persona-divider"),Ke=ne?.querySelector(".persona-flex-col");if($t)I.style.display="none",ne&&Ke&&!ne.contains(Ke)&&ne.insertBefore(Ke,ne.firstChild);else{if(I.style.display="",I.style.height=ct,I.style.width=ct,ne&&Ke&&(ne.contains(I)?I.nextSibling!==Ke&&(I.remove(),ne.insertBefore(I,Ke)):ne.insertBefore(I,Ke)),vt){let ot=parseFloat(ct)||24,st=ie(vt,ot*.6,"currentColor",1);st?I.replaceChildren(st):I.textContent=ke.agentIconText??"\u{1F4AC}"}else if(ke.iconUrl){let ot=I.querySelector("img");if(ot)ot.src=ke.iconUrl,ot.style.height=ct,ot.style.width=ct;else{let st=document.createElement("img");st.src=ke.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=ct,st.style.width=ct,I.replaceChildren(st)}}else{let ot=I.querySelector("svg"),st=I.querySelector("img");(ot||st)&&I.replaceChildren(),I.textContent=ke.agentIconText??"\u{1F4AC}"}let mt=I.querySelector("img");mt&&(mt.style.height=ct,mt.style.width=ct)}}let gt=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(q&&(q.style.display=gt===!1?"none":""),H&&(H.style.display=Ze===!1?"none":""),T){let ne=$()&&o.layout?.header?.showCloseButton!==!1;T.style.display=ne?"":"none";let Ke=ke.closeButtonSize??"32px",mt=ke.closeButtonPlacement??"inline";T.style.height=Ke,T.style.width=Ke;let{closeButtonWrapper:ot}=Ie,st=mt==="top-right",jt=ot?.classList.contains("persona-absolute");if(ot&&st!==jt)if(ot.remove(),st)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(ot);else{let no=ke.clearChat?.placement??"inline",Kr=ke.clearChat?.enabled??!0;ot.className=Kr&&no==="inline"?"":"persona-ml-auto";let id=fe.querySelector(".persona-border-b-persona-divider");id&&id.appendChild(ot)}if(T.style.color=ke.closeButtonColor||Qt.actionIconColor,ke.closeButtonBackgroundColor?(T.style.backgroundColor=ke.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),ke.closeButtonBorderWidth||ke.closeButtonBorderColor){let no=ke.closeButtonBorderWidth||"0px",Kr=ke.closeButtonBorderColor||"transparent";T.style.border=`${no} solid ${Kr}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");ke.closeButtonBorderRadius?(T.style.borderRadius=ke.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),ke.closeButtonPaddingX?(T.style.paddingLeft=ke.closeButtonPaddingX,T.style.paddingRight=ke.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),ke.closeButtonPaddingY?(T.style.paddingTop=ke.closeButtonPaddingY,T.style.paddingBottom=ke.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let on=ke.closeButtonIconName??"x",wn=ke.closeButtonIconText??"\xD7";T.innerHTML="";let Nt=ie(on,"28px","currentColor",1);Nt?(Nt.style.display="block",T.appendChild(Nt)):T.textContent=wn;let Ut=ke.closeButtonTooltipText??"Close chat",Bn=ke.closeButtonShowTooltip??!0;T.setAttribute("aria-label",Ut),ot&&Ot({anchor:T,trigger:ot,text:()=>T?.getAttribute("aria-label")??Ut,enabled:Bn})}let{clearChatButton:We,clearChatButtonWrapper:ht}=Ie;if(We){let ne=ke.clearChat??{},Ke=ne.enabled??!0,mt=o.layout?.header?.showClearChat,ot=mt!==void 0?mt:Ke,st=ne.placement??"inline";if(ht){ht.style.display=ot?"":"none";let{closeButtonWrapper:jt}=Ie;!F()&&jt&&!jt.classList.contains("persona-absolute")&&(ot?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let on=st==="top-right",wn=ht.classList.contains("persona-absolute");if(!F()&&on!==wn&&ot){if(ht.remove(),on)ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px",fe.style.position="relative",fe.appendChild(ht);else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let Ut=fe.querySelector(".persona-border-b-persona-divider"),Bn=Ie.closeButtonWrapper;Ut&&Bn&&Bn.parentElement===Ut?Ut.insertBefore(ht,Bn):Ut&&Ut.appendChild(ht)}let Nt=Ie.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(on?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(ot){if(!F()){let no=ne.size??"32px";We.style.height=no,We.style.width=no}let jt=ne.iconName??"refresh-cw",on=ne.iconColor??"";We.style.color=on||Qt.actionIconColor,We.innerHTML="";let wn=F()?"14px":"20px",Nt=ie(jt,wn,"currentColor",1);if(Nt&&(Nt.style.display="block",We.appendChild(Nt)),ne.backgroundColor?(We.style.backgroundColor=ne.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let no=ne.borderWidth||"0px",Kr=ne.borderColor||"transparent";We.style.border=`${no} solid ${Kr}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");ne.borderRadius?(We.style.borderRadius=ne.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),ne.paddingX?(We.style.paddingLeft=ne.paddingX,We.style.paddingRight=ne.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),ne.paddingY?(We.style.paddingTop=ne.paddingY,We.style.paddingBottom=ne.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let Ut=ne.tooltipText??"Clear chat",Bn=ne.showTooltip??!0;We.setAttribute("aria-label",Ut),ht&&Ot({anchor:We,trigger:ht,text:()=>We?.getAttribute("aria-label")??Ut,enabled:Bn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zl],pn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Es.message,Es.messageAndClick];E=jl({parsers:zt,handlers:pn,getSessionMetadata:C,updateSessionMetadata:R,emit:p.emit,documentRef:typeof document<"u"?document:null}),Z=Gu(o,E,Ae),O.updateConfig(o),Dr(Pe,O.getMessages(),Z),bi(),Ic(),Ei(O.isStreaming());let Vr=o.voiceRecognition?.enabled===!0,na=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),St=o.voiceRecognition?.provider?.type==="runtype";if(Vr&&(na||St))if(!V||!_e){let ne=qf(o.voiceRecognition,o.sendButton);ne&&(V=ne.micButton,_e=ne.micButtonWrapper,Re.insertBefore(_e,te),V.addEventListener("click",ea),V.disabled=O.isStreaming())}else{let ne=o.voiceRecognition??{},Ke=o.sendButton??{},mt=ne.iconName??"mic",ot=Ke.size??"40px",st=ne.iconSize??ot,jt=parseFloat(st)||24;V.style.width=st,V.style.height=st,V.style.minWidth=st,V.style.minHeight=st;let on=ne.iconColor??Ke.textColor;V.innerHTML="";let wn=ie(mt,jt,on||"currentColor",1.5);wn?V.appendChild(wn):V.textContent="\u{1F3A4}";let Nt=ne.backgroundColor??Ke.backgroundColor;Nt?V.style.backgroundColor=Nt:V.style.backgroundColor="",on?V.style.color=on:V.style.color="var(--persona-text, #111827)",ne.borderWidth?(V.style.borderWidth=ne.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),ne.borderColor?V.style.borderColor=ne.borderColor:V.style.borderColor="",ne.paddingX?(V.style.paddingLeft=ne.paddingX,V.style.paddingRight=ne.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ne.paddingY?(V.style.paddingTop=ne.paddingY,V.style.paddingBottom=ne.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let Ut=ne.tooltipText??"Start voice recognition",Bn=ne.showTooltip??!1;V.setAttribute("aria-label",Ut),_e&&Ot({anchor:V,trigger:_e,text:()=>V?.getAttribute("aria-label")??Ut,enabled:Bn}),_e.style.display="",V.disabled=O.isStreaming()}else V&&_e&&(_e.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()&&O.toggleVoice():Tn&&Zn());if(o.attachments?.enabled===!0){if(!$e||!be){let ne=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Rt||(Rt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Rt.style.display="none",S.insertBefore(Rt,ue)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=(ne.allowedTypes??_n).join(","),Fe.multiple=(ne.maxFiles??4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),S.insertBefore(Fe,ue)),$e=h("div","persona-send-button-wrapper"),be=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),be.type="button",be.setAttribute("aria-label",ne.buttonTooltipText??"Attach file");let ot=ne.buttonIconName??"paperclip",st=mt,jt=parseFloat(st)||40,on=Math.round(jt*.6);be.style.width=st,be.style.height=st,be.style.minWidth=st,be.style.minHeight=st,be.style.fontSize="18px",be.style.lineHeight="1";let wn=ie(ot,on,"currentColor",1.5);wn?be.appendChild(wn):be.textContent="\u{1F4CE}",be.addEventListener("click",Ut=>{Ut.preventDefault(),Fe?.click()}),$e.appendChild(be);let Nt=ne.buttonTooltipText??"Attach file";Ot({anchor:be,trigger:$e,text:()=>be?.getAttribute("aria-label")??Nt}),Je?Je.append($e):S.appendChild($e),!Ct&&Fe&&Rt&&(Ct=as.fromConfig(ne),Ct.setPreviewsContainer(Rt),Fe.addEventListener("change",async()=>{Ct&&Fe?.files&&(await Ct.handleFileSelect(Fe.files),Fe.value="")}))}else{$e.style.display="";let ne=o.attachments??{};Fe&&(Fe.accept=(ne.allowedTypes??_n).join(","),Fe.multiple=(ne.maxFiles??4)>1),Ct&&Ct.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}if(fe.querySelector(".persona-attachment-drop-overlay")?.remove(),fe.appendChild(Qu(o.attachments?.dropOverlay)),be){let ne=o.attachments??{},Ke=ne.buttonTooltipText??"Attach file";be.setAttribute("aria-label",Ke),be.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,ot=ie(ne.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);ot?be.appendChild(ot):be.textContent="\u{1F4CE}",$e&&Ot({anchor:be,trigger:$e,text:()=>be?.getAttribute("aria-label")??Ke})}}else $e&&($e.style.display="none"),Ct&&Ct.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Wt=o.sendButton??{},qr=Wt.useIcon??!1,ra=Wt.iconText??"\u2191",Jo=Wt.iconName,sa=Wt.tooltipText??"Send message",Oi=Wt.showTooltip??!1,Eo=Wt.size??"40px",Hn=Wt.backgroundColor,ko=Wt.textColor;if(qr){if(Ce.style.width=Eo,Ce.style.height=Eo,Ce.style.minWidth=Eo,Ce.style.minHeight=Eo,Ce.style.fontSize="18px",Ce.style.lineHeight="1",ko?Ce.style.color=ko:Ce.style.color="var(--persona-button-primary-fg, #ffffff)",!O.isStreaming())if(Ce.innerHTML="",Jo){let ne=parseFloat(Eo)||24,Ke=ko?.trim()||"currentColor",mt=ie(Jo,ne,Ke,2);mt?Ce.appendChild(mt):Ce.textContent=ra}else Ce.textContent=ra;Ce.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Hn?(Ce.style.backgroundColor=Hn,Ce.classList.remove("persona-bg-persona-primary")):(Ce.style.backgroundColor="",Ce.classList.add("persona-bg-persona-primary"))}else Ce.textContent=o.copy?.sendButtonLabel??"Send",Ce.style.width="",Ce.style.height="",Ce.style.minWidth="",Ce.style.minHeight="",Ce.style.fontSize="",Ce.style.lineHeight="",Ce.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",Hn?(Ce.style.backgroundColor=Hn,Ce.classList.remove("persona-bg-persona-accent")):Ce.classList.add("persona-bg-persona-accent"),ko?Ce.style.color=ko:Ce.classList.add("persona-text-white");Wt.borderWidth?(Ce.style.borderWidth=Wt.borderWidth,Ce.style.borderStyle="solid"):(Ce.style.borderWidth="",Ce.style.borderStyle=""),Wt.borderColor?Ce.style.borderColor=Wt.borderColor:Ce.style.borderColor="",Wt.paddingX?(Ce.style.paddingLeft=Wt.paddingX,Ce.style.paddingRight=Wt.paddingX):(Ce.style.paddingLeft="",Ce.style.paddingRight=""),Wt.paddingY?(Ce.style.paddingTop=Wt.paddingY,Ce.style.paddingBottom=Wt.paddingY):(Ce.style.paddingTop="",Ce.style.paddingBottom=""),O.isStreaming()||Ce.setAttribute("aria-label",sa),te&&Ot({anchor:Ce,trigger:te,text:()=>Ce.getAttribute("aria-label")??sa,enabled:Oi});let aa=o.layout?.contentMaxWidth??(F()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);aa?(Pe.style.maxWidth=aa,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",S&&(S.style.maxWidth=aa,S.style.marginLeft="auto",S.style.marginRight="auto"),it&&(it.style.maxWidth=aa,it.style.marginLeft="auto",it.style.marginRight="auto")):(Pe.style.maxWidth="",Pe.style.marginLeft="",Pe.style.marginRight="",Pe.style.width="",S&&(S.style.maxWidth="",S.style.marginLeft="",S.style.marginRight=""),it&&(it.style.maxWidth="",it.style.marginLeft="",it.style.marginRight=""));let to=o.statusIndicator??{},Yf=to.visible??!0;if(D.style.display=Yf?"":"none",O){let ne=O.getStatus();qt(D,(mt=>mt==="idle"?to.idleText??Lt.idle:mt==="connecting"?to.connectingText??Lt.connecting:mt==="connected"?to.connectedText??Lt.connected:mt==="error"?to.errorText??Lt.error:Lt[mt])(ne),to,ne)}D.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Zf=to.align==="left"?"persona-text-left":to.align==="center"?"persona-text-center":"persona-text-right";D.classList.add(Zf)},open(){$()&&dt(!0,"api")},close(){$()&&dt(!1,"api")},toggle(){$()&&dt(!X,"api")},reconnect(){O.reconnectNow()},clearChat(){Ln=!1,O.clearMessages(),wo.clear(),Jn();try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)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),c?.clear&&Ai(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),Me?.clear(),De?.reset(),Qe?.update()},setMessage(i){return!ue||O.isStreaming()?!1:(!X&&$()&&dt(!0,"system"),ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(O.isStreaming())return!1;let g=i?.trim()||ue.value.trim();return g?(!X&&$()&&dt(!0,"system"),ue.value="",ue.style.height="auto",O.sendMessage(g),!0):!1},startVoiceRecognition(){return O.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()||(!X&&$()&&dt(!0,"system"),Ge.manuallyDeactivated=!1,vn(),O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("user"),O.isVoiceActive()&&Qo()})),!0):Tn?!0:Oc()?(!X&&$()&&dt(!0,"system"),Ge.manuallyDeactivated=!1,vn(),Ys("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,vn(),In("user"),Wn()}),!0):!1:Tn?(Ge.manuallyDeactivated=!0,vn(),Zn("user"),!0):!1},injectMessage(i){return!X&&$()&&dt(!0,"system"),O.injectMessage(i)},injectAssistantMessage(i){!X&&$()&&dt(!0,"system");let g=O.injectAssistantMessage(i);return me&&(me=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),g},injectUserMessage(i){return!X&&$()&&dt(!0,"system"),O.injectUserMessage(i)},injectSystemMessage(i){return!X&&$()&&dt(!0,"system"),O.injectSystemMessage(i)},injectMessageBatch(i){return!X&&$()&&dt(!0,"system"),O.injectMessageBatch(i)},injectComponentDirective(i){return!X&&$()&&dt(!0,"system"),O.injectComponentDirective(i)},injectTestMessage(i){!X&&$()&&dt(!0,"system"),O.injectTestEvent(i)},async connectStream(i,g){return O.connectStream(i,g)},__pushEventStreamEvent(i){Me&&(De?.processEvent(i.type,i.payload),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!le||!Me||ui()},hideEventStream(){Ve&&Tr()},isEventStreamVisible(){return Ve},showArtifacts(){Xt(o)&&(Ln=!1,$o=!0,Pn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(Ln=!0,Pn())},upsertArtifact(i){return Xt(o)?(ro(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Ln=!1,$o=!0),O.upsertArtifact(i)):null},selectArtifact(i){Xt(o)&&O.selectArtifact(i)},clearArtifacts(){Xt(o)&&O.clearArtifacts()},getArtifacts(){return O?.getArtifacts()??[]},getSelectedArtifactId(){return O?.getSelectedArtifactId()??null},focusInput(){return M&&!X&&!F()||!ue?!1:(ue.focus(),!0)},async resolveApproval(i,g,m){let A=O.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!A?.approval)throw new Error(`Approval not found: ${i}`);if(A.approval.toolType==="webmcp"){O.resolveWebMcpApproval(A.id,g);return}return O.resolveApproval(A.approval,g,m)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){R(i)},on(i,g){return p.on(i,g)},off(i,g){p.off(i,g)},isOpen(){return $()&&X},isVoiceActive(){return Ge.active},toggleReadAloud(i){O.toggleReadAloud(i)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(i){return O.getReadAloudState(i)},onReadAloudChange(i){return O.onReadAloudChange(i)},getState(){return{open:$()&&X,launcherEnabled:M,voiceActive:Ge.active,streaming:O.isStreaming()}},showCSATFeedback(i){!X&&$()&&dt(!0,"system");let g=Pe.querySelector(".persona-feedback-container");g&&g.remove();let m=Vu({onSubmit:async(b,A)=>{O.isClientTokenMode()&&await O.submitCSATFeedback(b,A),i?.onSubmit?.(b,A)},onDismiss:i?.onDismiss,...i});Pe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!X&&$()&&dt(!0,"system");let g=Pe.querySelector(".persona-feedback-container");g&&g.remove();let m=qu({onSubmit:async(b,A)=>{O.isClientTokenMode()&&await O.submitNPSFeedback(b,A),i?.onSubmit?.(b,A)},onDismiss:i?.onDismiss,...i});Pe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,g){return O.submitCSATFeedback(i,g)},async submitNPSFeedback(i,g){return O.submitNPSFeedback(i,g)},destroy(){Ii(),To!=null&&(clearInterval(To),To=null),ze.forEach(i=>i()),He.remove(),et?.remove(),Ft?.destroy(),Kt?.remove(),vo&&T.removeEventListener("click",vo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:Mt,getMessages:Mt.getMessages,getStatus:Mt.getStatus,getMetadata:Mt.getPersistentMetadata,updateMetadata:Mt.updatePersistentMetadata,clearHistory:()=>Mt.clearChat(),setVoiceActive:m=>m?Mt.startVoiceRecognition():Mt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ze.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.focusInput()};if(window.addEventListener("persona:focusInput",g),ze.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let N=ae=>{let ge=ae.detail;(!ge?.instanceId||ge.instanceId===i)&&Mt.showEventStream()},K=ae=>{let ge=ae.detail;(!ge?.instanceId||ge.instanceId===i)&&Mt.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",K),ze.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",K)})}let m=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.showArtifacts()},b=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.hideArtifacts()},A=N=>{let K=N.detail;K?.instanceId&&K.instanceId!==i||K?.artifact&&Mt.upsertArtifact(K.artifact)},k=N=>{let K=N.detail;K?.instanceId&&K.instanceId!==i||typeof K?.id=="string"&&Mt.selectArtifact(K.id)},Q=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",k),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",k),window.removeEventListener("persona:clearArtifacts",Q)})}let dn=lb(o.persistState);if(dn&&$()){let i=cb(dn.storage),g=`${dn.keyPrefix}widget-open`,m=`${dn.keyPrefix}widget-voice`,b=`${dn.keyPrefix}widget-voice-mode`;if(i){let A=dn.persist?.openState&&i.getItem(g)==="true",k=dn.persist?.voiceState&&i.getItem(m)==="true",Q=dn.persist?.voiceState&&i.getItem(b)==="true";if(A&&setTimeout(()=>{Mt.open(),setTimeout(()=>{if(k||Q)Mt.startVoiceRecognition();else if(dn.persist?.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),dn.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(g,"true")}),p.on("widget:closed",()=>{i.setItem(g,"false")})),dn.persist?.voiceState&&(p.on("voice:state",N=>{i.setItem(m,N.active?"true":"false")}),p.on("user:message",N=>{i.setItem(b,N.viaVoice?"true":"false")})),dn.clearOnChatClear){let N=()=>{i.removeItem(g),i.removeItem(m),i.removeItem(b)},K=()=>N();window.addEventListener("persona:clear-chat",K),ze.push(()=>{window.removeEventListener("persona:clear-chat",K)})}}}if(f&&$()&&setTimeout(()=>{Mt.open()},0),qo(),!hf){let i=la(()=>{O&&(vi++,wo.clear(),Dr(Pe,O.getMessages(),Z))});ze.push(i)}return Mt};var Ju=(e,t)=>{let n=e.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,t*parseFloat(r[1])/100):420},ub=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},fb=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},gb=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.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."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Yu=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},Ql=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Zu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Ql(e)},ql=e=>{e.style.transition=""},Kl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Gl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ci=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},mb=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},hb=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},yb=e=>{let t=dr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Gt(t,r)??r;return{inset:o(n?.inset,La),canvasBackground:o(n?.canvasBackground,Pa)}},ef=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},bb=(e,t,n,o,r,s,a,l)=>{let p=gn(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";mb(e,t,n,o,d),hb(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",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=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,R=f!=null?f.innerWidth<=C:!1;if(v&&R&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Kl(t),ql(o),Zu(o),Gl(n),ci(r,o),ef(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.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??Vt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Zu(o),ub(o,p.maxHeight),ef(o,c&&a,u,w),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Kl(t),ql(o),Gl(n),ci(r,o);let L=p.animate?"transform 180ms ease":"none",E=p.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":E;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=L,o.style.transform=M,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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ql(o),Ql(o),ci(r,o);let L=Ju(p.width,e.clientWidth),E=Math.max(0,e.clientWidth),M=p.animate?"margin-left 180ms ease":"none",_=p.side==="right"?a?-L:0:a?0:-L;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${E+L}px`,t.style.transition=M,t.style.marginLeft=`${_}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${E}px`,n.style.maxWidth=`${E}px`,n.style.minWidth=`${E}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{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Kl(t),Ql(o),Gl(n),ci(r,o);let L=p.reveal==="emerge";L?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=a?p.width:"0px",M=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",_=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${E}`,o.style.width=E,o.style.maxWidth=E,o.style.minWidth=E,o.style.minHeight="0",fb(o,p.maxHeight),o.style.overflow=L||_?"hidden":"visible",o.style.transition=M,L){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let G=c?`calc(${Ju(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=G,r.style.minWidth=G,r.style.maxWidth=G,r.style.boxSizing="border-box"}}},vb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Yu(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Yu(n,o)},destroy(){n.remove()}}},wb=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.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,e),p.appendChild(e);let w=null,f=()=>{w?.disconnect(),w=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?yb(t):null};C();let R=()=>{bb(a,l,p,d,c,t,u,v)},B=null,L=()=>{B?.(),B=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(B=Ia(()=>{C(),R()}))},E=()=>{f(),gn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{R()}),w.observe(a)))},M=!1,_=()=>{R(),E(),u&&!M&&a.dataset.personaDockMobileFullscreen!=="true"&&(M=!0,gb(a,gn(t)))},G=a.ownerDocument.defaultView,x=()=>{_()};return G?.addEventListener("resize",x),gn(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),_(),L(),{mode:"docked",host:c,shell:a,syncWidgetState(j){let U=j.launcherEnabled?j.open:!0;u!==U&&(u=U,_())},updateConfig(j){t=j,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),_(),L()},destroy(){G?.removeEventListener("resize",x),B?.(),B=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},tf=(e,t)=>Dt(t)?wb(e,t):vb(e,t);var ks={desktop:{w:1280,h:800},mobile:{w:390,h:844}},nf=.15,of=1.5,Xl="persona-preview-shell-theme",xb={load:()=>null,save:()=>{},clear:()=>{}},Cb=["How do I get started?","Pricing & plans","Talk to support"];function Jl(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ab(e){return e==="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 rf(e){let t=Ab(e);return`* { box-sizing: border-box; }
141
141
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
142
- html { color-scheme: ${t}; }
143
- body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
142
+ html { color-scheme: ${e}; }
143
+ body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
144
144
  .preview-iframe-mock { min-height: 100%; }
145
- .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
146
- .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${e.dot}; }
145
+ .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${t.chromeBorder}; background: ${t.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
146
+ .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${t.dot}; }
147
147
  .preview-iframe-copy { padding: 32px; }
148
- .preview-iframe-line { border-radius: 999px; background: ${e.skeleton}; margin-bottom: 12px; }
148
+ .preview-iframe-line { border-radius: 999px; background: ${t.skeleton}; margin-bottom: 12px; }
149
149
  .preview-iframe-line.hero { width: 48%; height: 16px; }
150
150
  .preview-iframe-line.body { width: 72%; height: 10px; }
151
151
  .preview-iframe-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 24px 0; }
152
- .preview-iframe-card { height: 84px; border-radius: 14px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
152
+ .preview-iframe-card { height: 84px; border-radius: 14px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
153
153
  .preview-workspace-shell { height: 100%; min-height: 100%; display: flex; flex-direction: column; }
154
- .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
154
+ .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${t.chromeBorder}; background: ${t.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
155
155
  .preview-workspace-topbar-left { display: flex; align-items: center; gap: 12px; }
156
- .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
157
- .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${e.skeleton}; }
158
- .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
156
+ .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
157
+ .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${t.skeleton}; }
158
+ .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
159
159
  .preview-workspace-body { flex: 1; min-height: 0; display: flex; padding: 20px; }
160
- .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
160
+ .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
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
- .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 _u(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Dl);o||(o=n.createElement("style"),o.id=Dl,n.head.appendChild(o)),o.textContent=Ou(e)}var Vy=`
163
+ .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
164
+ .preview-workspace-card.short { height: 96px; }`}function sf(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Xl);o||(o=n.createElement("style"),o.id=Xl,n.head.appendChild(o)),o.textContent=rf(t)}var Sb=`
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 Xr=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>`,Ky=`
183
+ </div>`,Tb=`
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,9 +193,9 @@ _Details: ${n.message}_`:o}var Xr=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 $u(t,e,n,o){let r=`
197
- ${Vy}
198
- <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
196
+ </div>`;function af(e,t,n,o){let r=`
197
+ ${Sb}
198
+ <div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
199
199
  <div class="preview-workspace-shell">
200
200
  <div class="preview-workspace-topbar">
201
201
  <div class="preview-workspace-topbar-left">
@@ -205,8 +205,8 @@ _Details: ${n.message}_`:o}var Xr=t=>({isError:!0,content:[{type:"text",text:t}]
205
205
  <span class="preview-workspace-topbar-pill"></span>
206
206
  </div>
207
207
  <div class="preview-workspace-body">
208
- <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
209
- ${Ky}
208
+ <div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
209
+ ${Tb}
210
210
  </div>
211
211
  </div>
212
212
  </div>`;return`<!DOCTYPE html>
@@ -214,16 +214,16 @@ _Details: ${n.message}_`:o}var Xr=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="${Fl(o)}">
218
- <style id="${Dl}">${Ou(e)}</style>
217
+ <link rel="stylesheet" href="${Jl(o)}">
218
+ <style id="${Xl}">${rf(t)}</style>
219
219
  </head>
220
220
  <body>
221
221
  ${n?s:r}
222
222
  </body>
223
- </html>`}var Gy=()=>[{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()}],Qy=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function Xy(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"&&Qy(e)?[...Gy(),...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 Jy(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:jy:t.suggestionChips,initialMessages:Xy(e,t,n),storageAdapter:Uy};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Yy(t,e){let n=t.theme?or(t.theme,{validate:!1}):or();return{...at,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function gr(t,e){let n=t.scene??"conversation";return Jy(Yy(t,e),n,t.appendedMessages??[])}function zu(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:gr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:gr(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:gr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:gr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:gr(t,n),shellMode:n}]}function Zy(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=vs[c()]??vs.desktop;return Math.min(x/j.w,U/j.h,1)}function f(){l=w();let k=Math.max(Fu,Math.min(Nu,u()));p=k;let M=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let P of M){let z=P.dataset.device??"desktop",K=vs[z]??vs.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=zu(n),P=c(),z=(n.compareMode??"off")!=="off",K=(n.scene??"conversation")==="minimized",x=n.widgetCssPath??"/widget-dist/widget.css",U=n.buildSrcdoc??$u,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">${Fl(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(),le=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 ie=()=>{},Z=Wt(Y.config),he=Z?(()=>{let pe=ee.contentDocument?.getElementById(`preview-content-${ce}`);if(!pe)return null;let Te=Du(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 $e=()=>Te.syncWidgetState(ye.getState()),Fe=ie;return ie=()=>{Te.destroy(),Fe()},Ae.__syncDock=$e,Ae.__hostLayout=Te,Ae})():ee.contentDocument.getElementById(ce);if(!he)continue;let ye=Iu(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),$e=ie;ie=()=>{Te(),Ae(),$e()},pe()}r.push(ie),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
223
+ </html>`}var Mb=()=>[{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()}],Eb=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||e?.features?.reasoningDisplay?.activePreview);function kb(e,t,n=[]){return e==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="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()}]:e==="conversation"&&Eb(t)?[...Mb(),...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 Lb(e,t,n=[]){let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?e.suggestionChips?.length?e.suggestionChips:Cb:e.suggestionChips,initialMessages:kb(t,e,n),storageAdapter:xb};return t==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Pb(e,t){let n=e.theme?cr(e.theme,{validate:!1}):cr();return{...at,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:t??e.config?.colorScheme??"light"}}function Cr(e,t){let n=e.scene??"conversation";return Lb(Pb(e,t),n,e.appendedMessages??[])}function lf(e){let t=e.compareMode??"off",n=e.shellMode??"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Cr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Cr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let o={...e,config:e.baselineConfig??e.config,theme:e.baselineTheme??e.theme,darkTheme:e.baselineDarkTheme??e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Cr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Cr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Cr(e,n),shellMode:n}]}function Ib(e,t){let n={...t},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 L=getComputedStyle(e),E=parseFloat(L.paddingLeft)+parseFloat(L.paddingRight),M=parseFloat(L.paddingTop)+parseFloat(L.paddingBottom),_=40,G=(n.compareMode??"off")!=="off",x=(e.clientWidth-E-_)/(G?2:1),j=e.clientHeight-M-_;if(x<=0||j<=0)return 1;let U=ks[c()]??ks.desktop;return Math.min(x/U.w,j/U.h,1)}function f(){l=w();let L=Math.max(nf,Math.min(of,u()));p=L;let E=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let M of E){let _=M.dataset.device??"desktop",G=ks[_]??ks.desktop;M.style.width=`${G.w*L}px`,M.style.height=`${G.h*L}px`,_==="mobile"&&(M.style.borderRadius=`${32*L}px`);let x=M.querySelector("iframe");x&&(x.style.width=`${G.w}px`,x.style.height=`${G.h}px`,x.style.transformOrigin="top left",x.style.transition="none",x.style.transform=`scale(${L})`)}n.onScaleChange?.(L)}function v(){n.onBeforeDestroy?.();for(let L of o)L.destroy();for(let L of r)L();o=[],r=[]}function C(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function R(){if(a)return;v();let L=++d,E=lf(n),M=c(),_=(n.compareMode??"off")!=="off",G=(n.scene??"conversation")==="minimized",x=n.widgetCssPath??"/widget-dist/widget.css",j=n.buildSrcdoc??af,U=M==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",oe=Ae=>`<div class="${U}" data-mount-id="${Ae.mountId}" data-device="${M}" data-shell-mode="${Ae.shellMode}">
224
+ ${_?`<div class="preview-frame-meta"><span class="preview-frame-label">${Jl(Ae.label)}</span></div>`:""}
225
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Ae.mountId}"></iframe>
226
+ </div>`,F=_?`<div class="preview-compare-grid">${E.map(Ae=>`<div class="preview-compare-cell">${oe(Ae)}</div>`).join("")}</div>`:`<div class="preview-single">${oe(E[0])}</div>`;n.morphContainer?n.morphContainer(e,F):e.innerHTML=F,f();let $=C(),X=0,me=$.length,he=()=>{if(a||L!==d)return;for(let Z of $){let ce=Z.dataset.mountId;if(!ce||!Z.contentDocument)continue;let ee=E.find(ye=>ye.mountId===ce);if(!ee)continue;let le=()=>{},Y=Dt(ee.config),pe=Y?(()=>{let ye=Z.contentDocument?.getElementById(`preview-content-${ce}`);if(!ye)return null;let ve=tf(ye,ee.config),je=Z.contentDocument.createElement("div");je.id=ce,je.style.height="100%",je.style.display="flex",je.style.flexDirection="column",je.style.flex="1",je.style.minHeight="0",ve.host.appendChild(je);let Me=()=>ve.syncWidgetState(xe.getState()),De=le;return le=()=>{ve.destroy(),De()},je.__syncDock=Me,je.__hostLayout=ve,je})():Z.contentDocument.getElementById(ce);if(!pe)continue;let xe=Xu(pe,ee.config);if(o.push(xe),Y&&pe.__syncDock){let ye=pe.__syncDock,ve=xe.on("widget:opened",ye),je=xe.on("widget:closed",ye),Me=le;le=()=>{ve(),je(),Me()},ye()}r.push(le),G&&xe.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let Z of o)Z.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: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",()=>{le++,le>=ge&&Ce()},{once:!0}),we.srcdoc=U(ee,ce.shellMode,Wt(ce.config),x))}ge===0&&Ce()}function B(){if(a)return;let k=zu(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&&_u(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{Zy as createThemePreview};
234
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:$,controllers:[...o]})};for(let Ae of $){let Z=Ae.dataset.mountId;if(!Z)continue;let ce=E.find(ee=>ee.mountId===Z);ce&&(Ae.addEventListener("load",()=>{X++,X>=me&&he()},{once:!0}),Ae.srcdoc=j(Z,ce.shellMode,Dt(ce.config),x))}me===0&&he()}function B(){if(a)return;let L=lf(n);if(o.length!==L.length){R();return}if(L.some(M=>{let _=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${M.mountId}"]`);return!_||_.dataset.shellMode!==M.shellMode})){R();return}o.forEach((M,_)=>{M.update(L[_].config),(n.scene??"conversation")==="minimized"&&M.close()});for(let M of L){let _=e.querySelector(`iframe[data-mount-id="${M.mountId}"]`);_&&sf(_,M.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||f()}),s.observe(e)),R(),{update(L){if(a)return;let E=L.device!==void 0&&L.device!==n.device||L.scene!==void 0&&L.scene!==n.scene||L.compareMode!==void 0&&L.compareMode!==n.compareMode||L.widgetCssPath!==void 0&&L.widgetCssPath!==n.widgetCssPath;n={...n,...L},E?R():B()},destroy(){a||(a=!0,v(),s?.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},f())},getIframes(){return C()},getScale(){return p},setZoom(L){a||(n={...n,zoom:L},f())}}}export{Ib as createThemePreview};