@runtypelabs/persona 3.29.0 → 3.30.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 (63) hide show
  1. package/README.md +55 -0
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-CxvHw0X6.d.cts → types-B_Qazlm4.d.cts} +6 -0
  5. package/dist/animations/{types-CxvHw0X6.d.ts → types-B_Qazlm4.d.ts} +6 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +6 -6
  9. package/dist/codegen.js +4 -4
  10. package/dist/index.cjs +47 -47
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +127 -7
  13. package/dist/index.d.ts +127 -7
  14. package/dist/index.global.js +60 -60
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +47 -47
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js +2 -2
  19. package/dist/launcher.global.js.map +1 -1
  20. package/dist/plugin-kit.cjs +1 -0
  21. package/dist/plugin-kit.d.cts +98 -0
  22. package/dist/plugin-kit.d.ts +98 -0
  23. package/dist/plugin-kit.js +1 -0
  24. package/dist/smart-dom-reader.d.cts +113 -4
  25. package/dist/smart-dom-reader.d.ts +113 -4
  26. package/dist/theme-editor.cjs +38 -38
  27. package/dist/theme-editor.d.cts +117 -6
  28. package/dist/theme-editor.d.ts +117 -6
  29. package/dist/theme-editor.js +38 -38
  30. package/dist/theme-reference.cjs +1 -1
  31. package/dist/theme-reference.d.cts +2 -0
  32. package/dist/theme-reference.d.ts +2 -0
  33. package/dist/theme-reference.js +1 -1
  34. package/package.json +8 -2
  35. package/src/client.test.ts +40 -0
  36. package/src/client.ts +18 -4
  37. package/src/components/approval-bubble.test.ts +268 -0
  38. package/src/components/approval-bubble.ts +170 -20
  39. package/src/components/launcher.ts +6 -3
  40. package/src/components/tool-bubble.test.ts +39 -0
  41. package/src/components/tool-bubble.ts +4 -0
  42. package/src/generated/runtype-openapi-contract.ts +12 -0
  43. package/src/index-core.ts +1 -0
  44. package/src/plugin-kit.test.ts +230 -0
  45. package/src/plugin-kit.ts +294 -0
  46. package/src/plugins/types.ts +49 -2
  47. package/src/session.test.ts +99 -0
  48. package/src/session.ts +204 -32
  49. package/src/session.webmcp.test.ts +326 -6
  50. package/src/theme-editor/preview-utils.test.ts +10 -0
  51. package/src/theme-editor/preview-utils.ts +29 -1
  52. package/src/theme-editor/sections.test.ts +17 -0
  53. package/src/theme-editor/sections.ts +31 -0
  54. package/src/theme-reference.ts +1 -1
  55. package/src/types/theme.ts +2 -0
  56. package/src/types.ts +59 -2
  57. package/src/ui.approval-plugin.test.ts +204 -0
  58. package/src/ui.ts +149 -16
  59. package/src/utils/theme.test.ts +6 -2
  60. package/src/utils/theme.ts +0 -8
  61. package/src/utils/tokens.ts +6 -1
  62. package/src/webmcp-bridge.test.ts +66 -0
  63. package/src/webmcp-bridge.ts +49 -0
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
- import{Marked as Pm}from"marked";var Im=e=>{if(e)return e},va=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new Pm({gfm:(s=t==null?void 0:t.gfm)!=null?s:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=Im(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},_o=e=>e?va({markedOptions:e.options,renderer:e.renderer}):va(),Wm=va(),wp=e=>Wm(e),jo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Cp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ap=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=vp(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=vp(t.length);return t.push({token:o,type:s}),o}),n},Rm=e=>{let t=_o(e);return n=>{let r=[],s=Ap(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Cp(i)}"></div>`;o=o.replace(d,p)}),o}},Hm=e=>{let t=[],n=Ap(e,t),r=wp(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Cp(o)}"></div>`;r=r.replace(a,d)}),r};import Bm from"dompurify";var Dm={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"]},Nm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Sp=()=>{let e=Bm(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let r=n.attrValue;r.toLowerCase().startsWith("data:")&&!Nm.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Dm)},Ts=e=>e===!1?null:typeof e=="function"?e:Sp();var Ca="webmcp:",wa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Ep(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Fm(t.join(""))}`}function Tp(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Fm(e){let t=Tp(e,0).toString(36),n=Tp(e,2654435761).toString(36);return`${t}.${n}`}var Es=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n: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(s){return wa.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=$m(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return hr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let u=typeof document!="undefined"&&!!document.modelContext;return hr(u?"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 o=Mp(t),a;try{a=await s.getTools()}catch(u){let v=u instanceof Error?u.message:String(u);return hr(`Failed to read WebMCP registry: ${v}`)}let i=a.find(u=>u.name===o);if(!i)return hr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return hr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let d={toolName:o,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),g=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",g,{once:!0}));try{let u=await s.executeTool(i,qm(n),{signal:l.signal});return _m(u)}catch(u){if(p)return hr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let v=u instanceof Error?u.message:String(u);return hr(v)}finally{clearTimeout(m),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){wa.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")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,wa.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 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){var r;let n=(r=this.confirmHandler)!=null?r:jm;try{return await n(t)}catch(s){return wa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Om(t,r))}},Mp=e=>e.startsWith(Ca)?e.slice(Ca.length):e,Aa=e=>e.startsWith(Ca),Om=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},$m=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},_m=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:zm(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),jm=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Um(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ import{Marked as _m}from"marked";var jm=e=>{if(e)return e},Aa=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new _m({gfm:(s=t==null?void 0:t.gfm)!=null?s:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=jm(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},Ko=e=>e?Aa({markedOptions:e.options,renderer:e.renderer}):Aa(),Um=Aa(),Mp=e=>Um(e),Jo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),kp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ep=e=>`%%FORM_PLACEHOLDER_${e}%%`,Lp=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Ep(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Ep(t.length);return t.push({token:o,type:s}),o}),n},qm=e=>{let t=Ko(e);return n=>{let r=[],s=Lp(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${kp(i)}"></div>`;o=o.replace(d,p)}),o}},zm=e=>{let t=[],n=Lp(e,t),r=Mp(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${kp(o)}"></div>`;r=r.replace(a,d)}),r};import Vm from"dompurify";var Km={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"]},Jm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pp=()=>{let e=Vm(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let r=n.attrValue;r.toLowerCase().startsWith("data:")&&!Jm.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Km)},Is=e=>e===!1?null:typeof e=="function"?e:Pp();var ro="webmcp:",Ei=new Map,Ip=e=>{var t;Ei.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Ei.set(n.name,r)}},Mi=e=>Ei.get(ki(e)),Sa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Rp(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Gm(t.join(""))}`}function Wp(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Gm(e){let t=Wp(e,0).toString(36),n=Wp(e,2654435761).toString(36);return`${t}.${n}`}var Ws=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n: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(s){return Sa.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}Ip(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Qm(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return Cr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let v=typeof document!="undefined"&&!!document.modelContext;return Cr(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 o=ki(t),a;try{a=await s.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return Cr(`Failed to read WebMCP registry: ${x}`)}Ip(a);let i=a.find(v=>v.name===o);if(!i)return Cr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return Cr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return Cr("Aborted by cancel()");let d=Mi(o),l={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Cr("User declined the tool call.");if(r!=null&&r.aborted)return Cr("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),m=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await s.executeTool(i,tg(n),{signal:p.signal});return Ym(v)}catch(v){if(u)return Cr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return Cr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return Cr(x)}finally{clearTimeout(f),r&&r.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Sa.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")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,Sa.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 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){var r;let n=(r=this.confirmHandler)!=null?r:Zm;try{return await n(t)}catch(s){return Sa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Xm(t,r))}},ki=e=>e.startsWith(ro)?e.slice(ro.length):e,ko=e=>e.startsWith(ro),Xm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Qm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Ym=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:ng(t)}]}},Cr=e=>({isError:!0,content:[{type:"text",text:e}]}),Zm=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=eg(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
4
  ${t}`:"")+(e.description?`
5
5
 
6
- ${e.description}`:"");return window.confirm(n)},Um=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)}},qm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},zm=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as kp,STR as Lp,OBJ as Pp}from"partial-json";var Sa=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Uo=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)}},Vm=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Ip=e=>e.status==="complete"?Vm(e):e.status==="pending"?"Waiting":"",Km=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a: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 Wp=e=>e.status==="complete"?Km(e):"Using tool...",Ta=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ks=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ta(t)},Ea=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ta(t)},Ai=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=ks(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ma=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Ms(r,n.slice(o,a.index),[]),a[1]!==void 0?Ms(r,a[1],["bold"]):a[2]!==void 0?Ms(r,a[2],["italic"]):a[3]!==void 0&&Ms(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&Ms(r,n.slice(o),[]),r},Ms=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Jm=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
6
+ ${e.description}`:"");return window.confirm(n)},eg=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)}},tg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ng=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Hp,STR as Bp,OBJ as Dp}from"partial-json";var Ta=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Go=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)}},rg=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Np=e=>e.status==="complete"?rg(e):e.status==="pending"?"Waiting":"",og=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a: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 Op=e=>e.status==="complete"?og(e):"Using tool...",Ea=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Hs=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ea(t)},Ma=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ea(t)},Li=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Hs(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},ka=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Rs(r,n.slice(o,a.index),[]),a[1]!==void 0?Rs(r,a[1],["bold"]):a[2]!==void 0?Rs(r,a[2],["italic"]):a[3]!==void 0&&Rs(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&Rs(r,n.slice(o),[]),r},Rs=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},sg=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},So=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Si=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ti=()=>{var t;let e=Jm();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Ei=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=kp(n,Lp|Pp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Sa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Sa(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Gm=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Sa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Sa(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=kp(o,Lp|Pp),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Mi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ka=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Xm="https://api.runtype.com/v1/dispatch",La="https://api.runtype.com";function Qm(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ki=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 Ym(e){switch(e){case"json":return Ei;case"regex-json":return Ti;case"xml":return Mi;default:return Si}}var Rp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Zm(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Rp(n);if(!Rp(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=So(e);return So(t)!==null&&a===null?t:e}var qo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Xm,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Ym(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new Es(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||La}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;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 r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||La}/v1/client/feedback`}async sendFeedback(t){var o,a;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 s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let P=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:P}),P}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(ki).map(P=>{var W,w,I;return{id:P.id,role:P.role,content:(I=(w=(W=P.contentParts)!=null?W:P.llmContent)!=null?w:P.rawContent)!=null?I:P.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,u=!!(g&&g.length>0),v=u?Ep(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,C=u&&x&&this.lastSentClientToolsFingerprint===v,T=!1,H=null,L;for(let P=0;;P++){let w={...m,...u&&(T||!C)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:r.signal}),L.status===409&&P===0&&u){let I=await L.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}H=I!=null?I:{error:"Chat request failed"}}break}if(!L.ok){let P=H!=null?H:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:w}),w}if(L.status===429){let w=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let W=new Error(P.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!L.body){let P=new Error("No response body received");throw n({type:"error",error:P}),P}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(L.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||La}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||La}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(ki).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(t){var o;let r={messages:t.slice().filter(ki).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var ln,Hn,Xn,Ue;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=N=>{let Ae=N.reasoning?{...N.reasoning,chunks:[...N.reasoning.chunks]}:void 0,Be=N.toolCall?{...N.toolCall,chunks:N.toolCall.chunks?[...N.toolCall.chunks]:void 0}:void 0,De=N.tools?N.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...N,reasoning:Ae,toolCall:Be,tools:De}},m=N=>{if(N.role!=="assistant"||N.variant)return!0;let Ae=Array.isArray(N.contentParts)&&N.contentParts.length>0,Be=typeof N.rawContent=="string"&&N.rawContent.trim()!=="";return typeof N.content=="string"&&N.content.trim()!==""||Ae||Be||!!N.stopReason},g=N=>{m(N)&&n({type:"message",message:p(N)})},u=null,v=null,x={current:null},C={current:null},T=!1,H=new Map,L=new Map,P=new Map,W=new Map,w={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},O=(N,Ae,Be="")=>`${N}::${Ae}::${Be}`,$=(N,Ae)=>`${N}::${Ae}::`,B=(N,Ae,Be,De)=>{let _e=O(N,Ae,Be),dt=P.get(_e);if(dt)return dt;let rt=Be?`-${Be}`:"",At={id:`nested-${N}-${Ae}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:De,parentToolId:N,parentStepId:Ae}};return P.set(_e,At),g(At),At},j=N=>{if(N==null)return null;try{return String(N)}catch{return null}},z=N=>{var Ae,Be,De,_e,dt;return j((dt=(_e=(De=(Be=(Ae=N.stepId)!=null?Ae:N.step_id)!=null?Be:N.step)!=null?De:N.parentId)!=null?_e:N.flowStepId)!=null?dt:N.flow_step_id)},oe=N=>{var Ae,Be,De,_e,dt,rt,At;return j((At=(rt=(dt=(_e=(De=(Be=(Ae=N.callId)!=null?Ae:N.call_id)!=null?Be:N.requestId)!=null?De:N.request_id)!=null?_e:N.toolCallId)!=null?dt:N.tool_call_id)!=null?rt:N.stepId)!=null?At:N.step_id)},We=r,je=!1,Ne=()=>{if(u)return u;let N;return!je&&We?(N=We,je=!0):We&&C.current?N=`${We}_${C.current}`:N=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:N,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(u),u},ge=(N,Ae)=>{w.lastId=Ae,N&&w.byStep.set(N,Ae)},ye=(N,Ae)=>{var dt;let Be=(dt=N.reasoningId)!=null?dt:N.id,De=z(N);if(Be){let rt=String(Be);return ge(De,rt),rt}if(De){let rt=w.byStep.get(De);if(rt)return w.lastId=rt,rt}if(w.lastId&&!Ae)return w.lastId;if(!Ae)return null;let _e=`reason-${l()}`;return ge(De,_e),_e},Le=N=>{let Ae=H.get(N);if(Ae)return Ae;let Be={id:`reason-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:N,status:"streaming",chunks:[]}};return H.set(N,Be),g(Be),Be},He=(N,Ae)=>{I.lastId=Ae,N&&I.byCall.set(N,Ae)},ee=new Set,Pe=new Map,V=new Set,le=new Map,ve=N=>{if(!N)return!1;let Ae=N.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ae==="emit_artifact_markdown"||Ae==="emit_artifact_component"},fe=(N,Ae)=>{var dt;let Be=(dt=N.toolId)!=null?dt:N.id,De=oe(N);if(Be){let rt=String(Be);return He(De,rt),rt}if(De){let rt=I.byCall.get(De);if(rt)return I.lastId=rt,rt}if(I.lastId&&!Ae)return I.lastId;if(!Ae)return null;let _e=`tool-${l()}`;return He(De,_e),_e},we=N=>{let Ae=L.get(N);if(Ae)return Ae;let Be={id:`tool-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:N,status:"pending"}};return L.set(N,Be),g(Be),Be},ze=N=>{if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){let Ae=Number(N);if(!Number.isNaN(Ae)&&Number.isFinite(Ae))return Ae;let Be=Date.parse(N);if(!Number.isNaN(Be))return Be}return Date.now()},Q=N=>{if(typeof N=="string")return N;if(N==null)return"";try{return JSON.stringify(N)}catch{return String(N)}},te=new Map,se=new Map,ue=new Map,ie=new Map,re=null,Qe=(N,Ae,Be)=>{var At;let De=ue.get(N);De||(De=[],ue.set(N,De));let _e=0,dt=De.length;for(;_e<dt;){let _t=_e+dt>>>1;De[_t].seq<Ae?_e=_t+1:dt=_t}((At=De[_e])==null?void 0:At.seq)===Ae?De[_e]={seq:Ae,text:Be}:De.splice(_e,0,{seq:Ae,text:Be});let rt="";for(let _t=0;_t<De.length;_t++)rt+=De[_t].text;return rt},Ie=(N,Ae)=>{let Be=Q(Ae),De=se.get(N.id),_e=Zm(De,Be);N.rawContent=_e;let dt=te.get(N.id),rt=Ye=>{var ne;let Dt=(ne=N.content)!=null?ne:"";Ye.trim()!==""&&(Dt.trim().length===0||Ye.startsWith(Dt)||Ye.trimStart().startsWith(Dt.trim()))&&(N.content=Ye)},At=()=>{var Ye;if(dt){let Dt=(Ye=dt.close)==null?void 0:Ye.call(dt);Dt instanceof Promise&&Dt.catch(()=>{})}te.delete(N.id),se.delete(N.id),N.streaming=!1,g(N)};if(!dt){rt(Be),At();return}let _t=So(_e);if(_t!==null&&_t.trim()!==""){rt(_t),At();return}let q=Ye=>{var me;let Dt=typeof Ye=="string"?Ye:(me=Ye==null?void 0:Ye.text)!=null?me:null;if(Dt!==null&&Dt.trim()!=="")return Dt;let ne=dt.getExtractedText();return ne!==null&&ne.trim()!==""?ne:Be},$t;try{$t=dt.processChunk(_e)}catch{rt(Be),At();return}if($t instanceof Promise){$t.then(Ye=>{rt(q(Ye)),At()}).catch(()=>{rt(Be),At()});return}rt(q($t)),At()},ce=[],G=!1,$e,Et=()=>{G||(G=!0,queueMicrotask(()=>{G=!1,$e()}))},de=new ka((N,Ae)=>{ce.push({payloadType:N,payload:Ae}),Et()}),ae=null,Mn=new Map,Ot=(ln=this.config.iterationDisplay)!=null?ln:"separate";for($e=()=>{var N,Ae,Be,De,_e,dt,rt,At,_t,q,$t,Ye,Dt,ne,me,vt,jt,Zt,hn,St,wt,ft,yt,zt,tt,Bn,Qn,yn,Dn,ut,xr,Nn,po,kn,Io,Or,Er,bt,Fn,On,bn,Lt,Yn,Zn,$n,$r,Mr,_r,_n,Wt,xn,er,jr,kr,Ur,vr,jn,lr,gt,Jt,Gt,Un,qr,tr,cr,qn,S,zn,dr,Lr,wr,ss,pr,ur,mr,Pr,uo,Zs,as,ea,Wo,mt,is,nr,Ln,ta,na,Ro,Ir,ra,mo,ls,Wr,cs,zr,Vr,oa,sa,wi,go,Kr,aa,ds,Jr,ia,ps,Gr,us,la,Rr,ca,Xr,Rt,Ho,Bo,ms,Cr,da,gs,fs,pa,Do,No,fo,ua,ma,hs,ys,bs,xs,vn,Vn,Hr,ot,vs,ho,gr,ga;for(let Qr=0;Qr<ce.length;Qr++){let Ve=ce[Qr].payloadType,A=ce[Qr].payload;if(Ve==="reason_start"){let _=(N=ye(A,!0))!=null?N:`reason-${l()}`,k=Le(_);k.reasoning=(Ae=k.reasoning)!=null?Ae:{id:_,status:"streaming",chunks:[]},k.reasoning.startedAt=(De=k.reasoning.startedAt)!=null?De:ze((Be=A.startedAt)!=null?Be:A.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",g(k)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let _=(dt=(_e=ye(A,!1))!=null?_e:ye(A,!0))!=null?dt:`reason-${l()}`,k=Le(_);k.reasoning=(rt=k.reasoning)!=null?rt:{id:_,status:"streaming",chunks:[]},k.reasoning.startedAt=(_t=k.reasoning.startedAt)!=null?_t:ze((At=A.startedAt)!=null?At:A.timestamp);let Y=(Ye=($t=(q=A.reasoningText)!=null?q:A.text)!=null?$t:A.delta)!=null?Ye:"";if(Y&&A.hidden!==!0){let K=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(K!==void 0){let J=Qe(_,K,String(Y));k.reasoning.chunks=[J]}else k.reasoning.chunks.push(String(Y))}if(k.reasoning.status=A.done?"complete":"streaming",A.done){k.reasoning.completedAt=ze((Dt=A.completedAt)!=null?Dt:A.timestamp);let K=(ne=k.reasoning.startedAt)!=null?ne:Date.now();k.reasoning.durationMs=Math.max(0,((me=k.reasoning.completedAt)!=null?me:Date.now())-K)}k.streaming=k.reasoning.status!=="complete",g(k)}else if(Ve==="reason_complete"){let _=(jt=(vt=ye(A,!1))!=null?vt:ye(A,!0))!=null?jt:`reason-${l()}`,k=H.get(_);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=ze((Zt=A.completedAt)!=null?Zt:A.timestamp);let K=(hn=k.reasoning.startedAt)!=null?hn:Date.now();k.reasoning.durationMs=Math.max(0,((St=k.reasoning.completedAt)!=null?St:Date.now())-K),k.streaming=!1,g(k)}let Y=z(A);Y&&w.byStep.delete(Y)}else if(Ve==="tool_start"){let _=(wt=fe(A,!0))!=null?wt:`tool-${l()}`,k=(ft=A.toolName)!=null?ft:A.name;if(ve(k)){ee.add(_);continue}let Y=we(_),K=(yt=Y.toolCall)!=null?yt:{id:_,status:"pending"};K.name=k!=null?k:K.name,K.status="running",A.args!==void 0?K.args=A.args:A.parameters!==void 0&&(K.args=A.parameters),K.startedAt=(tt=K.startedAt)!=null?tt:ze((zt=A.startedAt)!=null?zt:A.timestamp),K.completedAt=void 0,K.durationMs=void 0,Y.toolCall=K,Y.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(Y.agentMetadata={executionId:(Bn=J==null?void 0:J.executionId)!=null?Bn:A.executionId,iteration:(Qn=J==null?void 0:J.iteration)!=null?Qn:A.iteration}),g(Y)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let _=(Dn=(yn=fe(A,!1))!=null?yn:fe(A,!0))!=null?Dn:`tool-${l()}`;if(ee.has(_))continue;let k=we(_),Y=(ut=k.toolCall)!=null?ut:{id:_,status:"running"};Y.startedAt=(Nn=Y.startedAt)!=null?Nn:ze((xr=A.startedAt)!=null?xr:A.timestamp);let K=(Io=(kn=(po=A.text)!=null?po:A.delta)!=null?kn:A.message)!=null?Io:"";K&&(Y.chunks=(Or=Y.chunks)!=null?Or:[],Y.chunks.push(String(K))),Y.status="running",k.toolCall=Y,k.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(k.agentMetadata=(Fn=k.agentMetadata)!=null?Fn:{executionId:(Er=J==null?void 0:J.executionId)!=null?Er:A.executionId,iteration:(bt=J==null?void 0:J.iteration)!=null?bt:A.iteration}),g(k)}else if(Ve==="tool_complete"){let _=(bn=(On=fe(A,!1))!=null?On:fe(A,!0))!=null?bn:`tool-${l()}`;if(ee.has(_)){ee.delete(_);continue}let k=we(_),Y=(Lt=k.toolCall)!=null?Lt:{id:_,status:"running"};Y.status="complete",A.result!==void 0&&(Y.result=A.result),typeof A.duration=="number"&&(Y.duration=A.duration),Y.completedAt=ze((Yn=A.completedAt)!=null?Yn:A.timestamp);let K=(Zn=A.duration)!=null?Zn:A.executionTime;if(typeof K=="number")Y.durationMs=K;else{let Oe=($n=Y.startedAt)!=null?$n:Date.now();Y.durationMs=Math.max(0,(($r=Y.completedAt)!=null?$r:Date.now())-Oe)}k.toolCall=Y,k.streaming=!1;let J=A.agentContext;(J||A.executionId)&&(k.agentMetadata=(_n=k.agentMetadata)!=null?_n:{executionId:(Mr=J==null?void 0:J.executionId)!=null?Mr:A.executionId,iteration:(_r=J==null?void 0:J.iteration)!=null?_r:A.iteration}),g(k);let Xe=oe(A);Xe&&I.byCall.delete(Xe)}else if(Ve==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let _=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,k=(Wt=_!=null?_:A.toolId)!=null?Wt:`local-${l()}`,Y=we(k),K=(xn=Y.toolCall)!=null?xn:{id:k,status:"pending"};K.name=A.toolName,K.args=A.parameters,K.status="complete",K.chunks=(er=K.chunks)!=null?er:[],K.startedAt=(kr=K.startedAt)!=null?kr:ze((jr=A.startedAt)!=null?jr:A.timestamp),K.completedAt=(Ur=K.completedAt)!=null?Ur:K.startedAt,Y.toolCall=K,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(jn=A.executionId)!=null?jn:(vr=Y.agentMetadata)==null?void 0:vr.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},g(Y)}else if(Ve==="text_start"){if((lr=A.toolContext)!=null&&lr.toolId)continue;let _=A.partId;if(_!==void 0&&C.current!==null&&_!==C.current){let k=u;k&&(k.streaming=!1,g(k),re=k,u=null,T=!0)}_!==void 0&&(C.current=_)}else if(Ve==="text_end"){if((gt=A.toolContext)!=null&&gt.toolId)continue;let _=u;_&&(_.streaming=!1,g(_),re=_,u=null,T=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let _=A.stepType,k=A.executionType;if(_==="tool"||k==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let Oe=String((Gt=(Jt=A.id)!=null?Jt:Y.stepId)!=null?Gt:`step-${l()}`),et=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ee=`${Y.toolId}::${Oe}`,Je=W.get(Ee);if(et!==""&&Je!==void 0&&Je!==""&&Je!==et){let Ct=P.get(O(Y.toolId,Oe,Je));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,g(Ct))}et!==""&&W.set(Ee,et);let Pt=B(Y.toolId,Oe,et,Y.executionId),nn=(cr=(tr=(qr=(Un=A.text)!=null?Un:A.delta)!=null?qr:A.content)!=null?tr:A.chunk)!=null?cr:"";nn&&(Pt.content+=String(nn),Pt.streaming=!0,g(Pt)),A.isComplete&&(Pt.streaming=!1,g(Pt));continue}let K=A.partId;if(K!==void 0&&C.current!==null&&K!==C.current){let Oe=u;Oe&&(Oe.streaming=!1,g(Oe),re=Oe,u=null,T=!0)}K!==void 0&&(C.current=K);let J=K!==void 0&&(qn=ie.get(K))!=null?qn:Ne();K!==void 0&&(J.partId||(J.partId=K),ie.set(K,J));let Xe=(Lr=(dr=(zn=(S=A.text)!=null?S:A.delta)!=null?zn:A.content)!=null?dr:A.chunk)!=null?Lr:"";if(Xe){let Oe=typeof A.seq=="number"?A.seq:void 0,et=K!=null?K:J.id,Ee=Oe!==void 0?Qe(et,Oe,String(Xe)):((wr=se.get(J.id))!=null?wr:"")+Xe;J.rawContent=Ee,te.has(J.id)||te.set(J.id,this.createStreamParser());let Je=te.get(J.id),Pt=Ee.trim().startsWith("{")||Ee.trim().startsWith("[");if(Pt&&se.set(J.id,Ee),Je.__isPlainTextParser===!0){J.content=Oe!==void 0?Ee:J.content+Xe,se.delete(J.id),te.delete(J.id),J.rawContent=void 0,g(J);continue}let Ct=Je.processChunk(Ee);if(Ct instanceof Promise)Ct.then(Mt=>{var pn;let rn=typeof Mt=="string"?Mt:(pn=Mt==null?void 0:Mt.text)!=null?pn:null;if(rn!==null&&rn.trim()!=="")J.content=rn,g(J);else if(!Pt&&!Ee.trim().startsWith("<")){let wn=u,Xt=wn&&wn.id===J.id?wn:J;Xt.id===J.id&&(Xt.content=Oe!==void 0?Ee:Xt.content+Xe,se.delete(Xt.id),te.delete(Xt.id),Xt.rawContent=void 0,g(Xt))}}).catch(()=>{J.content=Oe!==void 0?Ee:J.content+Xe,se.delete(J.id),te.delete(J.id),J.rawContent=void 0,g(J)});else{let Mt=typeof Ct=="string"?Ct:(ss=Ct==null?void 0:Ct.text)!=null?ss:null;Mt!==null&&Mt.trim()!==""?(J.content=Mt,g(J)):!Pt&&!Ee.trim().startsWith("<")&&(J.content=Oe!==void 0?Ee:J.content+Xe,se.delete(J.id),te.delete(J.id),J.rawContent=void 0,g(J))}}if(A.isComplete){let Oe=(ur=(pr=A.result)==null?void 0:pr.response)!=null?ur:J.content;if(Oe){let et=se.get(J.id),Ee=et!=null?et:Q(Oe);J.rawContent=Ee;let Je=te.get(J.id),Pt=null,nn=!1;if(Je&&(Pt=Je.getExtractedText(),Pt===null&&(Pt=So(Ee)),Pt===null)){let Ct=Je.processChunk(Ee);Ct instanceof Promise?(nn=!0,Ct.then(Mt=>{var pn;let rn=typeof Mt=="string"?Mt:(pn=Mt==null?void 0:Mt.text)!=null?pn:null;if(rn!==null){let wn=u;wn&&wn.id===J.id&&(wn.content=rn,wn.streaming=!1,te.delete(wn.id),se.delete(wn.id),g(wn))}})):Pt=typeof Ct=="string"?Ct:(mr=Ct==null?void 0:Ct.text)!=null?mr:null}if(!nn){Pt!==null&&Pt.trim()!==""?J.content=Pt:se.has(J.id)||(J.content=Q(Oe));let Ct=te.get(J.id);if(Ct){let Mt=(Pr=Ct.close)==null?void 0:Pr.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),te.delete(J.id)}se.delete(J.id),J.streaming=!1,g(J)}}}}else if(Ve==="step_complete"){let _=A.stepType,k=A.executionType;if(_==="tool"||k==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let Oe=String((Zs=(uo=A.id)!=null?uo:Y.stepId)!=null?Zs:"");if(Oe){let et=$(Y.toolId,Oe);for(let[Ee,Je]of P)Ee.startsWith(et)&&Je.streaming!==!1&&(Je.streaming=!1,g(Je));W.delete(`${Y.toolId}::${Oe}`)}continue}let K=A.stopReason;if(T){if(u!==null){let Ee=u;K&&(Ee.stopReason=K),te.delete(Ee.id),se.delete(Ee.id),Ee.streaming!==!1&&(Ee.streaming=!1,g(Ee))}let Oe=(as=A.result)==null?void 0:as.response,et=re;et&&(K&&(et.stopReason=K),Oe!=null?Ie(et,Oe):(te.delete(et.id),se.delete(et.id))),re=null;continue}let J=(ea=A.result)==null?void 0:ea.response,Xe=Ne();if(K&&(Xe.stopReason=K),J!=null){let Oe=te.get(Xe.id),et=!1,Ee=!1;if(Oe){let Je=Oe.getExtractedText(),Pt=se.get(Xe.id),nn=Pt!=null?Pt:Q(J);if(Xe.rawContent=nn,Je!==null&&Je.trim()!=="")Xe.content=Je,et=!0;else{let Ct=So(nn);if(Ct!==null)Xe.content=Ct,et=!0;else{let Mt=Oe.processChunk(nn);if(Mt instanceof Promise)Ee=!0,Mt.then(rn=>{var wn;let pn=typeof rn=="string"?rn:(wn=rn==null?void 0:rn.text)!=null?wn:null;if(pn!==null&&pn.trim()!==""){let Xt=u;Xt&&Xt.id===Xe.id&&(Xt.content=pn,Xt.streaming=!1,te.delete(Xt.id),se.delete(Xt.id),g(Xt))}else{let Xt=Oe.getExtractedText(),rr=u;rr&&rr.id===Xe.id&&(Xt!==null&&Xt.trim()!==""?rr.content=Xt:se.has(rr.id)||(rr.content=Q(J)),rr.streaming=!1,te.delete(rr.id),se.delete(rr.id),g(rr))}});else{let rn=typeof Mt=="string"?Mt:(Wo=Mt==null?void 0:Mt.text)!=null?Wo:null;if(rn!==null&&rn.trim()!=="")Xe.content=rn,et=!0;else{let pn=Oe.getExtractedText();pn!==null&&pn.trim()!==""&&(Xe.content=pn,et=!0)}}}}}if(!Ee){if(!Xe.rawContent){let Je=se.get(Xe.id);Xe.rawContent=Je!=null?Je:Q(J)}if(!et&&!se.has(Xe.id)&&(Xe.content=Q(J)),Oe){let Je=(mt=Oe.close)==null?void 0:mt.call(Oe);Je instanceof Promise&&Je.catch(()=>{})}te.delete(Xe.id),se.delete(Xe.id),Xe.streaming=!1,g(Xe)}}else te.delete(Xe.id),se.delete(Xe.id),Xe.streaming=!1,g(Xe)}else if(Ve==="flow_complete"){let _=(is=A.result)==null?void 0:is.response;if(T){if(u!==null){let k=u;te.delete(k.id),se.delete(k.id),k.streaming!==!1&&(k.streaming=!1,g(k))}}else if(_!=null){let k=Ne(),Y=se.get(k.id),K=Y!=null?Y:Q(_);k.rawContent=K;let J=Q(_),Xe=te.get(k.id);if(Xe){let Ee=So(K);if(Ee!==null)J=Ee;else{let Je=Xe.processChunk(K);Je instanceof Promise&&Je.then(nn=>{var Mt;let Ct=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;Ct!==null&&(k.content=Ct,k.streaming=!1,g(k))});let Pt=Xe.getExtractedText();Pt!==null&&(J=Pt)}}te.delete(k.id),se.delete(k.id);let Oe=J!==k.content,et=k.streaming!==!1;Oe&&(k.content=J),k.streaming=!1,(Oe||et)&&g(k)}else if(u!==null){let k=u;te.delete(k.id),se.delete(k.id),k.streaming!==!1&&(k.streaming=!1,g(k))}n({type:"status",status:"idle"})}else if(Ve==="agent_start")ae={executionId:A.executionId,agentId:(nr=A.agentId)!=null?nr:"virtual",agentName:(Ln=A.agentName)!=null?Ln:"",status:"running",currentIteration:0,maxTurns:(ta=A.maxTurns)!=null?ta:1,startedAt:ze(A.startedAt)};else if(Ve==="agent_iteration_start"){if(ae&&(ae.currentIteration=A.iteration),Ot==="separate"&&A.iteration>1){let _=u;_&&(_.streaming=!1,g(_),Mn.set(A.iteration-1,_),u=null)}}else if(Ve==="agent_turn_start")v=null;else if(Ve==="agent_turn_delta"){if(A.contentType==="text"){let _=Ne();_.content+=(na=A.delta)!=null?na:"",_.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ae==null?void 0:ae.agentName},v=_,g(_)}else if(A.contentType==="thinking"){let _=(Ro=A.turnId)!=null?Ro:`agent-think-${A.iteration}`,k=Le(_);k.reasoning=(Ir=k.reasoning)!=null?Ir:{id:_,status:"streaming",chunks:[]},k.reasoning.chunks.push((ra=A.delta)!=null?ra:""),k.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},g(k)}else if(A.contentType==="tool_input"){let _=(mo=A.toolCallId)!=null?mo:I.lastId;if(_){let k=L.get(_);k!=null&&k.toolCall&&(k.toolCall.chunks=(ls=k.toolCall.chunks)!=null?ls:[],k.toolCall.chunks.push((Wr=A.delta)!=null?Wr:""),g(k))}}}else if(Ve==="agent_turn_complete"){let _=A.turnId;if(_){let K=H.get(_);if(K!=null&&K.reasoning){K.reasoning.status="complete",K.reasoning.completedAt=ze(A.completedAt);let J=(cs=K.reasoning.startedAt)!=null?cs:Date.now();K.reasoning.durationMs=Math.max(0,((zr=K.reasoning.completedAt)!=null?zr:Date.now())-J),K.streaming=!1,g(K)}}let k=A.stopReason,Y=u!=null?u:v;if(k&&Y!==null){let K=A.turnId;(!K||((Vr=Y.agentMetadata)==null?void 0:Vr.turnId)===K)&&(Y.stopReason=k,g(Y))}}else if(Ve==="agent_tool_start"){u&&(u.streaming=!1,g(u),u=null);let _=(oa=A.toolCallId)!=null?oa:`agent-tool-${l()}`;He(oe(A),_);let k=we(_),Y=(sa=k.toolCall)!=null?sa:{id:_,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(go=(wi=A.toolName)!=null?wi:A.name)!=null?go:Y.name,Y.status="running",A.parameters!==void 0&&(Y.args=A.parameters),Y.startedAt=ze((Kr=A.startedAt)!=null?Kr:A.timestamp),k.toolCall=Y,k.streaming=!0,k.agentMetadata={executionId:A.executionId,iteration:A.iteration},g(k)}else if(Ve==="agent_tool_delta"){let _=(aa=A.toolCallId)!=null?aa:I.lastId;if(_){let k=(ds=L.get(_))!=null?ds:we(_);k.toolCall&&(k.toolCall.chunks=(Jr=k.toolCall.chunks)!=null?Jr:[],k.toolCall.chunks.push((ia=A.delta)!=null?ia:""),k.toolCall.status="running",k.streaming=!0,g(k))}}else if(Ve==="agent_tool_complete"){let _=(ps=A.toolCallId)!=null?ps:I.lastId;if(_){let k=(Gr=L.get(_))!=null?Gr:we(_);if(k.toolCall){k.toolCall.status="complete",A.result!==void 0&&(k.toolCall.result=A.result),typeof A.executionTime=="number"&&(k.toolCall.durationMs=A.executionTime),k.toolCall.completedAt=ze((us=A.completedAt)!=null?us:A.timestamp),k.streaming=!1,g(k);let Y=oe(A);Y&&I.byCall.delete(Y)}}}else if(Ve==="agent_media"){let _=Array.isArray(A.media)?A.media:[],k=[];for(let Y of _){if(!Y||typeof Y!="object")continue;let K=Y,J=typeof K.type=="string"?K.type:void 0,Xe=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",Oe=null,et="";if(J==="media"){let Ee=typeof K.data=="string"?K.data:void 0;if(!Ee)continue;et=Xe.length>0?Xe:"application/octet-stream",Oe=`data:${et};base64,${Ee}`}else if(J==="image-url"){let Ee=typeof K.url=="string"?K.url:void 0;if(!Ee)continue;et=Xe,Oe=Ee}else if(J==="file-url"){let Ee=typeof K.url=="string"?K.url:void 0;if(!Ee)continue;et=Xe,Oe=Ee}else continue;if(Oe)if(J==="image-url"||et.startsWith("image/"))k.push({type:"image",image:Oe,...et?{mimeType:et}:{}});else if(et.startsWith("audio/"))k.push({type:"audio",audio:Oe,mimeType:et});else if(et.startsWith("video/"))k.push({type:"video",video:Oe,mimeType:et});else{let Ee=et||"application/octet-stream";k.push({type:"file",data:Oe,mimeType:Ee,filename:Qm(Ee)})}}if(k.length>0){let Y=l(),K=A.toolCallId,Xe={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(Xe);let Oe=u;Oe&&(Oe.streaming=!1,g(Oe)),u=null,x.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let _=`agent-reflection-${A.executionId}-${A.iteration}`,k={id:_,role:"assistant",content:(la=A.reflection)!=null?la:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"complete",chunks:[(Rr=A.reflection)!=null?Rr:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(k)}else if(Ve==="agent_complete"){ae&&(ae.status=A.success?"complete":"error",ae.completedAt=ze(A.completedAt),ae.stopReason=A.stopReason);let _=u;_&&(_.streaming=!1,g(_)),n({type:"status",status:"idle"})}else if(Ve==="agent_error"){let _=typeof A.error=="string"?A.error:(Xr=(ca=A.error)==null?void 0:ca.message)!=null?Xr:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",_):n({type:"error",error:new Error(_)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let _=(Rt=A.approvalId)!=null?Rt:`approval-${l()}`,k={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:"pending",agentId:(Ho=ae==null?void 0:ae.agentId)!=null?Ho:"virtual",executionId:(ms=(Bo=A.executionId)!=null?Bo:ae==null?void 0:ae.executionId)!=null?ms:"",toolName:(Cr=A.toolName)!=null?Cr:"",toolType:A.toolType,description:(gs=A.description)!=null?gs:`Execute ${(da=A.toolName)!=null?da:"tool"}`,parameters:A.parameters}};g(k)}else if(Ve==="step_await"&&A.awaitReason==="approval_required"){let _=(fs=A.approvalId)!=null?fs:`approval-${l()}`,k={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:"pending",agentId:(pa=ae==null?void 0:ae.agentId)!=null?pa:"virtual",executionId:(No=(Do=A.executionId)!=null?Do:ae==null?void 0:ae.executionId)!=null?No:"",toolName:(fo=A.toolName)!=null?fo:"",toolType:A.toolType,description:(ma=A.description)!=null?ma:`Execute ${(ua=A.toolName)!=null?ua:"tool"}`,parameters:A.parameters}};g(k)}else if(Ve==="agent_approval_complete"){let _=A.approvalId;if(_){let Y={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:(hs=A.decision)!=null?hs:"approved",agentId:(ys=ae==null?void 0:ae.agentId)!=null?ys:"virtual",executionId:(xs=(bs=A.executionId)!=null?bs:ae==null?void 0:ae.executionId)!=null?xs:"",toolName:(vn=A.toolName)!=null?vn:"",description:(Vn=A.description)!=null?Vn:"",resolvedAt:Date.now()}};g(Y)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let _=A.artifactType,k=String(A.id),Y=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:k,artifactType:_,title:Y,component:typeof A.component=="string"?A.component:void 0}),le.set(k,{markdown:"",title:Y}),!V.has(k)){V.add(k);let K={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Y,artifactType:_,status:"streaming"}})};Pe.set(k,K),g(K)}}else if(Ve==="artifact_delta"){let _=String(A.id),k=typeof A.delta=="string"?A.delta:String((Hr=A.delta)!=null?Hr:"");n({type:"artifact_delta",id:_,artDelta:k});let Y=le.get(_);Y&&(Y.markdown+=k)}else if(Ve==="artifact_update"){let _=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:_,component:typeof A.component=="string"?A.component:void 0})}else if(Ve==="artifact_complete"){let _=String(A.id);n({type:"artifact_complete",id:_});let k=Pe.get(_);if(k){k.streaming=!1;try{let Y=JSON.parse((ot=k.rawContent)!=null?ot:"{}");if(Y.props){Y.props.status="complete";let K=le.get(_);K!=null&&K.markdown&&(Y.props.markdown=K.markdown)}k.rawContent=JSON.stringify(Y)}catch{}le.delete(_),g(k),Pe.delete(_)}}}else if(Ve==="transcript_insert"){let _=A.message;if(!_||typeof _!="object")continue;let k=String((vs=_.id)!=null?vs:`msg-${l()}`),Y=_.role,J={id:k,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof _.content=="string"?_.content:"",rawContent:typeof _.rawContent=="string"?_.rawContent:void 0,createdAt:typeof _.createdAt=="string"?_.createdAt:new Date().toISOString(),streaming:_.streaming===!0,...typeof _.variant=="string"?{variant:_.variant}:{},sequence:l()};if(g(J),J.rawContent)try{let Xe=JSON.parse(J.rawContent),Oe=(ho=Xe==null?void 0:Xe.props)==null?void 0:ho.artifactId;typeof Oe=="string"&&V.add(Oe)}catch{}u=null,x.current=null,te.delete(k),se.delete(k)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let _=null;if(A.error instanceof Error)_=A.error;else if(Ve==="dispatch_error"){let k=(gr=A.message)!=null?gr:A.error;k!=null&&k!==""&&(_=new Error(String(k)))}else if(Ve==="step_error"||Ve==="flow_error"){let k=A.error;typeof k=="string"&&k!==""?_=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&(_=new Error(String((ga=k.message)!=null?ga:k)))}else Ve==="error"&&A.error!=null&&A.error!==""&&(_=new Error(String(A.error)));if(_){n({type:"error",error:_});let k=u;k&&k.streaming&&(k.streaming=!1,g(k)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:N,value:Ae}=await s.read();if(N)break;a+=o.decode(Ae,{stream:!0});let Be=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Lo=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Pi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ii=()=>{var t;let e=sg();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Wi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=Hp(n,Bp|Dp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ta(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ta(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ag=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ta(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ta(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=Hp(o,Bp|Dp),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Ri=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var La=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var ig="https://api.runtype.com/v1/dispatch",Pa="https://api.runtype.com";function lg(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Hi=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 cg(e){switch(e){case"json":return Wi;case"regex-json":return Ii;case"xml":return Ri;default:return Pi}}var Fp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function dg(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Fp(n);if(!Fp(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Lo(e);return Lo(t)!==null&&a===null?t:e}var Xo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:ig,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:cg(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new Ws(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;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 r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pa}/v1/client/feedback`}async sendFeedback(t){var o,a;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 s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let L=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:L}),L}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Hi).map(L=>{var I,A,P;return{id:L.id,role:L.role,content:(P=(A=(I=L.contentParts)!=null?I:L.llmContent)!=null?A:L.rawContent)!=null?P:L.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,m=!!(f&&f.length>0),v=m?Rp(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,w=m&&x&&this.lastSentClientToolsFingerprint===v,S=!1,H=null,M;for(let L=0;;L++){let A={...u,...m&&(S||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),signal:r.signal}),M.status===409&&L===0&&m){let P=await M.json().catch(()=>null);if((P==null?void 0:P.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}H=P!=null?P:{error:"Chat request failed"}}break}if(!M.ok){let L=H!=null?H:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:A}),A}if(M.status===429){let A=new Error(L.hint||"Message limit reached for this session.");throw n({type:"error",error:A}),A}let I=new Error(L.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!M.body){let L=new Error("No response body received");throw n({type:"error",error:L}),L}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(M.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pa}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Pa}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Hi).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(t){var o;let r={messages:t.slice().filter(Hi).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=u,s(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var mn,Hn,Yn,je;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=O=>{let Te=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Be=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,De=O.tools?O.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{...O,reasoning:Te,toolCall:Be,tools:De}},u=O=>{if(O.role!=="assistant"||O.variant)return!0;let Te=Array.isArray(O.contentParts)&&O.contentParts.length>0,Be=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||Te||Be||!!O.stopReason},f=O=>{u(O)&&n({type:"message",message:p(O)})},m=null,v=null,x={current:null},w={current:null},S=!1,H=new Map,M=new Map,L=new Map,I=new Map,A={lastId:null,byStep:new Map},P={lastId:null,byCall:new Map},F=(O,Te,Be="")=>`${O}::${Te}::${Be}`,B=(O,Te)=>`${O}::${Te}::`,W=(O,Te,Be,De)=>{let $e=F(O,Te,Be),ut=L.get($e);if(ut)return ut;let st=Be?`-${Be}`:"",Pt={id:`nested-${O}-${Te}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:De,parentToolId:O,parentStepId:Te}};return L.set($e,Pt),f(Pt),Pt},U=O=>{if(O==null)return null;try{return String(O)}catch{return null}},V=O=>{var Te,Be,De,$e,ut;return U((ut=($e=(De=(Be=(Te=O.stepId)!=null?Te:O.step_id)!=null?Be:O.step)!=null?De:O.parentId)!=null?$e:O.flowStepId)!=null?ut:O.flow_step_id)},oe=O=>{var Te,Be,De,$e,ut,st,Pt;return U((Pt=(st=(ut=($e=(De=(Be=(Te=O.callId)!=null?Te:O.call_id)!=null?Be:O.requestId)!=null?De:O.request_id)!=null?$e:O.toolCallId)!=null?ut:O.tool_call_id)!=null?st:O.stepId)!=null?Pt:O.step_id)},We=r,Je=!1,ve=()=>{if(m)return m;let O;return!Je&&We?(O=We,Je=!0):We&&w.current?O=`${We}_${w.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},Re=(O,Te)=>{A.lastId=Te,O&&A.byStep.set(O,Te)},he=(O,Te)=>{var ut;let Be=(ut=O.reasoningId)!=null?ut:O.id,De=V(O);if(Be){let st=String(Be);return Re(De,st),st}if(De){let st=A.byStep.get(De);if(st)return A.lastId=st,st}if(A.lastId&&!Te)return A.lastId;if(!Te)return null;let $e=`reason-${l()}`;return Re(De,$e),$e},He=O=>{let Te=H.get(O);if(Te)return Te;let Be={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return H.set(O,Be),f(Be),Be},Le=(O,Te)=>{P.lastId=Te,O&&P.byCall.set(O,Te)},K=new Set,pe=new Map,z=new Set,ce=new Map,ie=O=>{if(!O)return!1;let Te=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return Te==="emit_artifact_markdown"||Te==="emit_artifact_component"},se=(O,Te)=>{var ut;let Be=(ut=O.toolId)!=null?ut:O.id,De=oe(O);if(Be){let st=String(Be);return Le(De,st),st}if(De){let st=P.byCall.get(De);if(st)return P.lastId=st,st}if(P.lastId&&!Te)return P.lastId;if(!Te)return null;let $e=`tool-${l()}`;return Le(De,$e),$e},Ae=O=>{let Te=M.get(O);if(Te)return Te;let Be={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return M.set(O,Be),f(Be),Be},qe=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let Te=Number(O);if(!Number.isNaN(Te)&&Number.isFinite(Te))return Te;let Be=Date.parse(O);if(!Number.isNaN(Be))return Be}return Date.now()},Q=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},te=new Map,le=new Map,ye=new Map,ue=new Map,re=null,Ye=(O,Te,Be)=>{var Pt;let De=ye.get(O);De||(De=[],ye.set(O,De));let $e=0,ut=De.length;for(;$e<ut;){let zt=$e+ut>>>1;De[zt].seq<Te?$e=zt+1:ut=zt}((Pt=De[$e])==null?void 0:Pt.seq)===Te?De[$e]={seq:Te,text:Be}:De.splice($e,0,{seq:Te,text:Be});let st="";for(let zt=0;zt<De.length;zt++)st+=De[zt].text;return st},Ie=(O,Te)=>{let Be=Q(Te),De=le.get(O.id),$e=dg(De,Be);O.rawContent=$e;let ut=te.get(O.id),st=Ze=>{var ne;let Ft=(ne=O.content)!=null?ne:"";Ze.trim()!==""&&(Ft.trim().length===0||Ze.startsWith(Ft)||Ze.trimStart().startsWith(Ft.trim()))&&(O.content=Ze)},Pt=()=>{var Ze;if(ut){let Ft=(Ze=ut.close)==null?void 0:Ze.call(ut);Ft instanceof Promise&&Ft.catch(()=>{})}te.delete(O.id),le.delete(O.id),O.streaming=!1,f(O)};if(!ut){st(Be),Pt();return}let zt=Lo($e);if(zt!==null&&zt.trim()!==""){st(zt),Pt();return}let q=Ze=>{var xe;let Ft=typeof Ze=="string"?Ze:(xe=Ze==null?void 0:Ze.text)!=null?xe:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let ne=ut.getExtractedText();return ne!==null&&ne.trim()!==""?ne:Be},Ut;try{Ut=ut.processChunk($e)}catch{st(Be),Pt();return}if(Ut instanceof Promise){Ut.then(Ze=>{st(q(Ze)),Pt()}).catch(()=>{st(Be),Pt()});return}st(q(Ut)),Pt()},ge=[],G=!1,Fe,Rt=()=>{G||(G=!0,queueMicrotask(()=>{G=!1,Fe()}))},fe=new La((O,Te)=>{ge.push({payloadType:O,payload:Te}),Rt()}),de=null,Ln=new Map,jt=(mn=this.config.iterationDisplay)!=null?mn:"separate";for(Fe=()=>{var O,Te,Be,De,$e,ut,st,Pt,zt,q,Ut,Ze,Ft,ne,xe,Tt,Vt,tn,wn,It,Mt,vt,Ct,Jt,rt,Bn,Zn,Cn,Dn,ht,Tr,Nn,fo,Pn,Do,jr,Ir,At,On,Fn,An,kt,er,tr,$n,Ur,Wr,qr,_n,Bt,Sn,nr,zr,Rr,Vr,Er,jn,gr,yt,Xt,Qt,Un,Kr,rr,fr,qn,$,or,be,zn,sr,hr,ps,br,yr,xr,Hr,ho,aa,us,ia,No,bt,ms,ar,In,la,ca,Oo,Br,da,bo,gs,Dr,fs,Jr,Gr,pa,ua,Si,yo,Xr,ma,hs,Qr,ga,bs,Yr,ys,fa,Nr,ha,Zr,Dt,Fo,$o,xs,Mr,ba,vs,ws,ya,_o,jo,xo,xa,va,Cs,As,Ss,Ts,Tn,Vn,Or,lt,Es,vo,vr;for(let Uo=0;Uo<ge.length;Uo++){let Ke=ge[Uo].payloadType,C=ge[Uo].payload;if(Ke==="reason_start"){let _=(O=he(C,!0))!=null?O:`reason-${l()}`,E=He(_);E.reasoning=(Te=E.reasoning)!=null?Te:{id:_,status:"streaming",chunks:[]},E.reasoning.startedAt=(De=E.reasoning.startedAt)!=null?De:qe((Be=C.startedAt)!=null?Be:C.timestamp),E.reasoning.completedAt=void 0,E.reasoning.durationMs=void 0,E.streaming=!0,E.reasoning.status="streaming",f(E)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let _=(ut=($e=he(C,!1))!=null?$e:he(C,!0))!=null?ut:`reason-${l()}`,E=He(_);E.reasoning=(st=E.reasoning)!=null?st:{id:_,status:"streaming",chunks:[]},E.reasoning.startedAt=(zt=E.reasoning.startedAt)!=null?zt:qe((Pt=C.startedAt)!=null?Pt:C.timestamp);let Y=(Ze=(Ut=(q=C.reasoningText)!=null?q:C.text)!=null?Ut:C.delta)!=null?Ze:"";if(Y&&C.hidden!==!0){let ae=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(ae!==void 0){let J=Ye(_,ae,String(Y));E.reasoning.chunks=[J]}else E.reasoning.chunks.push(String(Y))}if(E.reasoning.status=C.done?"complete":"streaming",C.done){E.reasoning.completedAt=qe((Ft=C.completedAt)!=null?Ft:C.timestamp);let ae=(ne=E.reasoning.startedAt)!=null?ne:Date.now();E.reasoning.durationMs=Math.max(0,((xe=E.reasoning.completedAt)!=null?xe:Date.now())-ae)}E.streaming=E.reasoning.status!=="complete",f(E)}else if(Ke==="reason_complete"){let _=(Vt=(Tt=he(C,!1))!=null?Tt:he(C,!0))!=null?Vt:`reason-${l()}`,E=H.get(_);if(E!=null&&E.reasoning){E.reasoning.status="complete",E.reasoning.completedAt=qe((tn=C.completedAt)!=null?tn:C.timestamp);let ae=(wn=E.reasoning.startedAt)!=null?wn:Date.now();E.reasoning.durationMs=Math.max(0,((It=E.reasoning.completedAt)!=null?It:Date.now())-ae),E.streaming=!1,f(E)}let Y=V(C);Y&&A.byStep.delete(Y)}else if(Ke==="tool_start"){let _=(Mt=se(C,!0))!=null?Mt:`tool-${l()}`,E=(vt=C.toolName)!=null?vt:C.name;if(ie(E)){K.add(_);continue}let Y=Ae(_),ae=(Ct=Y.toolCall)!=null?Ct:{id:_,status:"pending"};ae.name=E!=null?E:ae.name,ae.status="running",C.args!==void 0?ae.args=C.args:C.parameters!==void 0&&(ae.args=C.parameters),ae.startedAt=(rt=ae.startedAt)!=null?rt:qe((Jt=C.startedAt)!=null?Jt:C.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,Y.toolCall=ae,Y.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(Y.agentMetadata={executionId:(Bn=J==null?void 0:J.executionId)!=null?Bn:C.executionId,iteration:(Zn=J==null?void 0:J.iteration)!=null?Zn:C.iteration}),f(Y)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let _=(Dn=(Cn=se(C,!1))!=null?Cn:se(C,!0))!=null?Dn:`tool-${l()}`;if(K.has(_))continue;let E=Ae(_),Y=(ht=E.toolCall)!=null?ht:{id:_,status:"running"};Y.startedAt=(Nn=Y.startedAt)!=null?Nn:qe((Tr=C.startedAt)!=null?Tr:C.timestamp);let ae=(Do=(Pn=(fo=C.text)!=null?fo:C.delta)!=null?Pn:C.message)!=null?Do:"";ae&&(Y.chunks=(jr=Y.chunks)!=null?jr:[],Y.chunks.push(String(ae))),Y.status="running",E.toolCall=Y,E.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(E.agentMetadata=(On=E.agentMetadata)!=null?On:{executionId:(Ir=J==null?void 0:J.executionId)!=null?Ir:C.executionId,iteration:(At=J==null?void 0:J.iteration)!=null?At:C.iteration}),f(E)}else if(Ke==="tool_complete"){let _=(An=(Fn=se(C,!1))!=null?Fn:se(C,!0))!=null?An:`tool-${l()}`;if(K.has(_)){K.delete(_);continue}let E=Ae(_),Y=(kt=E.toolCall)!=null?kt:{id:_,status:"running"};Y.status="complete",C.result!==void 0&&(Y.result=C.result),typeof C.duration=="number"&&(Y.duration=C.duration),Y.completedAt=qe((er=C.completedAt)!=null?er:C.timestamp);let ae=(tr=C.duration)!=null?tr:C.executionTime;if(typeof ae=="number")Y.durationMs=ae;else{let Oe=($n=Y.startedAt)!=null?$n:Date.now();Y.durationMs=Math.max(0,((Ur=Y.completedAt)!=null?Ur:Date.now())-Oe)}E.toolCall=Y,E.streaming=!1;let J=C.agentContext;(J||C.executionId)&&(E.agentMetadata=(_n=E.agentMetadata)!=null?_n:{executionId:(Wr=J==null?void 0:J.executionId)!=null?Wr:C.executionId,iteration:(qr=J==null?void 0:J.iteration)!=null?qr:C.iteration}),f(E);let Me=oe(C);Me&&P.byCall.delete(Me)}else if(Ke==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let _=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,E=(Bt=_!=null?_:C.toolId)!=null?Bt:`local-${l()}`,Y=Ae(E),ae=C.toolName,J=ko(ae),Me=(Sn=Y.toolCall)!=null?Sn:{id:E,status:"pending"};Me.name=ae,Me.args=C.parameters,Me.status=J?"running":"complete",Me.chunks=(nr=Me.chunks)!=null?nr:[],Me.startedAt=(Rr=Me.startedAt)!=null?Rr:qe((zr=C.startedAt)!=null?zr:C.timestamp),J?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(Vr=Me.completedAt)!=null?Vr:Me.startedAt,Y.toolCall=Me,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(jn=C.executionId)!=null?jn:(Er=Y.agentMetadata)==null?void 0:Er.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},f(Y)}else if(Ke==="text_start"){if((gr=C.toolContext)!=null&&gr.toolId)continue;let _=C.partId;if(_!==void 0&&w.current!==null&&_!==w.current){let E=m;E&&(E.streaming=!1,f(E),re=E,m=null,S=!0)}_!==void 0&&(w.current=_)}else if(Ke==="text_end"){if((yt=C.toolContext)!=null&&yt.toolId)continue;let _=m;_&&(_.streaming=!1,f(_),re=_,m=null,S=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let _=C.stepType,E=C.executionType;if(_==="tool"||E==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Oe=String((Qt=(Xt=C.id)!=null?Xt:Y.stepId)!=null?Qt:`step-${l()}`),ct=C.partId!==void 0&&C.partId!==null?String(C.partId):"",Ge=`${Y.toolId}::${Oe}`,Xe=I.get(Ge);if(ct!==""&&Xe!==void 0&&Xe!==""&&Xe!==ct){let Lt=L.get(F(Y.toolId,Oe,Xe));Lt&&Lt.streaming!==!1&&(Lt.streaming=!1,f(Lt))}ct!==""&&I.set(Ge,ct);let et=W(Y.toolId,Oe,ct,Y.executionId),Yt=(fr=(rr=(Kr=(Un=C.text)!=null?Un:C.delta)!=null?Kr:C.content)!=null?rr:C.chunk)!=null?fr:"";Yt&&(et.content+=String(Yt),et.streaming=!0,f(et)),C.isComplete&&(et.streaming=!1,f(et));continue}let ae=C.partId;if(ae!==void 0&&w.current!==null&&ae!==w.current){let Oe=m;Oe&&(Oe.streaming=!1,f(Oe),re=Oe,m=null,S=!0)}ae!==void 0&&(w.current=ae);let J=ae!==void 0&&(qn=ue.get(ae))!=null?qn:ve();ae!==void 0&&(J.partId||(J.partId=ae),ue.set(ae,J));let Me=(zn=(be=(or=($=C.text)!=null?$:C.delta)!=null?or:C.content)!=null?be:C.chunk)!=null?zn:"";if(Me){let Oe=typeof C.seq=="number"?C.seq:void 0,ct=ae!=null?ae:J.id,Ge=Oe!==void 0?Ye(ct,Oe,String(Me)):((sr=le.get(J.id))!=null?sr:"")+Me;J.rawContent=Ge,te.has(J.id)||te.set(J.id,this.createStreamParser());let Xe=te.get(J.id),et=Ge.trim().startsWith("{")||Ge.trim().startsWith("[");if(et&&le.set(J.id,Ge),Xe.__isPlainTextParser===!0){J.content=Oe!==void 0?Ge:J.content+Me,le.delete(J.id),te.delete(J.id),J.rawContent=void 0,f(J);continue}let Lt=Xe.processChunk(Ge);if(Lt instanceof Promise)Lt.then(Ht=>{var hn;let an=typeof Ht=="string"?Ht:(hn=Ht==null?void 0:Ht.text)!=null?hn:null;if(an!==null&&an.trim()!=="")J.content=an,f(J);else if(!et&&!Ge.trim().startsWith("<")){let fn=m,nn=fn&&fn.id===J.id?fn:J;nn.id===J.id&&(nn.content=Oe!==void 0?Ge:nn.content+Me,le.delete(nn.id),te.delete(nn.id),nn.rawContent=void 0,f(nn))}}).catch(()=>{J.content=Oe!==void 0?Ge:J.content+Me,le.delete(J.id),te.delete(J.id),J.rawContent=void 0,f(J)});else{let Ht=typeof Lt=="string"?Lt:(hr=Lt==null?void 0:Lt.text)!=null?hr:null;Ht!==null&&Ht.trim()!==""?(J.content=Ht,f(J)):!et&&!Ge.trim().startsWith("<")&&(J.content=Oe!==void 0?Ge:J.content+Me,le.delete(J.id),te.delete(J.id),J.rawContent=void 0,f(J))}}if(C.isComplete){let Oe=(br=(ps=C.result)==null?void 0:ps.response)!=null?br:J.content;if(Oe){let ct=le.get(J.id),Ge=ct!=null?ct:Q(Oe);J.rawContent=Ge;let Xe=te.get(J.id),et=null,Yt=!1;if(Xe&&(et=Xe.getExtractedText(),et===null&&(et=Lo(Ge)),et===null)){let Lt=Xe.processChunk(Ge);Lt instanceof Promise?(Yt=!0,Lt.then(Ht=>{var hn;let an=typeof Ht=="string"?Ht:(hn=Ht==null?void 0:Ht.text)!=null?hn:null;if(an!==null){let fn=m;fn&&fn.id===J.id&&(fn.content=an,fn.streaming=!1,te.delete(fn.id),le.delete(fn.id),f(fn))}})):et=typeof Lt=="string"?Lt:(yr=Lt==null?void 0:Lt.text)!=null?yr:null}if(!Yt){et!==null&&et.trim()!==""?J.content=et:le.has(J.id)||(J.content=Q(Oe));let Lt=te.get(J.id);if(Lt){let Ht=(xr=Lt.close)==null?void 0:xr.call(Lt);Ht instanceof Promise&&Ht.catch(()=>{}),te.delete(J.id)}le.delete(J.id),J.streaming=!1,f(J)}}}}else if(Ke==="step_complete"){let _=C.stepType,E=C.executionType;if(_==="tool"||E==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Oe=String((ho=(Hr=C.id)!=null?Hr:Y.stepId)!=null?ho:"");if(Oe){let ct=B(Y.toolId,Oe);for(let[Ge,Xe]of L)Ge.startsWith(ct)&&Xe.streaming!==!1&&(Xe.streaming=!1,f(Xe));I.delete(`${Y.toolId}::${Oe}`)}continue}let ae=C.stopReason;if(S){if(m!==null){let Ge=m;ae&&(Ge.stopReason=ae),te.delete(Ge.id),le.delete(Ge.id),Ge.streaming!==!1&&(Ge.streaming=!1,f(Ge))}let Oe=(aa=C.result)==null?void 0:aa.response,ct=re;ct&&(ae&&(ct.stopReason=ae),Oe!=null?Ie(ct,Oe):(te.delete(ct.id),le.delete(ct.id))),re=null;continue}let J=(us=C.result)==null?void 0:us.response,Me=ve();if(ae&&(Me.stopReason=ae),J!=null){let Oe=te.get(Me.id),ct=!1,Ge=!1;if(Oe){let Xe=Oe.getExtractedText(),et=le.get(Me.id),Yt=et!=null?et:Q(J);if(Me.rawContent=Yt,Xe!==null&&Xe.trim()!=="")Me.content=Xe,ct=!0;else{let Lt=Lo(Yt);if(Lt!==null)Me.content=Lt,ct=!0;else{let Ht=Oe.processChunk(Yt);if(Ht instanceof Promise)Ge=!0,Ht.then(an=>{var fn;let hn=typeof an=="string"?an:(fn=an==null?void 0:an.text)!=null?fn:null;if(hn!==null&&hn.trim()!==""){let nn=m;nn&&nn.id===Me.id&&(nn.content=hn,nn.streaming=!1,te.delete(nn.id),le.delete(nn.id),f(nn))}else{let nn=Oe.getExtractedText(),ir=m;ir&&ir.id===Me.id&&(nn!==null&&nn.trim()!==""?ir.content=nn:le.has(ir.id)||(ir.content=Q(J)),ir.streaming=!1,te.delete(ir.id),le.delete(ir.id),f(ir))}});else{let an=typeof Ht=="string"?Ht:(ia=Ht==null?void 0:Ht.text)!=null?ia:null;if(an!==null&&an.trim()!=="")Me.content=an,ct=!0;else{let hn=Oe.getExtractedText();hn!==null&&hn.trim()!==""&&(Me.content=hn,ct=!0)}}}}}if(!Ge){if(!Me.rawContent){let Xe=le.get(Me.id);Me.rawContent=Xe!=null?Xe:Q(J)}if(!ct&&!le.has(Me.id)&&(Me.content=Q(J)),Oe){let Xe=(No=Oe.close)==null?void 0:No.call(Oe);Xe instanceof Promise&&Xe.catch(()=>{})}te.delete(Me.id),le.delete(Me.id),Me.streaming=!1,f(Me)}}else te.delete(Me.id),le.delete(Me.id),Me.streaming=!1,f(Me)}else if(Ke==="flow_complete"){let _=(bt=C.result)==null?void 0:bt.response;if(S){if(m!==null){let E=m;te.delete(E.id),le.delete(E.id),E.streaming!==!1&&(E.streaming=!1,f(E))}}else if(_!=null){let E=ve(),Y=le.get(E.id),ae=Y!=null?Y:Q(_);E.rawContent=ae;let J=Q(_),Me=te.get(E.id);if(Me){let Ge=Lo(ae);if(Ge!==null)J=Ge;else{let Xe=Me.processChunk(ae);Xe instanceof Promise&&Xe.then(Yt=>{var Ht;let Lt=typeof Yt=="string"?Yt:(Ht=Yt==null?void 0:Yt.text)!=null?Ht:null;Lt!==null&&(E.content=Lt,E.streaming=!1,f(E))});let et=Me.getExtractedText();et!==null&&(J=et)}}te.delete(E.id),le.delete(E.id);let Oe=J!==E.content,ct=E.streaming!==!1;Oe&&(E.content=J),E.streaming=!1,(Oe||ct)&&f(E)}else if(m!==null){let E=m;te.delete(E.id),le.delete(E.id),E.streaming!==!1&&(E.streaming=!1,f(E))}n({type:"status",status:"idle"})}else if(Ke==="agent_start")de={executionId:C.executionId,agentId:(ms=C.agentId)!=null?ms:"virtual",agentName:(ar=C.agentName)!=null?ar:"",status:"running",currentIteration:0,maxTurns:(In=C.maxTurns)!=null?In:1,startedAt:qe(C.startedAt)};else if(Ke==="agent_iteration_start"){if(de&&(de.currentIteration=C.iteration),jt==="separate"&&C.iteration>1){let _=m;_&&(_.streaming=!1,f(_),Ln.set(C.iteration-1,_),m=null)}}else if(Ke==="agent_turn_start")v=null;else if(Ke==="agent_turn_delta"){if(C.contentType==="text"){let _=ve();_.content+=(la=C.delta)!=null?la:"",_.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:de==null?void 0:de.agentName},v=_,f(_)}else if(C.contentType==="thinking"){let _=(ca=C.turnId)!=null?ca:`agent-think-${C.iteration}`,E=He(_);E.reasoning=(Oo=E.reasoning)!=null?Oo:{id:_,status:"streaming",chunks:[]},E.reasoning.chunks.push((Br=C.delta)!=null?Br:""),E.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},f(E)}else if(C.contentType==="tool_input"){let _=(da=C.toolCallId)!=null?da:P.lastId;if(_){let E=M.get(_);E!=null&&E.toolCall&&(E.toolCall.chunks=(bo=E.toolCall.chunks)!=null?bo:[],E.toolCall.chunks.push((gs=C.delta)!=null?gs:""),f(E))}}}else if(Ke==="agent_turn_complete"){let _=C.turnId;if(_){let ae=H.get(_);if(ae!=null&&ae.reasoning){ae.reasoning.status="complete",ae.reasoning.completedAt=qe(C.completedAt);let J=(Dr=ae.reasoning.startedAt)!=null?Dr:Date.now();ae.reasoning.durationMs=Math.max(0,((fs=ae.reasoning.completedAt)!=null?fs:Date.now())-J),ae.streaming=!1,f(ae)}}let E=C.stopReason,Y=m!=null?m:v;if(E&&Y!==null){let ae=C.turnId;(!ae||((Jr=Y.agentMetadata)==null?void 0:Jr.turnId)===ae)&&(Y.stopReason=E,f(Y))}}else if(Ke==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let _=(Gr=C.toolCallId)!=null?Gr:`agent-tool-${l()}`;Le(oe(C),_);let E=Ae(_),Y=(pa=E.toolCall)!=null?pa:{id:_,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(Si=(ua=C.toolName)!=null?ua:C.name)!=null?Si:Y.name,Y.status="running",C.parameters!==void 0&&(Y.args=C.parameters),Y.startedAt=qe((yo=C.startedAt)!=null?yo:C.timestamp),E.toolCall=Y,E.streaming=!0,E.agentMetadata={executionId:C.executionId,iteration:C.iteration},f(E)}else if(Ke==="agent_tool_delta"){let _=(Xr=C.toolCallId)!=null?Xr:P.lastId;if(_){let E=(ma=M.get(_))!=null?ma:Ae(_);E.toolCall&&(E.toolCall.chunks=(hs=E.toolCall.chunks)!=null?hs:[],E.toolCall.chunks.push((Qr=C.delta)!=null?Qr:""),E.toolCall.status="running",E.streaming=!0,f(E))}}else if(Ke==="agent_tool_complete"){let _=(ga=C.toolCallId)!=null?ga:P.lastId;if(_){let E=(bs=M.get(_))!=null?bs:Ae(_);if(E.toolCall){E.toolCall.status="complete",C.result!==void 0&&(E.toolCall.result=C.result),typeof C.executionTime=="number"&&(E.toolCall.durationMs=C.executionTime),E.toolCall.completedAt=qe((Yr=C.completedAt)!=null?Yr:C.timestamp),E.streaming=!1,f(E);let Y=oe(C);Y&&P.byCall.delete(Y)}}}else if(Ke==="agent_media"){let _=Array.isArray(C.media)?C.media:[],E=[];for(let Y of _){if(!Y||typeof Y!="object")continue;let ae=Y,J=typeof ae.type=="string"?ae.type:void 0,Me=typeof ae.mediaType=="string"?ae.mediaType.toLowerCase():"",Oe=null,ct="";if(J==="media"){let Ge=typeof ae.data=="string"?ae.data:void 0;if(!Ge)continue;ct=Me.length>0?Me:"application/octet-stream",Oe=`data:${ct};base64,${Ge}`}else if(J==="image-url"){let Ge=typeof ae.url=="string"?ae.url:void 0;if(!Ge)continue;ct=Me,Oe=Ge}else if(J==="file-url"){let Ge=typeof ae.url=="string"?ae.url:void 0;if(!Ge)continue;ct=Me,Oe=Ge}else continue;if(Oe)if(J==="image-url"||ct.startsWith("image/"))E.push({type:"image",image:Oe,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))E.push({type:"audio",audio:Oe,mimeType:ct});else if(ct.startsWith("video/"))E.push({type:"video",video:Oe,mimeType:ct});else{let Ge=ct||"application/octet-stream";E.push({type:"file",data:Oe,mimeType:Ge,filename:lg(Ge)})}}if(E.length>0){let Y=l(),ae=C.toolCallId,Me={id:`agent-media-${typeof ae=="string"&&ae.length>0?`${ae}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:E,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(Me);let Oe=m;Oe&&(Oe.streaming=!1,f(Oe)),m=null,x.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let _=`agent-reflection-${C.executionId}-${C.iteration}`,E={id:_,role:"assistant",content:(ys=C.reflection)!=null?ys:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"complete",chunks:[(fa=C.reflection)!=null?fa:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(E)}else if(Ke==="agent_complete"){de&&(de.status=C.success?"complete":"error",de.completedAt=qe(C.completedAt),de.stopReason=C.stopReason);let _=m;_&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"})}else if(Ke==="agent_error"){let _=typeof C.error=="string"?C.error:(ha=(Nr=C.error)==null?void 0:Nr.message)!=null?ha:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",_):n({type:"error",error:new Error(_)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let _=(Zr=C.approvalId)!=null?Zr:`approval-${l()}`,E={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:"pending",agentId:(Dt=de==null?void 0:de.agentId)!=null?Dt:"virtual",executionId:($o=(Fo=C.executionId)!=null?Fo:de==null?void 0:de.executionId)!=null?$o:"",toolName:(xs=C.toolName)!=null?xs:"",toolType:C.toolType,description:(ba=C.description)!=null?ba:`Execute ${(Mr=C.toolName)!=null?Mr:"tool"}`,parameters:C.parameters}};f(E)}else if(Ke==="step_await"&&C.awaitReason==="approval_required"){let _=(vs=C.approvalId)!=null?vs:`approval-${l()}`,E={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:"pending",agentId:(ws=de==null?void 0:de.agentId)!=null?ws:"virtual",executionId:(_o=(ya=C.executionId)!=null?ya:de==null?void 0:de.executionId)!=null?_o:"",toolName:(jo=C.toolName)!=null?jo:"",toolType:C.toolType,description:(xa=C.description)!=null?xa:`Execute ${(xo=C.toolName)!=null?xo:"tool"}`,parameters:C.parameters}};f(E)}else if(Ke==="agent_approval_complete"){let _=C.approvalId;if(_){let Y={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:(va=C.decision)!=null?va:"approved",agentId:(Cs=de==null?void 0:de.agentId)!=null?Cs:"virtual",executionId:(Ss=(As=C.executionId)!=null?As:de==null?void 0:de.executionId)!=null?Ss:"",toolName:(Ts=C.toolName)!=null?Ts:"",description:(Tn=C.description)!=null?Tn:"",resolvedAt:Date.now()}};f(Y)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let _=C.artifactType,E=String(C.id),Y=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:E,artifactType:_,title:Y,component:typeof C.component=="string"?C.component:void 0}),ce.set(E,{markdown:"",title:Y}),!z.has(E)){z.add(E);let ae={id:`artifact-ref-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:E,title:Y,artifactType:_,status:"streaming"}})};pe.set(E,ae),f(ae)}}else if(Ke==="artifact_delta"){let _=String(C.id),E=typeof C.delta=="string"?C.delta:String((Vn=C.delta)!=null?Vn:"");n({type:"artifact_delta",id:_,artDelta:E});let Y=ce.get(_);Y&&(Y.markdown+=E)}else if(Ke==="artifact_update"){let _=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:_,component:typeof C.component=="string"?C.component:void 0})}else if(Ke==="artifact_complete"){let _=String(C.id);n({type:"artifact_complete",id:_});let E=pe.get(_);if(E){E.streaming=!1;try{let Y=JSON.parse((Or=E.rawContent)!=null?Or:"{}");if(Y.props){Y.props.status="complete";let ae=ce.get(_);ae!=null&&ae.markdown&&(Y.props.markdown=ae.markdown)}E.rawContent=JSON.stringify(Y)}catch{}ce.delete(_),f(E),pe.delete(_)}}}else if(Ke==="transcript_insert"){let _=C.message;if(!_||typeof _!="object")continue;let E=String((lt=_.id)!=null?lt:`msg-${l()}`),Y=_.role,J={id:E,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof _.content=="string"?_.content:"",rawContent:typeof _.rawContent=="string"?_.rawContent:void 0,createdAt:typeof _.createdAt=="string"?_.createdAt:new Date().toISOString(),streaming:_.streaming===!0,...typeof _.variant=="string"?{variant:_.variant}:{},sequence:l()};if(f(J),J.rawContent)try{let Me=JSON.parse(J.rawContent),Oe=(Es=Me==null?void 0:Me.props)==null?void 0:Es.artifactId;typeof Oe=="string"&&z.add(Oe)}catch{}m=null,x.current=null,te.delete(E),le.delete(E)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let _=null;if(C.error instanceof Error)_=C.error;else if(Ke==="dispatch_error"){let E=(vo=C.message)!=null?vo:C.error;E!=null&&E!==""&&(_=new Error(String(E)))}else if(Ke==="step_error"||Ke==="flow_error"){let E=C.error;typeof E=="string"&&E!==""?_=new Error(E):E!=null&&typeof E=="object"&&"message"in E&&(_=new Error(String((vr=E.message)!=null?vr:E)))}else Ke==="error"&&C.error!=null&&C.error!==""&&(_=new Error(String(C.error)));if(_){n({type:"error",error:_});let E=m;E&&E.streaming&&(E.streaming=!1,f(E)),n({type:"status",status:"idle"})}}}}}ge.length=0};;){let{done:O,value:Te}=await s.read();if(O)break;a+=o.decode(Te,{stream:!0});let Be=a.split(`
10
10
 
11
- `);a=(Hn=Be.pop())!=null?Hn:"";for(let De of Be){let _e=De.split(`
12
- `),dt="message",rt="";for(let q of _e)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(rt+=q.replace("data:","").trim());if(!rt)continue;let At;try{At=JSON.parse(rt)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let _t=dt!=="message"?dt:(Xn=At.type)!=null?Xn:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,_t,At),this.parseSSEEvent){x.current=u;let q=await this.handleCustomSSEEvent(At,n,x,g,l,C);if(x.current&&x.current!==u&&(u=x.current),q)continue}de.push(_t,At),$e()}}de.flushPending(),$e(),de.destroy()}};function eg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ls(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function zo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Pa="[Image]";function tg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ng(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function rg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function og(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ia(e){return{type:"text",text:e}}function sg(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function ag(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function ig(e,t=["image/png","image/jpeg","image/gif","image/webp"],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. Accepted types: ${t.join(", ")}`}}var Hp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],lg=["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"],Nr=[...Hp,...lg];function cg(e){return Hp.includes(e)||e.startsWith("image/")}function Wa(e){return cg(e.type)}async function Bp(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Wa(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Dp(e,t=Nr,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 dg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Np(e,t){let n=dg(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 Ra=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ha=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ha;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let v=!1,x=T=>{v||(v=!0,clearTimeout(C),u(new Error(T)))},C=setTimeout(()=>x("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(C),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!v){let H=T.code!==1006?` (code ${T.code})`:"";x("WebSocket connection failed"+H+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ra(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var To=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!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}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 Vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ps(e.runtype);case"browser":if(!To.isSupported())throw new Error("Browser speech recognition not supported");return new To(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Li(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Vo({type:"runtype",runtype:e.runtype});if(To.isSupported())return Vo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ba(e){try{return Li(e),!0}catch{return!1}}function Fp(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 r="Sorry \u2014 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?`${r}
11
+ `);a=(Hn=Be.pop())!=null?Hn:"";for(let De of Be){let $e=De.split(`
12
+ `),ut="message",st="";for(let q of $e)q.startsWith("event:")?ut=q.replace("event:","").trim():q.startsWith("data:")&&(st+=q.replace("data:","").trim());if(!st)continue;let Pt;try{Pt=JSON.parse(st)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let zt=ut!=="message"?ut:(Yn=Pt.type)!=null?Yn:"message";if((je=this.onSSEEvent)==null||je.call(this,zt,Pt),this.parseSSEEvent){x.current=m;let q=await this.handleCustomSSEEvent(Pt,n,x,f,l,w);if(x.current&&x.current!==m&&(m=x.current),q)continue}fe.push(zt,Pt),Fe()}}fe.flushPending(),Fe(),fe.destroy()}};function pg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Bs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Qo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ia="[Image]";function ug(e){return typeof e=="string"?[{type:"text",text:e}]:e}function mg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function gg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function fg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Wa(e){return{type:"text",text:e}}function hg(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function bg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function yg(e,t=["image/png","image/jpeg","image/gif","image/webp"],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. Accepted types: ${t.join(", ")}`}}var $p=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],xg=["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"],$r=[...$p,...xg];function vg(e){return $p.includes(e)||e.startsWith("image/")}function Ra(e){return vg(e.type)}async function _p(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ra(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function jp(e,t=$r,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 wg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Up(e,t){let n=wg(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 Ha=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ba=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ds=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ba;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,x=S=>{v||(v=!0,clearTimeout(w),m(new Error(S)))},w=setTimeout(()=>x("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(w),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!v){let H=S.code!==1006?` (code ${S.code})`:"";x("WebSocket connection failed"+H+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ha(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Po=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!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}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 Yo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ds(e.runtype);case"browser":if(!Po.isSupported())throw new Error("Browser speech recognition not supported");return new Po(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bi(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Yo({type:"runtype",runtype:e.runtype});if(Po.isSupported())return Yo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Da(e){try{return Bi(e),!0}catch{return!1}}function qp(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 r="Sorry \u2014 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?`${r}
13
13
 
14
- _Details: ${n.message}_`:r}var Is=class e{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.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.handleEvent=t=>{var n,r,s,o,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Aa(p.name)&&this.enqueueWebMcpAwait(t.message),(r=t.message.agentMetadata)!=null&&r.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:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new qo(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])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)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ba((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,s;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Vo(o);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,g,u,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let C=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:v.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(){var n,r,s,o,a,i,d,l,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((s=t.runtype)==null?void 0:s.clientToken)||"",host:(o=t.runtype)==null?void 0:o.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),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(){var t;return(t=this.clientSession)!=null?t: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){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new qo(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=t,u={id:a!=null?a:n==="user"?Ls():n==="assistant"?zo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}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 r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:s==="user"?Ls():s==="assistant"?zo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,l={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,m,g,u;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=Ls(),o=zo(),a={id:s,role:"user",content:r||Pa,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let C=Fp(v,this.config.errorMessage);if(C){let T={id:o,role:"assistant",createdAt:new Date().toISOString(),content:C,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=zo();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Fp(l,this.config.errorMessage);if(m){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n){var d,l,p,m;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let u=null;if(g instanceof Response){if(!g.ok){let v=await g.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${g.status}`)}u=g.body}else g instanceof ReadableStream&&(u=g);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(g){let u=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,g,u,v,x,C,T,H,L,P,W;let r=this.messages.find(w=>w.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(g=t.toolCall)==null?void 0:g.name;if(!s||!o){(v=(u=this.callbacks).onError)==null||v.call(u,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 w=(x=t.toolCall)==null?void 0:x.args,I=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(I.length===1){let O=typeof((C=I[0])==null?void 0:C.question)=="string"?I[0].question:"";O&&(a={[O]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(H=t.toolCall)==null?void 0:H.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof n=="string"?n:Object.entries(n).map(([I,O])=>`${I}: ${Array.isArray(O)?O.join(", "):O}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((I,O)=>{let $=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!$)return;let B=w[$],j=Array.isArray(B)?B.join(", "):typeof B=="string"?B:"";this.appendMessage({id:`ask-user-q-${i}-${O}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${O}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:n});if(!w.ok){let I=await w.json().catch(()=>null);throw new Error((L=I==null?void 0:I.error)!=null?L:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let I=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(W=(P=this.callbacks).onError)==null||W.call(P,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.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:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{var H,L,P,W,w,I,O;let m=(H=p.toolCall)==null?void 0:H.name,g=(L=p.toolCall)==null?void 0:L.id;if(!m||!g)return null;let u=`${t}:${g}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u))return null;this.webMcpInflightKeys.add(u),r.push(u),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let v=new AbortController;this.webMcpResolveControllers.add(v),s.push(v);let x=(W=(P=p.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?W:m,C=this.client.executeWebMcpToolCall(m,(w=p.toolCall)==null?void 0:w.args,v.signal),T;if(!C)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await C}catch($){return $ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"))||(O=(I=this.callbacks).onError)==null||O.call(I,$ instanceof Error?$:new Error(String($))),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:x,output:T}}));try{let p=a.filter(u=>u!==null);if(p.length===0)return;let m={};for(let u of p)m[u.resumeKey]=u.output;let g=await this.client.resumeFlow(t,m,{signal:o.signal});if(!g.ok){let u=await g.json().catch(()=>null);throw new Error((i=u==null?void 0:u.error)!=null?i:`Resume failed: ${g.status}`)}for(let u of p)this.webMcpResolvedKeys.add(u.dedupeKey);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of r)this.webMcpInflightKeys.delete(p);for(let p of s)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,m,g,u,v,x,C,T,H,L,P,W;let n=(p=t.agentMetadata)==null?void 0:p.executionId,r=(m=t.toolCall)==null?void 0:m.name,s=(g=t.toolCall)==null?void 0:g.id;if(!n){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let w=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(w)}catch(I){(C=(x=this.callbacks).onError)==null||C.call(x,I instanceof Error?I:new Error(String(I)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(T=t.toolCall)==null?void 0:T.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let w;if(l?w=await l:w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let I=(L=(H=t.agentMetadata)==null?void 0:H.webMcpToolCallId)!=null?L:r;await this.resumeWithToolOutput(n,I,w,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(w){w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"))||(W=(P=this.callbacks).onError)==null||W.call(P,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.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(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,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){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;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:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}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!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t),o=r.getVoices();if(n.voice){let a=o.find(i=>i.name===n.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=n.pickVoice?n.pickVoice(o):e.pickBestVoice(o));n.rate!==void 0&&(s.rate=n.rate),n.pitch!==void 0&&(s.pitch=n.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(t){var r;let n=["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 s of n){let o=t.find(a=>a.name===s);if(o)return o}return(r=t.find(s=>s.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"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),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,g,u,v,x;if(o!==r)return s;let a={...s,...n};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=n.toolCall)==null?void 0:m.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&Aa(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let C=`${d}:${l}`;(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}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,r)=>{var d,l;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Sr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import{Activity as pg,ArrowDown as ug,ArrowUp as mg,ArrowUpRight as gg,Bot as fg,ChevronDown as hg,ChevronUp as yg,ChevronRight as bg,ChevronLeft as xg,Check as vg,Clipboard as wg,ClipboardCopy as Cg,Copy as Ag,File as Sg,FileCode as Tg,FileSpreadsheet as Eg,FileText as Mg,ImagePlus as kg,Loader as Lg,LoaderCircle as Pg,Mic as Ig,Paperclip as Wg,RefreshCw as Rg,Search as Hg,Send as Bg,ShieldAlert as Dg,ShieldCheck as Ng,ShieldX as Fg,Square as Og,ThumbsDown as $g,ThumbsUp as _g,Upload as jg,Volume2 as Ug,X as qg,User as zg,Mail as Vg,Phone as Kg,Calendar as Jg,Clock as Gg,Building as Xg,MapPin as Qg,Lock as Yg,Key as Zg,CreditCard as ef,AtSign as tf,Hash as nf,Globe as rf,Link as of,CircleCheck as sf,CircleX as af,TriangleAlert as lf,Info as cf,Ban as df,Shield as pf,ArrowLeft as uf,ArrowRight as mf,ExternalLink as gf,Ellipsis as ff,EllipsisVertical as hf,Menu as yf,House as bf,Plus as xf,Minus as vf,Pencil as wf,Trash as Cf,Trash2 as Af,Save as Sf,Download as Tf,Share as Ef,Funnel as Mf,Settings as kf,RotateCw as Lf,Maximize as Pf,Minimize as If,ShoppingCart as Wf,ShoppingBag as Rf,Package as Hf,Truck as Bf,Tag as Df,Gift as Nf,Receipt as Ff,Wallet as Of,Store as $f,DollarSign as _f,Percent as jf,Play as Uf,Pause as qf,VolumeX as zf,Camera as Vf,Image as Kf,Film as Jf,Headphones as Gf,MessageCircle as Xf,MessageSquare as Qf,Bell as Yf,Heart as Zf,Star as eh,Eye as th,EyeOff as nh,Bookmark as rh,CalendarDays as oh,History as sh,Timer as ah,Folder as ih,FolderOpen as lh,Files as ch,Sparkles as dh,Zap as ph,Sun as uh,Moon as mh,Flag as gh,Monitor as fh,Smartphone as hh}from"lucide";var yh={activity:pg,"arrow-down":ug,"arrow-up":mg,"arrow-up-right":gg,bot:fg,"chevron-down":hg,"chevron-up":yg,"chevron-right":bg,"chevron-left":xg,check:vg,clipboard:wg,"clipboard-copy":Cg,copy:Ag,file:Sg,"file-code":Tg,"file-spreadsheet":Eg,"file-text":Mg,"image-plus":kg,loader:Lg,"loader-circle":Pg,mic:Ig,paperclip:Wg,"refresh-cw":Rg,search:Hg,send:Bg,"shield-alert":Dg,"shield-check":Ng,"shield-x":Fg,square:Og,"thumbs-down":$g,"thumbs-up":_g,upload:jg,"volume-2":Ug,x:qg,user:zg,mail:Vg,phone:Kg,calendar:Jg,clock:Gg,building:Xg,"map-pin":Qg,lock:Yg,key:Zg,"credit-card":ef,"at-sign":tf,hash:nf,globe:rf,link:of,"circle-check":sf,"circle-x":af,"triangle-alert":lf,info:cf,ban:df,shield:pf,"arrow-left":uf,"arrow-right":mf,"external-link":gf,ellipsis:ff,"ellipsis-vertical":hf,menu:yf,house:bf,plus:xf,minus:vf,pencil:wf,trash:Cf,"trash-2":Af,save:Sf,download:Tf,share:Ef,funnel:Mf,settings:kf,"rotate-cw":Lf,maximize:Pf,minimize:If,"shopping-cart":Wf,"shopping-bag":Rf,package:Hf,truck:Bf,tag:Df,gift:Nf,receipt:Ff,wallet:Of,store:$f,"dollar-sign":_f,percent:jf,play:Uf,pause:qf,"volume-x":zf,camera:Vf,image:Kf,film:Jf,headphones:Gf,"message-circle":Xf,"message-square":Qf,bell:Yf,heart:Zf,star:eh,eye:th,"eye-off":nh,bookmark:rh,"calendar-days":oh,history:sh,timer:ah,folder:ih,"folder-open":lh,files:ch,sparkles:dh,zap:ph,sun:uh,moon:mh,flag:gh,monitor:fh,smartphone:hh},be=(e,t=24,n="currentColor",r=2)=>{let s=yh[e];return s?bh(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function bh(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var Da={allowedTypes:Nr,maxFileSize:10*1024*1024,maxFiles:4};function xh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vh(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 Ko=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Da.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Da.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Da.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:Da.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){var n,r,s,o,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=Dp(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,m);continue}try{let m=await Bp(l),g=Wa(l)?URL.createObjectURL(l):null,u={id:xh(),file:l,previewUrl:g,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Wa(t.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.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",r.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 i=vh(t.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Np(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=be("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Op=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ws(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];Op(o)&&Op(s)?n[r]=Ws(o,s):n[r]=s}return n}var sr="min(440px, calc(100vw - 24px))",Pi="440px",Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{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:sr,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)"},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:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,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 $p(e,t){if(!(!e&&!t))return e?t?Ws(e,t):e:t}function Ii(e){var t,n,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,L,P,W;return e?{...Ft,...e,theme:$p(Ft.theme,e.theme),darkTheme:$p(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(t=Ft.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var ye,Le,He,ee,Pe,V,le,ve;let w=(ye=Ft.features)==null?void 0:ye.artifacts,I=(Le=e.features)==null?void 0:Le.artifacts,O=(He=Ft.features)==null?void 0:He.scrollToBottom,$=(ee=e.features)==null?void 0:ee.scrollToBottom,B=(Pe=Ft.features)==null?void 0:Pe.streamAnimation,j=(V=e.features)==null?void 0:V.streamAnimation,z=(le=Ft.features)==null?void 0:le.askUserQuestion,oe=(ve=e.features)==null?void 0:ve.askUserQuestion,We=w===void 0&&I===void 0?void 0:{...w,...I,layout:{...w==null?void 0:w.layout,...I==null?void 0:I.layout}},je=O===void 0&&$===void 0?void 0:{...O,...$},Ne=B===void 0&&j===void 0?void 0:{...B,...j},ge=z===void 0&&oe===void 0?void 0:{...z,...oe,styles:{...z==null?void 0:z.styles,...oe==null?void 0:oe.styles}};return{...Ft.features,...e.features,...je!==void 0?{scrollToBottom:je}:{},...We!==void 0?{artifacts:We}:{},...Ne!==void 0?{streamAnimation:Ne}:{},...ge!==void 0?{askUserQuestion:ge}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=Ft.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(g=e.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Ft.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(C=e.layout)==null?void 0:C.messages)==null?void 0:T.timestamp}},slots:{...(H=Ft.layout)==null?void 0:H.slots,...(L=e.layout)==null?void 0:L.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(P=Ft.markdown)==null?void 0:P.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}var _p={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"}},jp={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"}},Up={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"}},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:sr,maxWidth:Pi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},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:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"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:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",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 Jo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Jo(e,r):r}function Wi(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Jo(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function qp(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 zp(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=zp(o,s):n[r]=s}return n}function wh(e,t){return t?zp(e,t):e}function Rs(e,t={}){var s,o,a,i,d,l,p,m,g,u,v,x,C;let n={palette:_p,semantic:jp,components:Up},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:wh(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=qp(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(H=>H.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function Ri(e){var x,C,T,H,L,P,W,w,I,O,$,B,j,z,oe,We,je,Ne,ge,ye,Le,He,ee,Pe,V,le,ve,fe,we,ze,Q,te,se,ue,ie,re,Qe,Ie,ce,G,$e,Et,de,ae,Mn,Ot,ln,Hn,Xn,Ue,N,Ae,Be,De,_e,dt,rt,At,_t,q,$t,Ye,Dt,ne,me,vt,jt,Zt,hn,St,wt,ft,yt,zt,tt,Bn,Qn,yn,Dn,ut,xr,Nn,po,kn,Io,Or,Er,bt,Fn,On,bn,Lt,Yn,Zn,$n,$r,Mr,_r,_n,Wt,xn,er,jr,kr,Ur,vr,jn,lr,gt,Jt,Gt,Un,qr,tr,cr,qn;let t=Wi(e),n={};for(let[S,zn]of Object.entries(t)){let dr=S.replace(/\./g,"-");n[`--persona-${dr}`]=zn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(C=n["--persona-semantic-colors-secondary"])!=null?C:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(H=n["--persona-semantic-colors-surface"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(L=n["--persona-semantic-colors-background"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(P=n["--persona-semantic-colors-container"])!=null?P:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(w=n["--persona-semantic-colors-text-muted"])!=null?w:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(O=n["--persona-semantic-colors-border"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=($=n["--persona-semantic-colors-divider"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(B=n["--persona-components-voice-recording-indicator"])!=null?B:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(oe=n["--persona-components-voice-speaking-icon"])!=null?oe:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(We=n["--persona-components-approval-requested-background"])!=null?We:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(je=n["--persona-components-approval-requested-border"])!=null?je:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ne=n["--persona-components-approval-requested-text"])!=null?Ne:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ge=n["--persona-components-approval-approve-background"])!=null?ge:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(ye=n["--persona-components-approval-deny-background"])!=null?ye:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Le=n["--persona-components-attachment-image-background"])!=null?Le:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(He=n["--persona-components-attachment-image-border"])!=null?He:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ee=n["--persona-semantic-typography-fontFamily"])!=null?ee:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Pe=n["--persona-semantic-typography-fontSize"])!=null?Pe:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(V=n["--persona-semantic-typography-fontWeight"])!=null?V:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(le=n["--persona-semantic-typography-lineHeight"])!=null?le: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"]=(ve=n["--persona-palette-radius-sm"])!=null?ve:"0.125rem",n["--persona-radius-md"]=(fe=n["--persona-palette-radius-md"])!=null?fe:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(ze=n["--persona-palette-radius-xl"])!=null?ze:"0.75rem",n["--persona-radius-full"]=(Q=n["--persona-palette-radius-full"])!=null?Q:"9999px",n["--persona-launcher-radius"]=(se=(te=n["--persona-components-launcher-borderRadius"])!=null?te:n["--persona-palette-radius-full"])!=null?se:"9999px",n["--persona-launcher-bg"]=(ue=n["--persona-components-launcher-background"])!=null?ue:n["--persona-primary"],n["--persona-launcher-fg"]=(ie=n["--persona-components-launcher-foreground"])!=null?ie:n["--persona-text-inverse"],n["--persona-launcher-border"]=(re=n["--persona-components-launcher-border"])!=null?re:n["--persona-border"],n["--persona-button-primary-bg"]=(Qe=n["--persona-components-button-primary-background"])!=null?Qe:n["--persona-primary"],n["--persona-button-primary-fg"]=(Ie=n["--persona-components-button-primary-foreground"])!=null?Ie:n["--persona-text-inverse"],n["--persona-button-radius"]=(G=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?G:"9999px",n["--persona-panel-radius"]=(Et=($e=n["--persona-components-panel-borderRadius"])!=null?$e:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(de=n["--persona-components-panel-border"])!=null?de:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Mn=(ae=n["--persona-components-panel-shadow"])!=null?ae:n["--persona-palette-shadows-xl"])!=null?Mn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Ot=n["--persona-components-input-borderRadius"])!=null?Ot:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Xn=(Hn=n["--persona-components-message-user-borderRadius"])!=null?Hn:n["--persona-radius-lg"])!=null?Xn:"0.5rem",n["--persona-message-assistant-radius"]=(N=(Ue=n["--persona-components-message-assistant-borderRadius"])!=null?Ue:n["--persona-radius-lg"])!=null?N:"0.5rem",n["--persona-header-bg"]=(Ae=n["--persona-components-header-background"])!=null?Ae:n["--persona-surface"],n["--persona-header-border"]=(Be=n["--persona-components-header-border"])!=null?Be:n["--persona-divider"],n["--persona-header-icon-bg"]=(De=n["--persona-components-header-iconBackground"])!=null?De:n["--persona-primary"],n["--persona-header-icon-fg"]=(_e=n["--persona-components-header-iconForeground"])!=null?_e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(dt=n["--persona-components-header-titleForeground"])!=null?dt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(rt=n["--persona-components-header-subtitleForeground"])!=null?rt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(At=n["--persona-components-header-actionIconForeground"])!=null?At:n["--persona-muted"];let r=(_t=e.components)==null?void 0:_t.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=($t=n["--persona-components-introCard-background"])!=null?$t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ye=n["--persona-components-introCard-borderRadius"])!=null?Ye:"1rem",n["--persona-intro-card-padding"]=(Dt=n["--persona-components-introCard-padding"])!=null?Dt:"1.5rem",n["--persona-intro-card-shadow"]=(me=(ne=s==null?void 0:s.shadow)!=null?ne:n["--persona-components-introCard-shadow"])!=null?me:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(vt=n["--persona-components-input-background"])!=null?vt:n["--persona-surface"],n["--persona-input-placeholder"]=(jt=n["--persona-components-input-placeholder"])!=null?jt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Zt=n["--persona-components-message-user-background"])!=null?Zt:n["--persona-accent"],n["--persona-message-user-text"]=(hn=n["--persona-components-message-user-text"])!=null?hn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(St=n["--persona-components-message-user-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(wt=n["--persona-components-message-assistant-background"])!=null?wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(ft=n["--persona-components-message-assistant-text"])!=null?ft:n["--persona-text"],n["--persona-message-assistant-border"]=(yt=n["--persona-components-message-assistant-border"])!=null?yt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Bn=(tt=n["--persona-components-scrollToBottom-background"])!=null?tt:n["--persona-button-primary-bg"])!=null?Bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(yn=(Qn=n["--persona-components-scrollToBottom-foreground"])!=null?Qn:n["--persona-button-primary-fg"])!=null?yn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Dn=n["--persona-components-scrollToBottom-border"])!=null?Dn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(po=(Nn=(xr=n["--persona-components-scrollToBottom-borderRadius"])!=null?xr:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?po:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Io=(kn=n["--persona-components-scrollToBottom-shadow"])!=null?kn:n["--persona-palette-shadows-sm"])!=null?Io:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Or=n["--persona-components-scrollToBottom-padding"])!=null?Or:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Er=n["--persona-components-scrollToBottom-gap"])!=null?Er:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Fn=(bt=n["--persona-components-scrollToBottom-fontSize"])!=null?bt:n["--persona-palette-typography-fontSize-sm"])!=null?Fn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(On=n["--persona-components-scrollToBottom-iconSize"])!=null?On:"14px",n["--persona-tool-bubble-shadow"]=(bn=n["--persona-components-toolBubble-shadow"])!=null?bn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Lt=n["--persona-components-reasoningBubble-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Yn=n["--persona-components-composer-shadow"])!=null?Yn:"none",n["--persona-md-inline-code-bg"]=(Zn=n["--persona-components-markdown-inlineCode-background"])!=null?Zn:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Mr=($r=n["--persona-components-markdown-link-foreground"])!=null?$r:n["--persona-accent"])!=null?Mr:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(_r=n["--persona-components-markdown-codeBlock-background"])!=null?_r:n["--persona-container"],n["--persona-md-code-block-border-color"]=(_n=n["--persona-components-markdown-codeBlock-borderColor"])!=null?_n:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(xn=n["--persona-components-markdown-table-headerBackground"])!=null?xn:n["--persona-container"],n["--persona-md-table-border-color"]=(er=n["--persona-components-markdown-table-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-hr-color"]=(jr=n["--persona-components-markdown-hr-color"])!=null?jr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(kr=n["--persona-components-markdown-blockquote-borderColor"])!=null?kr:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Ur=n["--persona-components-markdown-blockquote-background"])!=null?Ur:"transparent",n["--persona-md-blockquote-text-color"]=(vr=n["--persona-components-markdown-blockquote-textColor"])!=null?vr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(jn=n["--persona-components-collapsibleWidget-container"])!=null?jn:n["--persona-surface"],n["--cw-surface"]=(lr=n["--persona-components-collapsibleWidget-surface"])!=null?lr:n["--persona-surface"],n["--cw-border"]=(gt=n["--persona-components-collapsibleWidget-border"])!=null?gt:n["--persona-border"],n["--persona-message-border"]=(Jt=n["--persona-components-message-border"])!=null?Jt:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let S=v.toolbar;S.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=S.iconHoverColor),S.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=S.iconHoverBackground),S.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=S.iconPadding),S.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=S.iconBorderRadius),S.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=S.iconBorder),S.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=S.toggleGroupGap),S.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=S.toggleBorderRadius),S.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=S.copyBackground),S.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=S.copyBorder),S.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=S.copyColor),S.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=S.copyBorderRadius),S.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=S.copyPadding),S.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=S.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:S.copyMenuBackground),S.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=S.copyMenuBorder,n["--persona-dropdown-border"]=(Un=n["--persona-dropdown-border"])!=null?Un:S.copyMenuBorder),S.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=S.copyMenuShadow,n["--persona-dropdown-shadow"]=(qr=n["--persona-dropdown-shadow"])!=null?qr:S.copyMenuShadow),S.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=S.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(tr=n["--persona-dropdown-radius"])!=null?tr:S.copyMenuBorderRadius),S.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=S.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(cr=n["--persona-dropdown-item-hover-bg"])!=null?cr:S.copyMenuItemHoverBackground),S.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=S.iconBackground),S.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=S.toolbarBorder)}if(v!=null&&v.tab){let S=v.tab;S.background&&(n["--persona-artifact-tab-bg"]=S.background),S.activeBackground&&(n["--persona-artifact-tab-active-bg"]=S.activeBackground),S.activeBorder&&(n["--persona-artifact-tab-active-border"]=S.activeBorder),S.borderRadius&&(n["--persona-artifact-tab-radius"]=S.borderRadius),S.textColor&&(n["--persona-artifact-tab-color"]=S.textColor),S.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=S.hoverBackground),S.listBackground&&(n["--persona-artifact-tab-list-bg"]=S.listBackground),S.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=S.listBorderColor),S.listPadding&&(n["--persona-artifact-tab-list-padding"]=S.listPadding)}if(v!=null&&v.pane){let S=v.pane;if(S.toolbarBackground){let zn=(qn=Jo(e,S.toolbarBackground))!=null?qn:S.toolbarBackground;n["--persona-artifact-toolbar-bg"]=zn}}return n}var Ch={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Ah={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"}}},Vp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Na=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Sh=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Na()},Kp=e=>Sh(e),Th=e=>Rs(e),Eh=e=>{var n;let t=Rs(void 0,{validate:!1});return Rs({...e,palette:{...t.palette,colors:{...Ah.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Hs=e=>{let t=Kp(e),n=Vp(e==null?void 0:e.theme),r=Vp(e==null?void 0:e.darkTheme);return t==="dark"?Eh(Ws(n!=null?n:{},r!=null?r:{})):Th(n)},Mh=e=>Ri(e),Eo=(e,t)=>{var o;let n=Hs(t),r=Mh(n);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=t==null?void 0:t.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Hi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Na())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Na());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as kh}from"idiomorph";var Fa=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;kh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Oa={index:-1,draft:""};function Jp(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...Oa}}}function Gp(e,t){var n,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,L,P,W,w,I,O,$,B,j,z,oe,We,je,Ne,ge,ye,Le,He,ee,Pe,V;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(v=(u=e.toolCall)==null?void 0:u.status)!=null?v:"",(C=(x=e.toolCall)==null?void 0:x.name)!=null?C:"",(L=(H=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:H.length)!=null?L:0,(I=(w=(W=(P=e.toolCall)==null?void 0:P.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?I:"",typeof((O=e.toolCall)==null?void 0:O.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(z=(j=(B=e.reasoning)==null?void 0:B.chunks)==null?void 0:j.length)!=null?z:0,(Ne=(je=(We=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:je.length)!=null?Ne:0,(He=(Le=(ye=(ge=e.reasoning)==null?void 0:ge.chunks)==null?void 0:ye[e.reasoning.chunks.length-1])==null?void 0:Le.slice(-32))!=null?He:"",(Pe=(ee=e.contentParts)==null?void 0:ee.length)!=null?Pe:0,(V=e.stopReason)!=null?V:"",t].join("\0")}function Xp(){return new Map}function Qp(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Yp(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Zp(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function $a(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Bs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ds(e,t){return Bs(e)-e.scrollTop<=t}function _a(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function ja(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var gn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},fn=1e5,eo=fn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Lh=["pre","code","a","script","style"],Ua=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ns.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ns.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ns.buffer}},tu=[{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"}],Fs=new Map;for(let e of tu)Fs.set(e.name,e);var Ph=e=>{Fs.set(e.name,e)},Ih=e=>{tu.some(t=>t.name===e)||Fs.delete(e)},Wh=()=>Array.from(Fs.keys()),Os=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Fs.get(e))!=null?r:null},qa=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
15
- `);return o<0?"":e.slice(0,o)}return e},Rh=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},Hh=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},Bi=/\s/,Bh=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Dh=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(Bi.test(o[i])){let l=i;for(;l<o.length&&Bi.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<o.length&&!Bi.test(o[p]);)l.appendChild(Rh(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},Nh=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Hh(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},$s=(e,t,n,r)=>{var m,g;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:Lh).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Bh(d,o)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Dh:Nh;for(let u of i)p(u,n,l);return s.innerHTML},za=(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},_s=(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},eu=new WeakMap,Fh=(e,t)=>{var o;if(!e.styles)return;let n=eu.get(t);if(n||(n=new Set,eu.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},Di=new WeakMap,Oh=(e,t)=>{if(!e.onAttach)return;let n=Di.get(t);if(n||(n=new Map,Di.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},nu=e=>{let t=Di.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ni=(e,t)=>{Fh(e,t),Oh(e,t)};function Fi(e,t=fn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var js=0,to=null;function Oi(e=document){var n;if(js++,js===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;to={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,js=Math.max(0,js-1),js===0&&to)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=to.originalOverflow,s.style.position=to.originalPosition,s.style.top=to.originalTop,s.style.width=to.originalWidth,o.scrollTo(0,to.scrollY),to=null}}}var Va={side:"right",width:"420px",animate:!0,reveal:"resize"},an=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},no=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},yr=e=>{var n,r,s,o,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Va.side,width:(s=t==null?void 0:t.width)!=null?s:Va.width,animate:(o=t==null?void 0:t.animate)!=null?o:Va.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Va.reveal}};var br={"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 Us=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
14
+ _Details: ${n.message}_`:r}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]}),zp=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Os=class e{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.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.handleEvent=t=>{var n,r,s,o,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&ko(p.name)&&this.enqueueWebMcpAwait(t.message),(r=t.message.agentMetadata)!=null&&r.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:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Xo(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])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)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Da((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,s;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Yo(o);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,u,f,m,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let w=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:v.id;w&&this.ttsSpokenMessageIds.add(w)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(){var n,r,s,o,a,i,d,l,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((s=t.runtype)==null?void 0:s.clientToken)||"",host:(o=t.runtype)==null?void 0:o.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),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(){var t;return(t=this.clientSession)!=null?t: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){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Xo(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,m={id:a!=null?a:n==="user"?Bs():n==="assistant"?Qo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(m),m}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 r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:s==="user"?Bs():s==="assistant"?Qo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,l={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,u,f,m;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=Bs(),o=Qo(),a={id:s,role:"user",content:r||Ia,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let w=qp(v,this.config.errorMessage);if(w){let S={id:o,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(S)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=Qo();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=qp(l,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,m,v;let s=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===s),i={id:s,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:o};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let w=null;if(x instanceof Response){if(!x.ok){let S=await x.json().catch(()=>null);throw new Error((f=S==null?void 0:S.error)!=null?f:`Approval request failed: ${x.status}`)}w=x.body}else x instanceof ReadableStream&&(w=x);w?await this.connectStream(w,{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(x){let w=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,m,v,x,w,S,H,M,L,I;let r=this.messages.find(A=>A.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(u=t.agentMetadata)==null?void 0:u.executionId,o=(f=t.toolCall)==null?void 0:f.name;if(!s||!o){(v=(m=this.callbacks).onError)==null||v.call(m,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 A=(x=t.toolCall)==null?void 0:x.args,P=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(P.length===1){let F=typeof((w=P[0])==null?void 0:w.question)=="string"?P[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(t,a),(S=this.abortController)==null||S.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(H=t.toolCall)==null?void 0:H.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let A=typeof n=="string"?n:Object.entries(n).map(([P,F])=>`${P}: ${Array.isArray(F)?F.join(", "):F}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};l.forEach((P,F)=>{let B=typeof(P==null?void 0:P.question)=="string"?P.question:"";if(!B)return;let W=A[B],U=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:B,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(s,{[o]:n});if(!A.ok){let P=await A.json().catch(()=>null);throw new Error((M=P==null?void 0:P.error)!=null?M:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let P=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,P||(I=(L=this.callbacks).onError)==null||I.call(L,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.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:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}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,r,s=Date.now()){this.messages.some(o=>o.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var L,I,A,P,F,B,W;let f=(L=u.toolCall)==null?void 0:L.name,m=(I=u.toolCall)==null?void 0:I.id;if(!f||!m)return null;let v=`${t}:${m}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return null;this.webMcpInflightKeys.add(v),r.push(v);let x=this.markWebMcpToolRunning(u),w=new AbortController;this.webMcpResolveControllers.add(w),s.push(w);let S=(P=(A=u.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?P:f,H=this.client.executeWebMcpToolCall(f,(F=u.toolCall)==null?void 0:F.args,w.signal),M;if(!H)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await H}catch(U){let V=U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")||U.message.includes("abort"));return V||(W=(B=this.callbacks).onError)==null||W.call(B,U instanceof Error?U:new Error(String(U))),this.markWebMcpToolComplete(u,Ns(V?"Aborted by cancel()":zp(U)),x),this.webMcpInflightKeys.delete(v),null}return w.signal.aborted?(this.markWebMcpToolComplete(u,Ns("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:S,output:M,toolMessage:u,startedAt:x,completedAt:Date.now()}})),i=[];try{if(i=a.filter(m=>m!==null),i.length===0)return;let u={};for(let m of i)u[m.resumeKey]=m.output;let f=await this.client.resumeFlow(t,u,{signal:o.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Resume failed: ${f.status}`)}for(let m of i)this.webMcpResolvedKeys.add(m.dedupeKey),this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,u instanceof Error?u:new Error(String(u)));else for(let m of i)this.markWebMcpToolComplete(m.toolMessage,Ns("Aborted by cancel()"),m.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of s)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var m,v,x,w,S,H,M,L,I,A,P,F;let n=(m=t.agentMetadata)==null?void 0:m.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(x=t.toolCall)==null?void 0:x.id;if(!n){(S=(w=this.callbacks).onError)==null||S.call(w,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let B=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(B)||this.webMcpResolvedKeys.has(B))return;this.webMcpInflightKeys.add(B);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(B)}catch(W){(M=(H=this.callbacks).onError)==null||M.call(H,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(B)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(L=t.toolCall)==null?void 0:L.args,p=this.client.executeWebMcpToolCall(r,l,d),u="execute",f=a;try{let B;if(p?B=await p:B={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ns("Aborted by cancel()"),a);return}let W=(A=(I=t.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?A:r;u="resume",await this.resumeWithToolOutput(n,W,B,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,B,a,f)},signal:d})}catch(B){let W=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));(u==="execute"||W||d.aborted)&&this.markWebMcpToolComplete(t,Ns(W||d.aborted?"Aborted by cancel()":zp(B)),a),W||(F=(P=this.callbacks).onError)==null||F.call(P,B instanceof Error?B:new Error(String(B)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.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(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,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){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;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:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}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!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t),o=r.getVoices();if(n.voice){let a=o.find(i=>i.name===n.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=n.pickVoice?n.pickVoice(o):e.pickBestVoice(o));n.rate!==void 0&&(s.rate=n.rate),n.pitch!==void 0&&(s.pitch=n.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(t){var r;let n=["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 s of n){let o=t.find(a=>a.name===s);if(o)return o}return(r=t.find(s=>s.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"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),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,u,f,m,v,x,w,S,H,M;if(o!==r)return s;let a={...s,...n};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(u=n.toolCall)==null?void 0:u.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(m=n.toolCall)==null?void 0:m.id;if(i&&ko(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let L=`${d}:${l}`,I=this.webMcpInflightKeys.has(L),A=this.webMcpResolvedKeys.has(L),P=(x=s.toolCall)==null?void 0:x.name,F=((w=s.agentMetadata)==null?void 0:w.executionId)===d&&((S=s.toolCall)==null?void 0:S.id)===l&&P!==void 0&&ko(P)&&((H=s.toolCall)==null?void 0:H.status)==="complete";(I||A||F)&&(a.agentMetadata={...(M=a.agentMetadata)!=null?M:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.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,r)=>{var d,l;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Lr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import{Activity as Cg,ArrowDown as Ag,ArrowUp as Sg,ArrowUpRight as Tg,Bot as Eg,ChevronDown as Mg,ChevronUp as kg,ChevronRight as Lg,ChevronLeft as Pg,Check as Ig,Clipboard as Wg,ClipboardCopy as Rg,Copy as Hg,File as Bg,FileCode as Dg,FileSpreadsheet as Ng,FileText as Og,ImagePlus as Fg,Loader as $g,LoaderCircle as _g,Mic as jg,Paperclip as Ug,RefreshCw as qg,Search as zg,Send as Vg,ShieldAlert as Kg,ShieldCheck as Jg,ShieldX as Gg,Square as Xg,ThumbsDown as Qg,ThumbsUp as Yg,Upload as Zg,Volume2 as ef,X as tf,User as nf,Mail as rf,Phone as of,Calendar as sf,Clock as af,Building as lf,MapPin as cf,Lock as df,Key as pf,CreditCard as uf,AtSign as mf,Hash as gf,Globe as ff,Link as hf,CircleCheck as bf,CircleX as yf,TriangleAlert as xf,Info as vf,Ban as wf,Shield as Cf,ArrowLeft as Af,ArrowRight as Sf,ExternalLink as Tf,Ellipsis as Ef,EllipsisVertical as Mf,Menu as kf,House as Lf,Plus as Pf,Minus as If,Pencil as Wf,Trash as Rf,Trash2 as Hf,Save as Bf,Download as Df,Share as Nf,Funnel as Of,Settings as Ff,RotateCw as $f,Maximize as _f,Minimize as jf,ShoppingCart as Uf,ShoppingBag as qf,Package as zf,Truck as Vf,Tag as Kf,Gift as Jf,Receipt as Gf,Wallet as Xf,Store as Qf,DollarSign as Yf,Percent as Zf,Play as eh,Pause as th,VolumeX as nh,Camera as rh,Image as oh,Film as sh,Headphones as ah,MessageCircle as ih,MessageSquare as lh,Bell as ch,Heart as dh,Star as ph,Eye as uh,EyeOff as mh,Bookmark as gh,CalendarDays as fh,History as hh,Timer as bh,Folder as yh,FolderOpen as xh,Files as vh,Sparkles as wh,Zap as Ch,Sun as Ah,Moon as Sh,Flag as Th,Monitor as Eh,Smartphone as Mh}from"lucide";var kh={activity:Cg,"arrow-down":Ag,"arrow-up":Sg,"arrow-up-right":Tg,bot:Eg,"chevron-down":Mg,"chevron-up":kg,"chevron-right":Lg,"chevron-left":Pg,check:Ig,clipboard:Wg,"clipboard-copy":Rg,copy:Hg,file:Bg,"file-code":Dg,"file-spreadsheet":Ng,"file-text":Og,"image-plus":Fg,loader:$g,"loader-circle":_g,mic:jg,paperclip:Ug,"refresh-cw":qg,search:zg,send:Vg,"shield-alert":Kg,"shield-check":Jg,"shield-x":Gg,square:Xg,"thumbs-down":Qg,"thumbs-up":Yg,upload:Zg,"volume-2":ef,x:tf,user:nf,mail:rf,phone:of,calendar:sf,clock:af,building:lf,"map-pin":cf,lock:df,key:pf,"credit-card":uf,"at-sign":mf,hash:gf,globe:ff,link:hf,"circle-check":bf,"circle-x":yf,"triangle-alert":xf,info:vf,ban:wf,shield:Cf,"arrow-left":Af,"arrow-right":Sf,"external-link":Tf,ellipsis:Ef,"ellipsis-vertical":Mf,menu:kf,house:Lf,plus:Pf,minus:If,pencil:Wf,trash:Rf,"trash-2":Hf,save:Bf,download:Df,share:Nf,funnel:Of,settings:Ff,"rotate-cw":$f,maximize:_f,minimize:jf,"shopping-cart":Uf,"shopping-bag":qf,package:zf,truck:Vf,tag:Kf,gift:Jf,receipt:Gf,wallet:Xf,store:Qf,"dollar-sign":Yf,percent:Zf,play:eh,pause:th,"volume-x":nh,camera:rh,image:oh,film:sh,headphones:ah,"message-circle":ih,"message-square":lh,bell:ch,heart:dh,star:ph,eye:uh,"eye-off":mh,bookmark:gh,"calendar-days":fh,history:hh,timer:bh,folder:yh,"folder-open":xh,files:vh,sparkles:wh,zap:Ch,sun:Ah,moon:Sh,flag:Th,monitor:Eh,smartphone:Mh},Ce=(e,t=24,n="currentColor",r=2)=>{let s=kh[e];return s?Lh(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Lh(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var Na={allowedTypes:$r,maxFileSize:10*1024*1024,maxFiles:4};function Ph(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ih(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 Zo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Na.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Na.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Na.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:Na.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){var n,r,s,o,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=jp(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,u);continue}try{let u=await _p(l),f=Ra(l)?URL.createObjectURL(l):null,m={id:Ph(),file:l,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ra(t.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.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",r.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 i=Ih(t.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Up(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=Ce("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Vp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];Vp(o)&&Vp(s)?n[r]=Fs(o,s):n[r]=s}return n}var pr="min(440px, calc(100vw - 24px))",Di="440px",_t={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:pr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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)"},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:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,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 Kp(e,t){if(!(!e&&!t))return e?t?Fs(e,t):e:t}function Ni(e){var t,n,r,s,o,a,i,d,l,p,u,f,m,v,x,w,S,H,M,L,I;return e?{..._t,...e,theme:Kp(_t.theme,e.theme),darkTheme:Kp(_t.darkTheme,e.darkTheme),launcher:{..._t.launcher,...e.launcher,dock:{...(t=_t.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=_t.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{..._t.copy,...e.copy},sendButton:{..._t.sendButton,...e.sendButton},statusIndicator:{..._t.statusIndicator,...e.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...e.voiceRecognition},features:(()=>{var he,He,Le,K,pe,z,ce,ie;let A=(he=_t.features)==null?void 0:he.artifacts,P=(He=e.features)==null?void 0:He.artifacts,F=(Le=_t.features)==null?void 0:Le.scrollToBottom,B=(K=e.features)==null?void 0:K.scrollToBottom,W=(pe=_t.features)==null?void 0:pe.streamAnimation,U=(z=e.features)==null?void 0:z.streamAnimation,V=(ce=_t.features)==null?void 0:ce.askUserQuestion,oe=(ie=e.features)==null?void 0:ie.askUserQuestion,We=A===void 0&&P===void 0?void 0:{...A,...P,layout:{...A==null?void 0:A.layout,...P==null?void 0:P.layout}},Je=F===void 0&&B===void 0?void 0:{...F,...B},ve=W===void 0&&U===void 0?void 0:{...W,...U},Re=V===void 0&&oe===void 0?void 0:{...V,...oe,styles:{...V==null?void 0:V.styles,...oe==null?void 0:oe.styles}};return{..._t.features,...e.features,...Je!==void 0?{scrollToBottom:Je}:{},...We!==void 0?{artifacts:We}:{},...ve!==void 0?{streamAnimation:ve}:{},...Re!==void 0?{askUserQuestion:Re}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{..._t.layout,...e.layout,header:{...(a=_t.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=_t.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=_t.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=_t.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(S=(w=e.layout)==null?void 0:w.messages)==null?void 0:S.timestamp}},slots:{...(H=_t.layout)==null?void 0:H.slots,...(M=e.layout)==null?void 0:M.slots}},markdown:{..._t.markdown,...e.markdown,options:{...(L=_t.markdown)==null?void 0:L.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{..._t.messageActions,...e.messageActions}}:_t}var Jp={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"}},Gp={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"}},Xp={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"}},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:pr,maxWidth:Di,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},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:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",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 es(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?es(e,r):r}function Oi(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=es(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Qp(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 Yp(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=Yp(o,s):n[r]=s}return n}function Wh(e,t){return t?Yp(e,t):e}function $s(e,t={}){var s,o,a,i,d,l,p,u,f,m,v,x,w;let n={palette:Jp,semantic:Gp,components:Xp},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(w=e==null?void 0:e.semantic)==null?void 0:w.typography}},components:Wh(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let S=Qp(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(H=>H.message).join(", ")}`)}if(t.plugins)for(let S of t.plugins)r=S.transform(r);return r}function Fi(e){var x,w,S,H,M,L,I,A,P,F,B,W,U,V,oe,We,Je,ve,Re,he,He,Le,K,pe,z,ce,ie,se,Ae,qe,Q,te,le,ye,ue,re,Ye,Ie,ge,G,Fe,Rt,fe,de,Ln,jt,mn,Hn,Yn,je,O,Te,Be,De,$e,ut,st,Pt,zt,q,Ut,Ze,Ft,ne,xe,Tt,Vt,tn,wn,It,Mt,vt,Ct,Jt,rt,Bn,Zn,Cn,Dn,ht,Tr,Nn,fo,Pn,Do,jr,Ir,At,On,Fn,An,kt,er,tr,$n,Ur,Wr,qr,_n,Bt,Sn,nr,zr,Rr,Vr,Er,jn,gr,yt,Xt,Qt,Un,Kr,rr,fr,qn,$,or;let t=Oi(e),n={};for(let[be,zn]of Object.entries(t)){let sr=be.replace(/\./g,"-");n[`--persona-${sr}`]=zn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(w=n["--persona-semantic-colors-secondary"])!=null?w:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(S=n["--persona-semantic-colors-accent"])!=null?S:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(H=n["--persona-semantic-colors-surface"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(M=n["--persona-semantic-colors-background"])!=null?M:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(L=n["--persona-semantic-colors-container"])!=null?L:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(I=n["--persona-semantic-colors-text"])!=null?I:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(A=n["--persona-semantic-colors-text-muted"])!=null?A:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(P=n["--persona-semantic-colors-text-inverse"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(F=n["--persona-semantic-colors-border"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(B=n["--persona-semantic-colors-divider"])!=null?B:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(W=n["--persona-components-voice-recording-indicator"])!=null?W:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(U=n["--persona-components-voice-recording-background"])!=null?U:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(V=n["--persona-components-voice-processing-icon"])!=null?V:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(oe=n["--persona-components-voice-speaking-icon"])!=null?oe:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(We=n["--persona-components-approval-requested-background"])!=null?We:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Je=n["--persona-components-approval-requested-border"])!=null?Je:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ve=n["--persona-components-approval-requested-text"])!=null?ve:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Re=n["--persona-components-approval-requested-shadow"])!=null?Re:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(he=n["--persona-components-approval-approve-background"])!=null?he:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(He=n["--persona-components-approval-deny-background"])!=null?He:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Le=n["--persona-components-attachment-image-background"])!=null?Le:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(K=n["--persona-components-attachment-image-border"])!=null?K:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(pe=n["--persona-semantic-typography-fontFamily"])!=null?pe:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(z=n["--persona-semantic-typography-fontSize"])!=null?z:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ce=n["--persona-semantic-typography-fontWeight"])!=null?ce:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(ie=n["--persona-semantic-typography-lineHeight"])!=null?ie: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"]=(se=n["--persona-palette-radius-sm"])!=null?se:"0.125rem",n["--persona-radius-md"]=(Ae=n["--persona-palette-radius-md"])!=null?Ae:"0.375rem",n["--persona-radius-lg"]=(qe=n["--persona-palette-radius-lg"])!=null?qe:"0.5rem",n["--persona-radius-xl"]=(Q=n["--persona-palette-radius-xl"])!=null?Q:"0.75rem",n["--persona-radius-full"]=(te=n["--persona-palette-radius-full"])!=null?te:"9999px",n["--persona-launcher-radius"]=(ye=(le=n["--persona-components-launcher-borderRadius"])!=null?le:n["--persona-palette-radius-full"])!=null?ye:"9999px",n["--persona-launcher-bg"]=(ue=n["--persona-components-launcher-background"])!=null?ue:n["--persona-primary"],n["--persona-launcher-fg"]=(re=n["--persona-components-launcher-foreground"])!=null?re:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ye=n["--persona-components-launcher-border"])!=null?Ye:n["--persona-border"],n["--persona-button-primary-bg"]=(Ie=n["--persona-components-button-primary-background"])!=null?Ie:n["--persona-primary"],n["--persona-button-primary-fg"]=(ge=n["--persona-components-button-primary-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-button-radius"]=(Fe=(G=n["--persona-components-button-primary-borderRadius"])!=null?G:n["--persona-palette-radius-full"])!=null?Fe:"9999px",n["--persona-panel-radius"]=(fe=(Rt=n["--persona-components-panel-borderRadius"])!=null?Rt:n["--persona-radius-xl"])!=null?fe:"0.75rem",n["--persona-panel-border"]=(de=n["--persona-components-panel-border"])!=null?de:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(jt=(Ln=n["--persona-components-panel-shadow"])!=null?Ln:n["--persona-palette-shadows-xl"])!=null?jt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(mn=n["--persona-components-launcher-shadow"])!=null?mn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(Yn=(Hn=n["--persona-components-input-borderRadius"])!=null?Hn:n["--persona-radius-lg"])!=null?Yn:"0.5rem",n["--persona-message-user-radius"]=(O=(je=n["--persona-components-message-user-borderRadius"])!=null?je:n["--persona-radius-lg"])!=null?O:"0.5rem",n["--persona-message-assistant-radius"]=(Be=(Te=n["--persona-components-message-assistant-borderRadius"])!=null?Te:n["--persona-radius-lg"])!=null?Be:"0.5rem",n["--persona-header-bg"]=(De=n["--persona-components-header-background"])!=null?De:n["--persona-surface"],n["--persona-header-border"]=($e=n["--persona-components-header-border"])!=null?$e:n["--persona-divider"],n["--persona-header-icon-bg"]=(ut=n["--persona-components-header-iconBackground"])!=null?ut:n["--persona-primary"],n["--persona-header-icon-fg"]=(st=n["--persona-components-header-iconForeground"])!=null?st:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pt=n["--persona-components-header-titleForeground"])!=null?Pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(zt=n["--persona-components-header-subtitleForeground"])!=null?zt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(q=n["--persona-components-header-actionIconForeground"])!=null?q:n["--persona-muted"];let r=(Ut=e.components)==null?void 0:Ut.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(Ze=e.components)==null?void 0:Ze.introCard;n["--persona-intro-card-bg"]=(Ft=n["--persona-components-introCard-background"])!=null?Ft:n["--persona-surface"],n["--persona-intro-card-radius"]=(ne=n["--persona-components-introCard-borderRadius"])!=null?ne:"1rem",n["--persona-intro-card-padding"]=(xe=n["--persona-components-introCard-padding"])!=null?xe:"1.5rem",n["--persona-intro-card-shadow"]=(Vt=(Tt=s==null?void 0:s.shadow)!=null?Tt:n["--persona-components-introCard-shadow"])!=null?Vt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(tn=n["--persona-components-input-background"])!=null?tn:n["--persona-surface"],n["--persona-input-placeholder"]=(wn=n["--persona-components-input-placeholder"])!=null?wn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(It=n["--persona-components-message-user-background"])!=null?It:n["--persona-accent"],n["--persona-message-user-text"]=(Mt=n["--persona-components-message-user-text"])!=null?Mt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(vt=n["--persona-components-message-user-shadow"])!=null?vt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Ct=n["--persona-components-message-assistant-background"])!=null?Ct:n["--persona-surface"],n["--persona-message-assistant-text"]=(Jt=n["--persona-components-message-assistant-text"])!=null?Jt:n["--persona-text"],n["--persona-message-assistant-border"]=(rt=n["--persona-components-message-assistant-border"])!=null?rt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Bn=n["--persona-components-message-assistant-shadow"])!=null?Bn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Cn=(Zn=n["--persona-components-scrollToBottom-background"])!=null?Zn:n["--persona-button-primary-bg"])!=null?Cn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(ht=(Dn=n["--persona-components-scrollToBottom-foreground"])!=null?Dn:n["--persona-button-primary-fg"])!=null?ht:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Tr=n["--persona-components-scrollToBottom-border"])!=null?Tr:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Nn=n["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",n["--persona-scroll-to-bottom-radius"]=(Do=(Pn=(fo=n["--persona-components-scrollToBottom-borderRadius"])!=null?fo:n["--persona-button-radius"])!=null?Pn:n["--persona-radius-full"])!=null?Do:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Ir=(jr=n["--persona-components-scrollToBottom-shadow"])!=null?jr:n["--persona-palette-shadows-sm"])!=null?Ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(At=n["--persona-components-scrollToBottom-padding"])!=null?At:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(On=n["--persona-components-scrollToBottom-gap"])!=null?On:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(An=(Fn=n["--persona-components-scrollToBottom-fontSize"])!=null?Fn:n["--persona-palette-typography-fontSize-sm"])!=null?An:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(kt=n["--persona-components-scrollToBottom-iconSize"])!=null?kt:"14px",n["--persona-tool-bubble-shadow"]=(er=n["--persona-components-toolBubble-shadow"])!=null?er:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(tr=n["--persona-components-reasoningBubble-shadow"])!=null?tr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=($n=n["--persona-components-composer-shadow"])!=null?$n:"none",n["--persona-md-inline-code-bg"]=(Ur=n["--persona-components-markdown-inlineCode-background"])!=null?Ur:n["--persona-container"],n["--persona-md-inline-code-color"]=(Wr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Wr:n["--persona-text"],n["--persona-md-link-color"]=(_n=(qr=n["--persona-components-markdown-link-foreground"])!=null?qr:n["--persona-accent"])!=null?_n:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(Bt=n["--persona-components-markdown-codeBlock-background"])!=null?Bt:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Sn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Sn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(nr=n["--persona-components-markdown-codeBlock-textColor"])!=null?nr:"inherit",n["--persona-md-table-header-bg"]=(zr=n["--persona-components-markdown-table-headerBackground"])!=null?zr:n["--persona-container"],n["--persona-md-table-border-color"]=(Rr=n["--persona-components-markdown-table-borderColor"])!=null?Rr:n["--persona-border"],n["--persona-md-hr-color"]=(Vr=n["--persona-components-markdown-hr-color"])!=null?Vr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Er=n["--persona-components-markdown-blockquote-borderColor"])!=null?Er:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(jn=n["--persona-components-markdown-blockquote-background"])!=null?jn:"transparent",n["--persona-md-blockquote-text-color"]=(gr=n["--persona-components-markdown-blockquote-textColor"])!=null?gr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(yt=n["--persona-components-collapsibleWidget-container"])!=null?yt:n["--persona-surface"],n["--cw-surface"]=(Xt=n["--persona-components-collapsibleWidget-surface"])!=null?Xt:n["--persona-surface"],n["--cw-border"]=(Qt=n["--persona-components-collapsibleWidget-border"])!=null?Qt:n["--persona-border"],n["--persona-message-border"]=(Un=n["--persona-components-message-border"])!=null?Un:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let be=v.toolbar;be.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=be.iconHoverColor),be.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=be.iconHoverBackground),be.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=be.iconPadding),be.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=be.iconBorderRadius),be.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=be.iconBorder),be.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=be.toggleGroupGap),be.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=be.toggleBorderRadius),be.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=be.copyBackground),be.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=be.copyBorder),be.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=be.copyColor),be.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=be.copyBorderRadius),be.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=be.copyPadding),be.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=be.copyMenuBackground,n["--persona-dropdown-bg"]=(Kr=n["--persona-dropdown-bg"])!=null?Kr:be.copyMenuBackground),be.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=be.copyMenuBorder,n["--persona-dropdown-border"]=(rr=n["--persona-dropdown-border"])!=null?rr:be.copyMenuBorder),be.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=be.copyMenuShadow,n["--persona-dropdown-shadow"]=(fr=n["--persona-dropdown-shadow"])!=null?fr:be.copyMenuShadow),be.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=be.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(qn=n["--persona-dropdown-radius"])!=null?qn:be.copyMenuBorderRadius),be.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=be.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=($=n["--persona-dropdown-item-hover-bg"])!=null?$:be.copyMenuItemHoverBackground),be.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=be.iconBackground),be.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=be.toolbarBorder)}if(v!=null&&v.tab){let be=v.tab;be.background&&(n["--persona-artifact-tab-bg"]=be.background),be.activeBackground&&(n["--persona-artifact-tab-active-bg"]=be.activeBackground),be.activeBorder&&(n["--persona-artifact-tab-active-border"]=be.activeBorder),be.borderRadius&&(n["--persona-artifact-tab-radius"]=be.borderRadius),be.textColor&&(n["--persona-artifact-tab-color"]=be.textColor),be.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=be.hoverBackground),be.listBackground&&(n["--persona-artifact-tab-list-bg"]=be.listBackground),be.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=be.listBorderColor),be.listPadding&&(n["--persona-artifact-tab-list-padding"]=be.listPadding)}if(v!=null&&v.pane){let be=v.pane;if(be.toolbarBackground){let zn=(or=es(e,be.toolbarBackground))!=null?or:be.toolbarBackground;n["--persona-artifact-toolbar-bg"]=zn}}return n}var Rh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Hh={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"}}},Zp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Oa=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Bh=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Oa()},eu=e=>Bh(e),Dh=e=>$s(e),Nh=e=>{var n;let t=$s(void 0,{validate:!1});return $s({...e,palette:{...t.palette,colors:{...Hh.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},_s=e=>{let t=eu(e),n=Zp(e==null?void 0:e.theme),r=Zp(e==null?void 0:e.darkTheme);return t==="dark"?Nh(Fs(n!=null?n:{},r!=null?r:{})):Dh(n)},Oh=e=>Fi(e),Io=(e,t)=>{let n=_s(t),r=Oh(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},$i=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Oa())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Oa());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Fh}from"idiomorph";var Fa=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Fh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var $a={index:-1,draft:""};function tu(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...$a}}}function nu(e,t){var n,r,s,o,a,i,d,l,p,u,f,m,v,x,w,S,H,M,L,I,A,P,F,B,W,U,V,oe,We,Je,ve,Re,he,He,Le,K,pe,z;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(w=(x=e.toolCall)==null?void 0:x.name)!=null?w:"",(M=(H=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:H.length)!=null?M:0,(P=(A=(I=(L=e.toolCall)==null?void 0:L.chunks)==null?void 0:I[e.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?P:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:(B=e.toolCall)!=null&&B.args?JSON.stringify(e.toolCall.args).length:0,(V=(U=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:U.length)!=null?V:0,(ve=(Je=(We=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:Je.length)!=null?ve:0,(Le=(He=(he=(Re=e.reasoning)==null?void 0:Re.chunks)==null?void 0:he[e.reasoning.chunks.length-1])==null?void 0:He.slice(-32))!=null?Le:"",(pe=(K=e.contentParts)==null?void 0:K.length)!=null?pe:0,(z=e.stopReason)!=null?z:"",t].join("\0")}function ru(){return new Map}function ou(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function su(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function au(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function _a(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function js(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Us(e,t){return js(e)-e.scrollTop<=t}function ja(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Ua(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},vn=1e5,oo=vn+1;var qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},$h=["pre","code","a","script","style"],qa=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:qs.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:qs.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:qs.speed,duration:(s=e==null?void 0:e.duration)!=null?s:qs.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:qs.buffer}},lu=[{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"}],zs=new Map;for(let e of lu)zs.set(e.name,e);var _h=e=>{zs.set(e.name,e)},jh=e=>{lu.some(t=>t.name===e)||zs.delete(e)},Uh=()=>Array.from(zs.keys()),Vs=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=zs.get(e))!=null?r:null},za=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
15
+ `);return o<0?"":e.slice(0,o)}return e},qh=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},zh=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},_i=/\s/,Vh=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Kh=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(_i.test(o[i])){let l=i;for(;l<o.length&&_i.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<o.length&&!_i.test(o[p]);)l.appendChild(qh(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},Jh=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(zh(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},Ks=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((u=r==null?void 0:r.skipTags)!=null?u:$h).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Vh(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Kh:Jh;for(let m of i)p(m,n,l);return s.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},Js=(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},iu=new WeakMap,Gh=(e,t)=>{var o;if(!e.styles)return;let n=iu.get(t);if(n||(n=new Set,iu.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},ji=new WeakMap,Xh=(e,t)=>{if(!e.onAttach)return;let n=ji.get(t);if(n||(n=new Map,ji.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},cu=e=>{let t=ji.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ui=(e,t)=>{Gh(e,t),Xh(e,t)};function qi(e,t=vn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var Gs=0,so=null;function zi(e=document){var n;if(Gs++,Gs===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;so={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,Gs=Math.max(0,Gs-1),Gs===0&&so)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=so.originalOverflow,s.style.position=so.originalPosition,s.style.top=so.originalTop,s.style.width=so.originalWidth,o.scrollTo(0,so.scrollY),so=null}}}var Ka={side:"right",width:"420px",animate:!0,reveal:"resize"},un=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},ao=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Ar=e=>{var n,r,s,o,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Ka.side,width:(s=t==null?void 0:t.width)!=null?s:Ka.width,animate:(o=t==null?void 0:t.animate)!=null?o:Ka.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ka.reveal}};var Sr={"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 Xs=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
16
16
  <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>
17
17
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
18
18
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -20,14 +20,14 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
20
20
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
21
21
  </span>
22
22
  <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>
23
- `,n.addEventListener("click",t);let r=o=>{var L,P,W,w,I,O,$,B,j,z,oe,We,je,Ne;let a=(L=o.launcher)!=null?L:{},i=an(o),d=n.querySelector("[data-role='launcher-title']");if(d){let ge=(P=a.title)!=null?P:"Chat Assistant";d.textContent=ge,d.setAttribute("title",ge)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ge=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=ge,l.setAttribute("title",ge)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ge=(w=a.agentIconSize)!=null?w:"40px";if(m.style.height=ge,m.style.width=ge,m.innerHTML="",a.agentIconName){let ye=parseFloat(ge)||24,Le=be(a.agentIconName,ye*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(m.appendChild(Le),m.style.display=""):(m.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ge=($=a.agentIconSize)!=null?$:"40px";g.style.height=ge,g.style.width=ge,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let ge=(B=a.callToActionIconSize)!=null?B:"32px";u.style.height=ge,u.style.width=ge,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let ye=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,ye=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Le=parseFloat(ge)||24,He=Math.max(Le-ye,8),ee=be(a.callToActionIconName,He,"currentColor",2);ee?u.appendChild(ee):u.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else u.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let v=a.position&&br[a.position]?br[a.position]:br["bottom-right"],x="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",C="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=i?C:`${x} ${v}`,i||(n.style.zIndex=String((oe=a.zIndex)!=null?oe:fn));let T="1px solid var(--persona-border, #e5e7eb)",H="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(We=a.border)!=null?We:T,n.style.boxShadow=(je=a.shadow)!=null?je:H,i?(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=(Ne=a.collapsedMaxWidth)!=null?Ne:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var $h="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ka=(e,t={})=>{var x,C,T,H,L,P;let{showClose:n=!0,wrapperClassName:r=$h,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(C=s!=null?s:a.closeButtonSize)!=null?C:"32px",d=h("div",r),l=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");l.style.height=i,l.style.width=i,l.type="button";let p=(T=a.closeButtonTooltipText)!=null?T:"Close chat",m=(H=a.closeButtonShowTooltip)!=null?H:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let g=(L=a.closeButtonIconName)!=null?L:"x",u=(P=a.closeButtonIconText)!=null?P:"\xD7";l.style.color=a.closeButtonColor||En.actionIconColor;let v=be(g,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let W=null,w=()=>{if(W)return;let O=l.ownerDocument,$=O.body;if(!$)return;W=Sr(O,"div","persona-clear-chat-tooltip"),W.textContent=p;let B=Sr(O,"div");B.className="persona-clear-chat-tooltip-arrow",W.appendChild(B);let j=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(eo),W.style.left=`${j.left+j.width/2}px`,W.style.top=`${j.top-8}px`,W.style.transform="translate(-50%, -100%)",$.appendChild(W)},I=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",I),l.addEventListener("focus",w),l.addEventListener("blur",I),d._cleanupTooltip=()=>{I(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",I),l.removeEventListener("focus",w),l.removeEventListener("blur",I)}}return{button:l,wrapper:d}},_h="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ja=(e,t={})=>{var W,w,I,O,$,B,j,z,oe,We,je,Ne,ge;let{wrapperClassName:n=_h,buttonSize:r,iconSize:s="20px"}=t,a=(w=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?w:{},i=(I=r!=null?r:a.size)!=null?I:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",l=($=a.iconColor)!=null?$:"",p=(B=a.backgroundColor)!=null?B:"",m=(j=a.borderWidth)!=null?j:"",g=(z=a.borderColor)!=null?z:"",u=(oe=a.borderRadius)!=null?oe:"",v=(We=a.paddingX)!=null?We:"",x=(je=a.paddingY)!=null?je:"",C=(Ne=a.tooltipText)!=null?Ne:"Clear chat",T=(ge=a.showTooltip)!=null?ge:!0,H=h("div",n),L=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");L.style.height=i,L.style.width=i,L.type="button",L.setAttribute("aria-label",C),L.style.color=l||En.actionIconColor;let P=be(d,s,"currentColor",1);if(P&&(P.style.display="block",L.appendChild(P)),p&&(L.style.backgroundColor=p,L.classList.remove("hover:persona-bg-gray-100")),m||g){let ye=m||"0px",Le=g||"transparent";L.style.border=`${ye} solid ${Le}`,L.classList.remove("persona-border-none")}if(u&&(L.style.borderRadius=u,L.classList.remove("persona-rounded-full")),v&&(L.style.paddingLeft=v,L.style.paddingRight=v),x&&(L.style.paddingTop=x,L.style.paddingBottom=x),H.appendChild(L),T&&C){let ye=null,Le=()=>{if(ye)return;let ee=L.ownerDocument,Pe=ee.body;if(!Pe)return;ye=Sr(ee,"div","persona-clear-chat-tooltip"),ye.textContent=C;let V=Sr(ee,"div");V.className="persona-clear-chat-tooltip-arrow",ye.appendChild(V);let le=L.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(eo),ye.style.left=`${le.left+le.width/2}px`,ye.style.top=`${le.top-8}px`,ye.style.transform="translate(-50%, -100%)",Pe.appendChild(ye)},He=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};H.addEventListener("mouseenter",Le),H.addEventListener("mouseleave",He),L.addEventListener("focus",Le),L.addEventListener("blur",He),H._cleanupTooltip=()=>{He(),H.removeEventListener("mouseenter",Le),H.removeEventListener("mouseleave",He),L.removeEventListener("focus",Le),L.removeEventListener("blur",He)}}return{button:L,wrapper:H}};var En={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))"},ro=e=>{var W,w,I,O,$,B,j,z,oe,We,je,Ne,ge,ye,Le,He;let{config:t,showClose:n=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(W=t==null?void 0:t.launcher)!=null?W:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(I=s.closeButtonPlacement)!=null?I:"inline",i=(O=s.headerIconHidden)!=null?O:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(o)||24,Pe=be(d,ee*.6,"currentColor",1);Pe?l.replaceChildren(Pe):l.textContent=(B=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?B:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let ee=h("img");ee.src=t.launcher.iconUrl,ee.alt="",ee.className="persona-rounded-xl persona-object-cover",ee.style.height=o,ee.style.width=o,l.replaceChildren(ee)}else l.textContent=(oe=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?oe:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=h("span","persona-text-base persona-font-semibold");m.style.color=En.titleColor,m.textContent=(je=(We=t==null?void 0:t.launcher)==null?void 0:We.title)!=null?je:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=En.subtitleColor,g.textContent=(ge=(Ne=t==null?void 0:t.launcher)==null?void 0:Ne.subtitle)!=null?ge:"Here to help you get answers fast",p.append(m,g),i?r.append(p):r.append(l,p);let u=(ye=s.clearChat)!=null?ye:{},v=(Le=u.enabled)!=null?Le:!0,x=(He=u.placement)!=null?He:"inline",C=null,T=null;if(v){let Pe=Ja(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=Pe.button,T=Pe.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let H=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="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:L,wrapper:P}=Ka(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&r.appendChild(P),{header:r,iconHolder:l,headerTitle:m,headerSubtitle:g,closeButton:L,closeButtonWrapper:P,clearChatButton:C,clearChatButtonWrapper:T}},Go=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Mo(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(eo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of t){if(u.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let C=be(u.icon,16,"currentColor",1.5);C&&v.appendChild(C)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",C=>{C.stopPropagation(),p(),n(u.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:g}}function qt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=be(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function Ga(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=be(t,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=h("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))p.setAttribute(g,u);return p}function Xa(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=qt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=h("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function l(p){a=p,d()}return{element:o,setSelected:l}}function $i(e){var u,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let m=be(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,C;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(C=d.border)!=null?C:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Mo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let C=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var ru=e=>{var r;let t=ro({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function jh(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=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(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=be(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=Mo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var ou=e=>{var H,L,P,W,w,I,O,$,B;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(H=t==null?void 0:t.launcher)!=null?H:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,p;if(d)l=$i({label:(L=a.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=En.titleColor,p=(P=l.querySelector(".persona-combo-btn-label"))!=null?P:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=En.titleColor,p.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(p),jh(l,s==null?void 0:s.trailingActions,(w=s==null?void 0:s.onAction)!=null?w:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let z=s.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||z()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),z())})}let j=s==null?void 0:s.titleRowHover;j&&(l.style.borderRadius=(I=j.borderRadius)!=null?I:"10px",l.style.padding=(O=j.padding)!=null?O:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var z,oe;l.style.backgroundColor=(z=j.background)!=null?z:"",l.style.borderColor=(oe=j.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=($=a.closeButtonSize)!=null?$:"32px",g=h("div",""),u=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");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||En.actionIconColor;let v=(B=a.closeButtonIconName)!=null?B:"x",x=be(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let C=h("div");C.style.display="none";let T=h("span");return T.style.display="none",{header:i,iconHolder:C,headerTitle:p,headerSubtitle:T,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},_i={default:ru,minimal:ou},su=e=>{var t;return(t=_i[e])!=null?t:_i.default},qs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=h("div");p.style.display="none";let m=h("span"),g=h("span"),u=h("button");u.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=su(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Qa=e=>{var a,i;let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"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-primary 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,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}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:o}},Ya=e=>{var W,w,I,O,$,B,j,z,oe,We,je,Ne;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(w=t.useIcon)!=null?w:!1,r=(I=t.iconText)!=null?I:"\u2191",s=t.iconName,o=(O=t.stopIconName)!=null?O:"square",a=($=t.tooltipText)!=null?$:"Send message",i=(B=t.stopTooltipText)!=null?B:"Stop generating",d=(z=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?z:"Send",l=(We=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?We:"Stop",p=(je=t.showTooltip)!=null?je:!1,m=(Ne=t.size)!=null?Ne:"40px",g=t.backgroundColor,u=t.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let C=null,T=null;if(n){x.style.width=m,x.style.height=m,x.style.minWidth=m,x.style.minHeight=m,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",u?x.style.color=u:x.style.color="var(--persona-button-primary-fg, #ffffff)";let ge=parseFloat(m)||24,ye=(u==null?void 0:u.trim())||"currentColor";s?(C=be(s,ge,ye,2),C?x.appendChild(C):x.textContent=r):x.textContent=r,T=be(o,ge,ye,2),g?x.style.backgroundColor=g:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,u?x.style.color=u:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let H=null;p&&a&&(H=h("div","persona-send-button-tooltip"),H.textContent=a,v.appendChild(H)),x.setAttribute("aria-label",a),v.appendChild(x);let L="send";return{button:x,wrapper:v,setMode:ge=>{if(ge===L)return;L=ge;let ye=ge==="stop"?i:a;if(x.setAttribute("aria-label",ye),H&&(H.textContent=ye),n){if(C&&T){let Le=ge==="stop"?T:C;x.replaceChildren(Le)}}else x.textContent=ge==="stop"?l:d}}},Za=e=>{var H,L,P,W,w,I,O,$,B,j,z,oe;let t=(H=e==null?void 0:e.voiceRecognition)!=null?H:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((L=t.provider)==null?void 0:L.type)==="runtype";if(!(r||s))return null;let a=(W=(P=e==null?void 0:e.sendButton)==null?void 0:P.size)!=null?W:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=t.iconName)!=null?w:"mic",p=(I=t.iconSize)!=null?I:a,m=parseFloat(p)||24,g=($=t.backgroundColor)!=null?$:(O=e==null?void 0:e.sendButton)==null?void 0:O.backgroundColor,u=(j=t.iconColor)!=null?j:(B=e==null?void 0:e.sendButton)==null?void 0:B.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let x=be(l,m,u||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let C=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((oe=t.showTooltip)!=null?oe:!1)&&C){let We=h("div","persona-send-button-tooltip");We.textContent=C,i.appendChild(We)}return{button:d,wrapper:i}},ei=e=>{var v,x,C,T,H,L,P,W;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(C=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?C:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((T=t.allowedTypes)!=null?T:Nr).join(","),s.multiple=((H=t.maxFiles)!=null?H:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(L=t.buttonTooltipText)!=null?L:"Attach file");let i=(P=t.buttonIconName)!=null?P:"paperclip",d=n,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=be(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),s.click()}),o.appendChild(a);let g=(W=t.buttonTooltipText)!=null?W:"Attach file",u=h("div","persona-send-button-tooltip");return u.textContent=g,o.appendChild(u),{button:a,wrapper:o,input:s,previewsContainer:r}},ti=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=h("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},ni=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var zs=e=>{var v,x,C,T,H,L;let{config:t}=e,n=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let r=ni(),s=h("form","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");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Qa(t);a();let i=Ya(t),d=Za(t),l=ei(t),p=ti(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let m=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(g,u),s.append(m),s.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(C=l==null?void 0:l.button)!=null?C:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(H=l==null?void 0:l.input)!=null?H:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var au=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=h("span","persona-pill-peek__icon"),n=be("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=be("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},iu=e=>{var v,x,C,T,H,L;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=ni();r.style.display="none";let s=ti(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Qa(t);o.style.maxHeight="100px",a();let i=Ya(t),d=Za(t),l=ei(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let g=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(m,o,g),l&&n.append(l.previewsContainer),n.append(p,r,s);let u=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(C=l==null?void 0:l.button)!=null?C:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(H=l==null?void 0:l.input)!=null?H:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var lu=e=>{var p,m,g,u,v,x,C,T,H,L,P,W,w,I,O,$,B;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=an(e);if(no(e)){let j=(u=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?u:{},z=h("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",z.style.zIndex=String((C=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?C:fn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",z.appendChild(oe);let We=h("div","persona-widget-pill-root");return We.setAttribute("data-persona-composer-bar",""),We.dataset.state="collapsed",We.dataset.expandedSize=(T=j.expandedSize)!=null?T:"anchored",We.style.zIndex=String((L=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?L:fn),{wrapper:z,panel:oe,pillRoot:We}}if(n){let j=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(z),{wrapper:j,panel:z}}if(!t){let j=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.width)!=null?W:"100%";return j.style.width=oe,z.style.width="100%",j.appendChild(z),{wrapper:j,panel:z}}let s=(w=e==null?void 0:e.launcher)!=null?w:{},o=s.position&&br[s.position]?br[s.position]:br["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((O=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?O:fn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(B=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?B:e==null?void 0:e.launcherWidth,l=d!=null?d:sr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Uh=(e,t)=>{var P,W,w,I,O,$,B,j,z;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:r,wrapper:s}=Ka(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(w=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.clearChat)==null?void 0:W.enabled)!=null?w:!0,a=null,i=null;if(o){let oe=Ja(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","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");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(O=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?O:"Hello \u{1F44B}";let g=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(B=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",p.append(m,g);let u=h("div","persona-flex persona-flex-col persona-gap-3"),v=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let C=h("div","persona-composer-overlay persona-pointer-events-none");C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20";let T=iu({config:e}),{root:H,textNode:L}=au();return n.append(d,s,l,C),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:C,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:m,introSubtitle:g,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:H,peekTextNode:L}},cu=(e,t=!0)=>{var C,T,H,L,P,W,w,I,O;if(no(e))return Uh(e,t);let n=h("div","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");n.setAttribute("data-persona-theme-zone","container");let r=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,o=r?qs(e,r,{showClose:t}):ro({config:e,showClose:t}),a=h("div","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");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=an(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(L=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?L:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),m=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=zs({config:e}),v=((O=e==null?void 0:e.layout)==null?void 0:O.showFooter)!==!1;s?Go(n,o,e):(o.header.style.display="none",Go(n,o,e)),n.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(u.footer.style.display="none"),n.append(u.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var qh=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}},zh=(e,t)=>{if(!e)return null;let n=qh(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Vh=(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},Kh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ji=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(":"))},Ui=320,pu=320,Jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Gh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Xh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Qh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Yh=(e,t,n)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let l=h("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Ui}px`,l.style.maxHeight=`${pu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),Kh(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Zh=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(r=>{if(!ji(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Ui}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ey=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(r=>{if(!ji(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Ui}px`,s.style.maxHeight=`${pu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ty=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(r=>{if(!ji(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Xo=()=>{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 r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},uu=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Xo};if(t){let s=t(r);if(s!==null)return s}return Xo()},ny=(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"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,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},du=(e,t)=>{let n=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ry=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];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-primary","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-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"),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-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},mu=(e,t,n)=>{var u,v,x,C,T,H;let r=(u=t.showCopy)!=null?u:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let L=h("div");return L.style.display="none",L.id=`actions-${e.id}`,L.setAttribute("data-actions-for",e.id),L}let a=(C=t.visibility)!=null?C:"hover",i=(T=t.align)!=null?T:"right",d=(H=t.layout)!=null?H:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let g=(L,P,W)=>{let w=qt({icon:L,label:P,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",W),w};return r&&m.appendChild(g("copy","Copy message","copy")),s&&m.appendChild(g("thumbs-up","Upvote","upvote")),o&&m.appendChild(g("thumbs-down","Downvote","downvote")),m},Vs=(e,t,n,r,s,o)=>{var ee,Pe,V,le,ve,fe,we,ze,Q,te,se,ue,ie,re,Qe,Ie,ce;let a=n!=null?n:{},i=(ee=a.layout)!=null?ee:"bubble",d=a.avatar,l=a.timestamp,p=(Pe=d==null?void 0:d.show)!=null?Pe:!1,m=(V=l==null?void 0:l.show)!=null?V:!1,g=(le=d==null?void 0:d.position)!=null?le:"left",u=(ve=l==null?void 0:l.position)!=null?ve:"below",v=ry(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=Jh(e),T=(we=(fe=e.content)==null?void 0:fe.trim())!=null?we:"",L=C.length>0&&T===Pa,P=Ua((Q=(ze=o==null?void 0:o.widgetConfig)==null?void 0:ze.features)==null?void 0:Q.streamAnimation),W=(ue=(se=(te=o==null?void 0:o.widgetConfig)==null?void 0:te.features)==null?void 0:se.streamAnimation)==null?void 0:ue.plugins,w=e.role==="assistant"&&P.type!=="none"?Os(P.type,W):null,I=e.role==="assistant"&&((ie=w==null?void 0:w.isAnimating)==null?void 0:ie.call(w,e))===!0,O=e.role==="assistant"&&w!==null&&(!!e.streaming||I);O&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),O&&w&&(w.containerClass&&$.classList.add(w.containerClass),$.style.setProperty("--persona-stream-step",`${P.speed}ms`),$.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let B=O?qa((re=e.content)!=null?re:"",P.buffer,w,e,!!e.streaming):(Qe=e.content)!=null?Qe:"",j=t({text:B,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=j;O&&(w==null?void 0:w.wrap)==="char"?z=$s(j,"char",e.id,{skipTags:w.skipTags}):O&&(w==null?void 0:w.wrap)==="word"&&(z=$s(j,"word",e.id,{skipTags:w.skipTags}));let oe=null;if(L?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",$.appendChild(oe)):$.innerHTML=z,O&&(w!=null&&w.useCaret)&&!L&&T){let G=za(),$e=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=$e[$e.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(G,Et.nextSibling);else{let de=$.lastElementChild;de?de.appendChild(G):$.appendChild(G)}}if(m&&u==="inline"&&e.createdAt){let G=du(e,l);G.classList.add("persona-ml-2","persona-inline"),$.appendChild(G)}if(C.length>0){let G=Yh(C,!L&&!!T,()=>{L&&oe&&(oe.style.display="")});G?x.appendChild(G):L&&oe&&(oe.style.display="")}let We=Gh(e);if(We.length>0){let G=Zh(We);G&&x.appendChild(G)}let je=Xh(e);if(je.length>0){let G=ey(je);G&&x.appendChild(G)}let Ne=Qh(e);if(Ne.length>0){let G=ty(Ne);G&&x.appendChild(G)}if(x.appendChild($),m&&u==="below"&&e.createdAt){let G=du(e,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let ge=e.role==="assistant"?zh(e.stopReason,(ce=(Ie=o==null?void 0:o.widgetConfig)==null?void 0:Ie.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(B&&B.trim()),$e=P.placeholder==="skeleton",Et=$e&&P.buffer==="line"&&G;if(G)Et&&x.appendChild(_s());else if($e)x.appendChild(_s());else{let de=uu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);de&&x.appendChild(de)}}if(ge&&e.stopReason&&!e.streaming&&(T||($.style.display="none"),x.appendChild(Vh(e.stopReason,ge))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let G=mu(e,r,s);x.appendChild(G)}if(!p||e.role==="system")return x;let Le=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),He=ny(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Le.append(x,He):Le.append(He,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},oy=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Vs(e,t,n,r,s,o)};var Qo=new Set,sy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ay=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
24
- `):""},gu=(e,t)=>{let n=Qo.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=be(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},qi=(e,t)=>{var je,Ne,ge,ye,Le,He,ee,Pe,V,le,ve;let n=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(Ne=(je=t==null?void 0:t.features)==null?void 0:je.reasoningDisplay)!=null?Ne:{},o=s.expandable!==!1,a=o&&Qo.has(e.id),i=n.status!=="complete",d=ay(e,(ge=s.previewMaxLines)!=null?ge:3),l=h("button",o?"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");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",u=(ye=t==null?void 0:t.reasoning)!=null?ye:{},v=String((Le=n.startedAt)!=null?Le:Date.now()),x=()=>{let fe=h("span","");return fe.setAttribute("data-tool-elapsed",v),fe.textContent=Ea(n),fe},C=(He=u.renderCollapsedSummary)==null?void 0:He.call(u,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ea(n),createElapsedElement:x});typeof C=="string"&&C.trim()?(m.textContent=C,p.appendChild(m)):C instanceof HTMLElement?p.appendChild(C):(m.textContent=g,p.appendChild(m));let T=h("span","persona-text-xs persona-text-persona-primary");T.textContent=Ip(n),p.appendChild(T);let H=(ee=s.loadingAnimation)!=null?ee:"none",L=u.activeTextTemplate,P=u.completeTextTemplate,W=i?L:P,w=C instanceof HTMLElement,I=(fe,we,ze)=>{let Q=ze;for(let te of we){let se=h("span","persona-tool-char");se.style.setProperty("--char-index",String(Q)),se.textContent=te===" "?"\xA0":te,fe.appendChild(se),Q++}return Q},O=(fe,we)=>{m.textContent="";let ze=Ma(fe,""),Q=0;for(let te of ze){let se=te.styles.length>0?(()=>{let ue=h("span",te.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(ue),ue})():m;if(te.isDuration&&i)se.appendChild(x());else{let ue=te.isDuration?Ea(n):te.text;we?Q=I(se,ue,Q):se.appendChild(document.createTextNode(ue))}}};if(!w&&W)if(T.style.display="none",m.style.display="",i&&H!=="none"){let fe=(Pe=u.loadingAnimationDuration)!=null?Pe:2e3;m.setAttribute("data-preserve-animation","true"),H==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),O(W,!1)):(m.classList.add(`persona-tool-loading-${H}`),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),H==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),O(W,!0))}else O(W,!1);else if(!w&&i&&H!=="none"){m.style.display="";let fe=(V=u.loadingAnimationDuration)!=null?V:2e3;if(m.setAttribute("data-preserve-animation","true"),H==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`);else{m.classList.add(`persona-tool-loading-${H}`),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),H==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let we=m.textContent||g;m.textContent="",I(m,we,0)}n.status==="complete"&&(m.style.display="none")}else w||(n.status==="complete"?m.style.display="none":m.style.display="");let $=null;if(o){$=h("div","persona-flex persona-items-center");let we=be(a?"chevron-up":"chevron-down",16,"currentColor",2);we?$.appendChild(we):$.textContent=a?"Hide":"Show";let ze=h("div","persona-flex persona-items-center persona-ml-auto");ze.append($),l.append(p,ze)}else l.append(p);let B=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","reasoning"),B.style.display="none",B.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let fe=(ve=(le=t==null?void 0:t.reasoning)==null?void 0:le.renderCollapsedPreview)==null?void 0:ve.call(le,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});sy(B,fe)||(B.textContent=d),B.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,B),r;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 z=n.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),$){$.innerHTML="";let we=be(a?"chevron-up":"chevron-down",16,"currentColor",2);we?$.appendChild(we):$.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",B.style.display=a?"none":B.textContent||B.childNodes.length?"":"none"})(),r.append(l,B,j),r};var Yo=new Set,iy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ly=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
- `);let s=Uo(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},cy=(e,t)=>{var p,m,g,u,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=ly(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?Wp(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},l=a;return s==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Ai(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ai(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},fu=(e,t,n)=>{var p;let r=Yo.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"currentColor",g=be(r?"chevron-up":"chevron-down",16,m,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},zi=(e,t)=>{var z,oe,We,je,Ne,ge,ye,Le,He;let n=e.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!n)return s;let o=(We=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?We:{},a=o.expandable!==!1,i=a&&Yo.has(e.id),{summary:d,previewText:l,isActive:p}=cy(e,t),m=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");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((je=n.startedAt)!=null?je:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",v),ee.textContent=ks(n),ee},C=(ge=r.renderCollapsedSummary)==null?void 0:ge.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Ne=o.collapsedMode)!=null?Ne:"tool-call",isActive:p,config:t!=null?t:{},elapsed:ks(n),createElapsedElement:x});typeof C=="string"&&C.trim()?(u.textContent=C,g.appendChild(u)):C instanceof HTMLElement?g.appendChild(C):(u.textContent=d,g.appendChild(u));let T=(ye=o.loadingAnimation)!=null?ye:"none",H=r.activeTextTemplate,L=r.completeTextTemplate,P=p?H:L,W=C instanceof HTMLElement,w=(ee,Pe,V)=>{let le=V;for(let ve of Pe){let fe=h("span","persona-tool-char");fe.style.setProperty("--char-index",String(le)),fe.textContent=ve===" "?"\xA0":ve,ee.appendChild(fe),le++}return le},I=(ee,Pe)=>{var fe;u.textContent="";let V=((fe=n.name)==null?void 0:fe.trim())||"tool",le=Ma(ee,V),ve=0;for(let we of le){let ze=we.styles.length>0?(()=>{let Q=h("span",we.styles.map(te=>`persona-tool-text-${te}`).join(" "));return u.appendChild(Q),Q})():u;if(we.isDuration&&p)ze.appendChild(x());else{let Q=we.isDuration?ks(n):we.text;Pe?ve=w(ze,Q,ve):ze.appendChild(document.createTextNode(Q))}}};if(!W)if(p&&T!=="none"){let ee=(Le=r.loadingAnimationDuration)!=null?Le:2e3;if(u.setAttribute("data-preserve-animation","true"),T==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),P&&I(P,!1);else if(u.classList.add(`persona-tool-loading-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),P)I(P,!0);else{let Pe=u.textContent||d;u.textContent="",w(u,Pe,0)}}else P&&I(P,!1);let O=null;if(a){O=h("div","persona-flex persona-items-center");let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Pe=be(i?"chevron-up":"chevron-down",16,ee,2);Pe?O.appendChild(Pe):O.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append(O),m.append(g,V)}else m.append(g);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let ee=(He=r.renderCollapsedPreview)==null?void 0:He.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});iy($,ee)||($.textContent=l),$.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,$),s;let B=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(B.style.display=i?"":"none",r.contentBackgroundColor&&(B.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(B.style.color=r.contentTextColor),r.contentPaddingX&&(B.style.paddingLeft=r.contentPaddingX,B.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(B.style.paddingTop=r.contentPaddingY,B.style.paddingBottom=r.contentPaddingY),n.name){let ee=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ee.style.color=r.contentTextColor:r.headerTextColor&&(ee.style.color=r.headerTextColor),ee.textContent=n.name,B.appendChild(ee)}if(n.args!==void 0){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Arguments";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=Uo(n.args),ee.append(Pe,V),B.appendChild(ee)}if(n.chunks&&n.chunks.length){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Activity";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=n.chunks.join(""),ee.append(Pe,V),B.appendChild(ee)}if(n.status==="complete"&&n.result!==void 0){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Result";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=Uo(n.result),ee.append(Pe,V),B.appendChild(ee)}if(n.status==="complete"&&typeof n.duration=="number"){let ee=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ee.style.color=r.contentTextColor),ee.textContent=`Duration: ${n.duration}ms`,B.appendChild(ee)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Pe=be(i?"chevron-up":"chevron-down",16,ee,2);Pe?O.appendChild(Pe):O.textContent=i?"Hide":"Show"}B.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(m,$,B),s};import{parse as dy,ARR as py,OBJ as uy,STR as my}from"partial-json";var yu="ask_user_question",Vi=8,Zo="data-persona-ask-sheet-for",gy="Other",fy="Other\u2026",bu="Type your own answer here",xu="Send",hy="Next",yy="Back",by="Submit all",xy="Skip",vy=3,Ki="data-ask-current-index",Ji="data-ask-question-count",vu="data-ask-answers",Gi="data-ask-grouped",wu="data-ask-layout",wy=e=>e.layout==="pills"?"pills":"rows",Cy=e=>e.getAttribute(wu)==="pills"?"pills":"rows",hu=!1,Cu=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===yu,ri=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},so=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 r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=dy(s,my|uy|py);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},Ks=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Vi&&!hu&&(hu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Vi}.`)),t.slice(0,Vi)},Ay=e=>{var t;return(t=Ks(e)[0])!=null?t:null},Sy=(e,t)=>{var n;return(n=Ks(e)[t])!=null?n:null},Au=(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))},Su=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Ty=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Su(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Ey=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},My=(e,t,n,r)=>{var p,m,g;let o=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");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<vy;u++)o.appendChild(Ey(r));return o}if(d.forEach((u,v)=>{o.appendChild(Ty(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?gy:fy;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),C=document.createElement("input");C.type="text",C.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",C.placeholder=(p=t.freeTextPlaceholder)!=null?p:bu,C.setAttribute("data-ask-free-text-input","true"),C.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),x.appendChild(C),v.appendChild(x);let T=Su(r,a,d.length);T&&v.appendChild(T),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:u,o.appendChild(v)}}return o},Tu=(e,t)=>{var o,a;let r=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");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:bu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:xu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},ky=e=>{var r;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=(r=e.submitLabel)!=null?r:xu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ly=(e,t,n)=>{var l,p,m,g;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:yy,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=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=(p=n.skipLabel)!=null?p:xy,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:by:(g=n.nextLabel)!=null?g:hy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},ko=e=>{let t=e.getAttribute(vu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Eu=(e,t)=>{e.setAttribute(vu,JSON.stringify(t))},ar=e=>{var n;let t=Number((n=e.getAttribute(Ki))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Py=(e,t)=>{e.setAttribute(Ki,String(Math.max(0,Math.floor(t))))},es=e=>{var n;let t=Number((n=e.getAttribute(Ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ao=e=>e.getAttribute(Gi)==="true",Iy=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Wy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},oi=(e,t)=>{let{payload:n}=so(t),r=Ks(n),s=ko(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Mu=e=>{let t=ko(e),n=ar(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},ku=e=>{if(!ao(e))return;let t=ko(e),n=ar(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Xi=(e,t,n)=>{let r=ri(n),s=Cy(e),{payload:o,complete:a}=so(t),i=ao(e),d=ar(e),l=es(e),p=i?Sy(o,d):Ay(o),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let H=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=H,v.classList.toggle("persona-ask-question-skeleton",!H&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let H=My(p,r,a,s);x.replaceWith(H)}if(s!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(Tu(r,s))}let C=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!C?e.appendChild(ky(r)):(!m||i)&&C&&C.remove(),e.setAttribute("data-multi-select",m?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let H=Ly(d,l,r);T?T.replaceWith(H):e.appendChild(H)}else T&&T.remove();Mu(e),ku(e)},Ry=(e,t,n)=>{let r=ri(t),s=wy(r),o=e.toolCall.id,a=Ks(n),i=Math.max(1,a.length),d=i>1,l=Iy(e,a),p=d?Wy(e,i):0,m=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Zo,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(Ji,String(i)),m.setAttribute(Ki,String(p)),m.setAttribute(Gi,d?"true":"false"),m.setAttribute(wu,s),Eu(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Au(m,r);let g=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=h("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),m.appendChild(g);let C=h("div",s==="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 C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),m.appendChild(C),s!=="rows"&&m.appendChild(Tu(r,s)),Xi(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Hy=(e,t,n)=>{let{payload:r}=so(t),s=Math.max(1,Ks(r).length);s>es(e)&&(e.setAttribute(Ji,String(s)),s>1&&!ao(e)&&e.setAttribute(Gi,"true")),Xi(e,t,n)},By=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=ri(t);Au(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=so(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Js=(e,t,n)=>{if(!n||!oo(e)||ri(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${Zo}]`).forEach(l=>{l.getAttribute(Zo)!==s&&l.remove()});let a=n.querySelector(`[${Zo}="${Cu(s)}"]`);if(a){Hy(a,e,t);return}let{payload:i}=so(e),d=Ry(e,t,i);n.appendChild(d)},Lo=(e,t)=>{if(!e)return;let n=t?`[${Zo}="${Cu(t)}"]`:`[${Zo}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Qi=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),io=(e,t)=>{let n=ko(e),r=ar(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Eu(e,n),Mu(e),ku(e)},si=(e,t,n,r)=>{let s=es(e),o=Math.max(0,Math.min(s-1,r));Py(e,o),Xi(e,t,n)};var Yi=(e,t)=>{var x,C,T,H,L,P,W,w,I,O,$,B;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=r==null?void 0:r.borderColor)!=null?C:"var(--persona-approval-border, #fef08a)",!n)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(T=r==null?void 0:r.titleColor)!=null?T:"currentColor",p=be(d,20,l,2);p&&i.appendChild(p);let m=h("div","persona-flex-1 persona-min-w-0"),g=h("div","persona-flex persona-items-center persona-gap-2"),u=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",g.appendChild(u),!s){let j=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");j.setAttribute("data-approval-status",n.status),n.status==="approved"?(j.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",j.style.color="var(--persona-palette-colors-success-700, #15803d)",j.textContent="Approved"):n.status==="denied"?(j.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",j.style.color="var(--persona-palette-colors-error-700, #b91c1c)",j.textContent="Denied"):n.status==="timeout"&&(j.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",j.style.color="var(--persona-palette-colors-warning-700, #b45309)",j.textContent="Timeout"),g.appendChild(j)}m.appendChild(g);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=n.description,m.appendChild(v),n.parameters){let j=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");r!=null&&r.parameterBackgroundColor&&(j.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(j.style.color=r.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=Uo(n.parameters),m.appendChild(j)}if(s){let j=h("div","persona-flex persona-gap-2 persona-mt-2");j.setAttribute("data-approval-buttons","true");let z=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");z.type="button",z.style.backgroundColor=(L=r==null?void 0:r.approveButtonColor)!=null?L:"var(--persona-approval-approve-bg, #22c55e)",z.style.color=(P=r==null?void 0:r.approveButtonTextColor)!=null?P:"#ffffff",z.setAttribute("data-approval-action","approve");let oe=be("shield-check",14,(W=r==null?void 0:r.approveButtonTextColor)!=null?W:"#ffffff",2);oe&&(oe.style.marginRight="4px",z.appendChild(oe));let We=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");z.appendChild(We);let je=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");je.type="button",je.style.backgroundColor=(I=r==null?void 0:r.denyButtonColor)!=null?I:"transparent",je.style.color=(O=r==null?void 0:r.denyButtonTextColor)!=null?O:"var(--persona-feedback-error, #dc2626)",je.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,je.setAttribute("data-approval-action","deny");let Ne=be("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);Ne&&(Ne.style.marginRight="4px",je.appendChild(Ne));let ge=document.createTextNode((B=r==null?void 0:r.denyLabel)!=null?B:"Deny");je.appendChild(ge),j.append(z,je),m.appendChild(j)}return a.append(i,m),o.appendChild(a),o};var Lu=e=>{let t=[];return{buttons:t,render:(r,s,o,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=s?s.isStreaming():!1,g=u=>{switch(u){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'}};r.forEach(u=>{let v=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");v.type="button",v.textContent=u,v.disabled=m,i!=null&&i.fontFamily&&(v.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(u))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var Gs=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){var n;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),(n=this.store)==null||n.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 r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.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(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=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 r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}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 r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}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(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Dy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ny=new Set(["step_start","execution_start"]),Fy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Oy=new Set(["step_complete","agent_turn_complete"]),$y=new Set(["flow_complete","agent_complete"]),Pu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Wu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Po=(e,t)=>{let n=e[t];return Wu(n)?n:void 0};function Zi(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ai(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function _y(e,t){return typeof t.type=="string"?t.type:e}function jy(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 Uy(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 Iu(e){var r,s,o,a,i;let t=Po(e,"result"),n=[Po(e,"tokens"),Po(e,"totalTokens"),t?Po(t,"tokens"):void 0,Po(e,"usage"),t?Po(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Gn(d.output))!=null?r:Gn(d.outputTokens))!=null?s:Gn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Gn(e.outputTokens))!=null?o:Gn(e.completionTokens))!=null?i:t?(a=Gn(t.outputTokens))!=null?a:Gn(t.completionTokens):void 0}function qy(e){var n,r,s,o,a;let t=Po(e,"result");return(a=(s=(r=(n=Gn(e.executionTime))!=null?n:Gn(e.executionTimeMs))!=null?r:Gn(e.execution_time))!=null?s:Gn(e.duration))!=null?a:t?(o=Gn(t.executionTime))!=null?o:Gn(t.executionTimeMs):void 0}function zy(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=zy){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:ai(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){var o;if(!Wu(n)){Pu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=_y(t,n),s=this.now();if(Dy.has(r)){this.startRun(s);return}if(Ny.has(r)){this.run||this.startRun(s);return}if(Fy.has(r)){if(!Uy(r,n))return;let a=jy(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Zi(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ai(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Oy.has(r)){if(!this.run)return;let a=this.run,i=Iu(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Zi(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:ai(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if($y.has(r)){if(!this.run)return;let a=this.run,i=Iu(n),d=i!=null?i:a.exactOutputTokens+Zi(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:ai(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Pu.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=qy(n);return o!=null?o:r-t.startedAt}};function ts(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Vy={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)"}},Ky={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Jy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Gy=100;function Xy(e,t){let n={...Vy,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Ky}function Qy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Yy(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function Zy(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function eb(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function tb(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 nb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function rb(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 ob(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=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]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function el(e,t,n,r,s,o,a,i){var g;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");ts(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var z,oe;let u=h("div",""),v=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");v.setAttribute("data-event-id",e.id);let x=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=be(d?"chevron-down":"chevron-right","14px","currentColor",2);C&&x.appendChild(C);let T=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),H=(z=r.timestampFormat)!=null?z:"relative";T.textContent=H==="relative"?Qy(e.timestamp,n):Yy(e.timestamp);let L=null;r.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 P=Xy(e.type,r.badgeColors),W=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");W.style.backgroundColor=P.bg,W.style.color=P.text,W.style.borderColor=P.text+"50",W.textContent=e.type;let w=(oe=r.descriptionFields)!=null?oe:Jy,I=Zy(e.payload,w),O=null;I&&(O=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),O.textContent=I);let $=h("div","persona-flex-1 persona-min-w-0"),B=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=be("clipboard","12px","currentColor",1.5);return j&&B.appendChild(j),B.addEventListener("click",async We=>{We.stopPropagation(),await eb(tb(e)),B.innerHTML="";let je=be("check","12px","currentColor",1.5);je&&B.appendChild(je),setTimeout(()=>{B.innerHTML="";let Ne=be("clipboard","12px","currentColor",1.5);Ne&&B.appendChild(Ne)},1500)}),v.appendChild(x),v.appendChild(T),L&&v.appendChild(L),v.appendChild(W),O&&v.appendChild(O),v.appendChild($),v.appendChild(B),u.appendChild(v),d&&u.appendChild(ob(e,a,i)),u}}function Ru(e){var v,x,C,T,H;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(C=i==null?void 0:i.label)!=null?C:"",m=(H=(T=s==null?void 0:s.features)==null?void 0:T.eventStream)!=null?H:{},g=o.find(L=>L.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let L=g.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>u().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return u();function u(){let L=m.classNames,P=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ts(P,L==null?void 0:L.panel);let W=[],w="",I="",O=null,$=[],B={},j=0,z=$a(),oe=0,We=0,je=!1,Ne=null,ge=!1,ye=0,Le=new Set,He=new Map,ee="",Pe="",V=null,le,ve,fe,we,ze,Q=null,te=null,se=null;function ue(){let ne=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),me=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");ts(me,L==null?void 0:L.headerBar);let vt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(vt.textContent="Events",le=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"),le.textContent="0",a){te=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),te.style.cursor="help";let Bn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Bn.textContent="Throughput",Q=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"),Q.textContent="-- tok/s",se=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"),se.style.display="none",se.style.pointerEvents="none";let Qn=te,yn=se,Dn=()=>{if(!yn.textContent)return;let xr=Qn.getBoundingClientRect(),Nn=ne.getBoundingClientRect();yn.style.left=`${xr.left-Nn.left}px`,yn.style.top=`${xr.bottom-Nn.top+4}px`,yn.style.display="block"},ut=()=>{yn.style.display="none"};te.addEventListener("mouseenter",Dn),te.addEventListener("mouseleave",ut),te.appendChild(Bn),te.appendChild(Q)}let jt=h("div","persona-flex-1");ve=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 Zt=h("option","");Zt.value="",Zt.textContent="All events",ve.appendChild(Zt),fe=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"),fe.type="button",fe.title="Copy All";let St=be("clipboard-copy","12px","currentColor",1.5);St&&fe.appendChild(St);let wt=h("span","persona-text-xs");wt.textContent="Copy All",fe.appendChild(wt),me.appendChild(vt),me.appendChild(le),te&&me.appendChild(te),me.appendChild(jt),me.appendChild(ve),me.appendChild(fe);let ft=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ts(ft,L==null?void 0:L.searchBar);let yt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=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");yt&&zt.appendChild(yt),we=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"),ts(we,L==null?void 0:L.searchInput),we.type="text",we.placeholder="Search event payloads...",ze=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"),ze.type="button",ze.style.display="none";let tt=be("x","12px","currentColor",2);return tt&&ze.appendChild(tt),ft.appendChild(zt),ft.appendChild(we),ft.appendChild(ze),ne.appendChild(me),ne.appendChild(ft),se&&ne.appendChild(se),ne}let ie,re=o.find(ne=>ne.renderEventStreamToolbar);if(re!=null&&re.renderEventStreamToolbar&&s){let ne=re.renderEventStreamToolbar({config:s,defaultRenderer:()=>ue(),eventCount:t.getSize(),filteredCount:0,onFilterChange:me=>{w=me,Hn(),N()},onSearchChange:me=>{I=me,Hn(),N()}});ie=ne!=null?ne:ue()}else ie=ue();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 Ie(){if(!a||!Q||!te)return;let ne=a();Q.textContent=nb(ne);let me=rb(ne);se&&(se.textContent=me,me||(se.style.display="none")),me?te.setAttribute("aria-label",me):te.removeAttribute("aria-label")}let ce=h("div","persona-flex-1 persona-min-h-0 persona-relative"),G=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let $e=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");ts($e,L==null?void 0:L.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Et=be(l,"14px","currentColor",2);Et&&$e.appendChild(Et);let de=h("span","");de.textContent=p,$e.appendChild(de);let ae=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",ce.appendChild(G),ce.appendChild(ae),ce.appendChild($e),P.setAttribute("tabindex","0"),P.appendChild(ie),P.appendChild(Qe),P.appendChild(ce);function Mn(){let ne=t.getAll(),me={};for(let wt of ne)me[wt.type]=(me[wt.type]||0)+1;let vt=Object.keys(me).sort(),jt=vt.length!==$.length||!vt.every((wt,ft)=>wt===$[ft]),Zt=!jt&&vt.some(wt=>me[wt]!==B[wt]),hn=ne.length!==Object.values(B).reduce((wt,ft)=>wt+ft,0);if(!jt&&!Zt&&!hn||($=vt,B=me,!ve))return;let St=ve.value;if(ve.options[0].textContent="All events",jt){for(;ve.options.length>1;)ve.remove(1);for(let wt of vt){let ft=h("option","");ft.value=wt,ft.textContent=`${wt} (${me[wt]||0})`,ve.appendChild(ft)}St&&vt.includes(St)?ve.value=St:St&&(ve.value="",w="")}else for(let wt=1;wt<ve.options.length;wt++){let ft=ve.options[wt];ft.textContent=`${ft.value} (${me[ft.value]||0})`}}function Ot(){let ne=t.getAll();if(w&&(ne=ne.filter(me=>me.type===w)),I){let me=I.toLowerCase();ne=ne.filter(vt=>vt.type.toLowerCase().includes(me)||vt.payload.toLowerCase().includes(me))}return ne}function ln(){return w!==""||I!==""}function Hn(){j=0,oe=0,z.resume(),$e.style.display="none"}function Xn(ne){Le.has(ne)?Le.delete(ne):Le.add(ne),V=ne;let me=G.scrollTop,vt=z.isFollowing();ge=!0,z.pause(),N(),G.scrollTop=me,vt&&z.resume(),ge=!1}function Ue(){return Ds(G,50)}function N(){We=Date.now(),je=!1,Ie(),Mn();let ne=t.getEvictedCount();ne>0?(Qe.textContent=`${ne.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",W=Ot();let me=W.length,vt=t.getSize()>0;le&&(le.textContent=String(t.getSize())),me===0&&vt&&ln()?(ae.textContent=I?`No events matching '${I}'`:"No events matching filter",ae.style.display="",G.style.display="none"):(ae.style.display="none",G.style.display=""),fe&&(fe.title=ln()?`Copy Filtered (${me})`:"Copy All"),d&&!z.isFollowing()&&me>j&&(oe+=me-j,de.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",$e.style.display=""),j=me;let jt=t.getAll(),Zt=jt.length>0?jt[0].timestamp:0,hn=new Set(W.map(ft=>ft.id));for(let ft of Le)hn.has(ft)||Le.delete(ft);let St=w!==ee||I!==Pe,wt=He.size===0&&W.length>0;if(St||wt||W.length===0){G.innerHTML="",He.clear();let ft=document.createDocumentFragment();for(let yt=0;yt<W.length;yt++){let zt=el(W[yt],yt,Zt,m,Le,Xn,o,s);He.set(W[yt].id,zt),ft.appendChild(zt)}G.appendChild(ft),ee=w,Pe=I,V=null}else{if(V!==null){let yt=He.get(V);if(yt&&yt.parentNode===G){let zt=W.findIndex(tt=>tt.id===V);if(zt>=0){let tt=el(W[zt],zt,Zt,m,Le,Xn,o,s);G.insertBefore(tt,yt),yt.remove(),He.set(V,tt)}}V=null}let ft=new Set(W.map(yt=>yt.id));for(let[yt,zt]of He)ft.has(yt)||(zt.remove(),He.delete(yt));for(let yt=0;yt<W.length;yt++){let zt=W[yt];if(!He.has(zt.id)){let tt=el(zt,yt,Zt,m,Le,Xn,o,s);He.set(zt.id,tt),G.appendChild(tt)}}}z.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Ae(){if(Date.now()-We>=Gy){Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),N();return}je||(je=!0,Ne=requestAnimationFrame(()=>{Ne=null,N()}))}let Be=(ne,me)=>{if(!fe)return;fe.innerHTML="";let vt=be(ne,"12px","currentColor",1.5);vt&&fe.appendChild(vt);let jt=h("span","persona-text-xs");jt.textContent="Copy All",fe.appendChild(jt),setTimeout(()=>{fe.innerHTML="";let Zt=be("clipboard-copy","12px","currentColor",1.5);Zt&&fe.appendChild(Zt);let hn=h("span","persona-text-xs");hn.textContent="Copy All",fe.appendChild(hn),fe.disabled=!1},me)},De=async()=>{if(fe){fe.disabled=!0;try{let ne;ln()?ne=W:n?(ne=await n(),ne.length===0&&(ne=t.getAll())):ne=t.getAll();let me=ne.map(vt=>{try{return JSON.parse(vt.payload)}catch{return vt.payload}});await navigator.clipboard.writeText(JSON.stringify(me,null,2)),Be("check",1500)}catch{Be("x",1500)}}},_e=()=>{ve&&(w=ve.value,Hn(),N())},dt=()=>{!we||!ze||(ze.style.display=we.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{I=we.value,Hn(),N()},150))},rt=()=>{!we||!ze||(we.value="",I="",ze.style.display="none",O&&clearTimeout(O),Hn(),N())},At=()=>{if(ge)return;let ne=G.scrollTop,{action:me,nextLastScrollTop:vt}=_a({following:z.isFollowing(),currentScrollTop:ne,lastScrollTop:ye,nearBottom:Ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ye=vt,me==="resume"?(z.resume(),oe=0,$e.style.display="none"):me==="pause"&&(z.pause(),d&&(de.textContent=p,$e.style.display=""))},_t=ne=>{let me=ja({following:z.isFollowing(),deltaY:ne.deltaY,nearBottom:Ue(),resumeWhenNearBottom:!0});me==="pause"?(z.pause(),d&&(de.textContent=p,$e.style.display="")):me==="resume"&&(z.resume(),oe=0,$e.style.display="none")},q=()=>{d&&(G.scrollTop=G.scrollHeight,z.resume(),oe=0,$e.style.display="none")},$t=ne=>{let me=ne.target;if(!me||me.closest("button"))return;let vt=me.closest("[data-event-id]");if(!vt)return;let jt=vt.getAttribute("data-event-id");jt&&Xn(jt)},Ye=ne=>{if((ne.metaKey||ne.ctrlKey)&&ne.key==="f"){ne.preventDefault(),we==null||we.focus(),we==null||we.select();return}ne.key==="Escape"&&(we&&document.activeElement===we?(rt(),we.blur(),P.focus()):r&&r())};fe&&fe.addEventListener("click",De),ve&&ve.addEventListener("change",_e),we&&we.addEventListener("input",dt),ze&&ze.addEventListener("click",rt),G.addEventListener("scroll",At),G.addEventListener("wheel",_t,{passive:!0}),G.addEventListener("click",$t),$e.addEventListener("click",q),P.addEventListener("keydown",Ye);function Dt(){O&&clearTimeout(O),Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),je=!1,He.clear(),fe&&fe.removeEventListener("click",De),ve&&ve.removeEventListener("change",_e),we&&we.removeEventListener("input",dt),ze&&ze.removeEventListener("click",rt),G.removeEventListener("scroll",At),G.removeEventListener("wheel",_t),G.removeEventListener("click",$t),$e.removeEventListener("click",q),P.removeEventListener("keydown",Ye)}return{element:P,update:Ae,destroy:Dt}}}function Hu(e,t){let n=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")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.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 l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Bu=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Hu(e,t)});if(p)return p}return Hu(e,t)};var tl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},lo=new tl;lo.register("PersonaArtifactCard",Bu);function sb(e){var s;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 r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Du(e,t){var ve,fe,we,ze;let n=(fe=(ve=e.features)==null?void 0:ve.artifacts)==null?void 0:fe.layout,s=((we=n==null?void 0:n.toolbarPreset)!=null?we:"default")==="document",o=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?_o(e.markdown):null,i=Ts(e.sanitize),d=Q=>{let te=a?a(Q):jo(Q);return i?i(te):te},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};l&&l.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let g=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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let u=h("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let x="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=s?qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):qt({icon:"eye",label:"Rendered view"}),H=s?qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):qt({icon:"code-2",label:"Source"}),L=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),P=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(W&&w&&w.length>0),O=null,$,B=null,j=null;if(s&&(P||W)&&!I){if($=P?Ga({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Q=be("chevron-down",14,"currentColor",2);Q&&$.appendChild(Q)}}else s&&I?(O=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=P?Ga({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B=qt({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"}}),O.append($,B)):s?$=qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=qt({icon:"copy",label:"Copy"});let z=s?qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):qt({icon:"refresh-cw",label:"Refresh"}),oe=s?qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):qt({icon:"x",label:"Close"}),We=()=>{var ie,re,Qe;let Q=(ie=He.find(Ie=>Ie.id===ee))!=null?ie:He[He.length-1],te=(re=Q==null?void 0:Q.id)!=null?re:null,se=(Q==null?void 0:Q.artifactType)==="markdown"&&(Qe=Q.markdown)!=null?Qe:"",ue=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:se,jsonPayload:ue,id:te}},je=async()=>{var ie;let{markdown:Q,jsonPayload:te}=We(),se=(ie=He.find(re=>re.id===ee))!=null?ie:He[He.length-1],ue=(se==null?void 0:se.artifactType)==="markdown"?Q:se?te:"";try{await navigator.clipboard.writeText(ue)}catch{}};if($.addEventListener("click",async()=>{let Q=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Q&&I){let{markdown:te,jsonPayload:se,id:ue}=We();try{await Q({actionId:"primary",artifactId:ue,markdown:te,jsonPayload:se})}catch{}return}await je()}),B&&(w!=null&&w.length)){let Q=()=>{var se;return(se=m.closest("[data-persona-root]"))!=null?se:document.body},te=()=>{j=Mo({items:w.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:ue,jsonPayload:ie,id:re}=We(),Qe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Qe?await Qe({actionId:se,artifactId:re,markdown:ue,jsonPayload:ie}):se==="markdown"||se==="md"?await navigator.clipboard.writeText(ue):se==="json"||se==="source"?await navigator.clipboard.writeText(ie):await navigator.clipboard.writeText(ue||ie)}catch{}},anchor:O!=null?O:B,position:"bottom-right",portal:Q()})};m.isConnected?te():requestAnimationFrame(te),B.addEventListener("click",se=>{se.stopPropagation(),j==null||j.toggle()})}z.addEventListener("click",async()=>{var Q;try{await((Q=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Q.call(n))}catch{}V()}),oe.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let Ne=()=>{s&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),H.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Ne(),V()}),H.addEventListener("click",()=>{x="source",Ne(),V()});let ge=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");s?(g.replaceChildren(),C.append(T,H),O?L.append(O,z,oe):L.append($,z,oe),g.append(C,ge,L),Ne()):(g.appendChild(u),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let ye=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"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ye.style.paddingLeft=o,ye.style.paddingRight=o,Le.style.padding=o),m.appendChild(g),m.appendChild(ye),m.appendChild(Le);let He=[],ee=null,Pe=!1,V=()=>{var ue,ie,re,Qe;let Q=s&&He.length<=1;ye.classList.toggle("persona-hidden",Q),ye.replaceChildren();for(let Ie of He){let ce=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");ce.type="button",ce.textContent=Ie.title||Ie.id.slice(0,8),Ie.id===ee&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(Ie.id)),ye.appendChild(ce)}Le.replaceChildren();let te=ee&&He.find(Ie=>Ie.id===ee)||He[He.length-1];if(!te)return;if(s){let Ie=te.artifactType==="markdown"?"MD":(ue=te.component)!=null?ue:"Component",G=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${G} \xB7 ${Ie}`}else u.textContent="Artifacts";if(te.artifactType==="markdown"){if(s&&x==="source"){let ce=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ce.textContent=(ie=te.markdown)!=null?ie:"",Le.appendChild(ce);return}let Ie=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ie.innerHTML=d((re=te.markdown)!=null?re:""),Le.appendChild(Ie);return}let se=te.component?lo.get(te.component):void 0;if(se){let ce={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let G=se((Qe=te.props)!=null?Qe:{},ce);if(G){Le.appendChild(G);return}}catch{}}Le.appendChild(sb(te))},le=()=>{var te;let Q=He.length>0;if(m.classList.toggle("persona-hidden",!Q),l){let se=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,ie=((te=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Q&&ie&&Pe?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(Q){var te,se,ue;He=Q.artifacts,ee=(ue=(se=Q.selectedId)!=null?se:(te=Q.artifacts[Q.artifacts.length-1])==null?void 0:te.id)!=null?ue:null,He.length>0&&(Pe=!0),V(),le()},setMobileOpen(Q){Pe=Q,!Q&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):le()}}}function ir(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Nu(e,t){var o,a,i,d;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"),!ir(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function ab(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")}function ii(e,t){var d,l,p,m,g,u,v,x,C,T;if(!ir(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"),ab(e),Nu(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=n==null?void 0:n.paneBackground)==null?void 0:u.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(C=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Nu(e,t)}var Fu=["panel","seamless"];function li(e,t){var i,d,l,p,m,g;for(let u of Fu)e.classList.remove(`persona-artifact-appearance-${u}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!ir(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",s=Fu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Ou(e,t){var n,r,s;return!t||!ir(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function ib(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function lb(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function cb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function db(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function $u(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function _u(e,t,n,r,s,o){let a=ib(s,200),i=db(t,n,r,200);i=Math.max(a,i);let d=lb(o);return d!==null&&(i=Math.min(i,d)),cb(e,a,i)}var ju={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},nl=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,C;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=ju[a])!=null?x:ju.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=h("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var w,I;let H=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");H.htmlFor=`${t.id}-${a}-${T.name}`;let L=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=T.label,H.appendChild(L);let P=(w=T.type)!=null?w:"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),W.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",W.id=`${t.id}-${a}-${T.name}`,W.name=T.name,W.placeholder=(I=T.placeholder)!=null?I:"",T.required&&(W.required=!0),H.appendChild(W),p.appendChild(H)});let m=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=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");u.type="submit",u.textContent=(C=i.submitLabel)!=null?C:"Submit",m.appendChild(g),m.appendChild(u),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async T=>{var W,w;T.preventDefault();let H=(W=n.formEndpoint)!=null?W:"/form",L=new FormData(p),P={};L.forEach((I,O)=>{P[O]=I}),P.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let I=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let O=await I.json();g.textContent=(w=O.message)!=null?w:"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await r.sendMessage(String(O.nextPrompt))}catch(I){g.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var rl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},ci=new rl;var Uu=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var pb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ub=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},di=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=pb(e),n=ub(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},ol=e=>typeof e=="string"?e:e==null?"":String(e),ns={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ol(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=ol(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ol(n.text)}}},qu=e=>Array.isArray(e)?e.map(t=>String(t)):[],pi=e=>{let t=new Set(qu(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(qu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var mb=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},gb=e=>e.map(t=>({...t,streaming:!1})),fb=e=>e.map(t=>({...t,status:"complete"})),sl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?mb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?gb(n.messages):void 0,artifacts:n.artifacts?fb(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as hb,STR as yb,OBJ as bb}from"partial-json";function xb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function vb(e,t){if(!xb(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function al(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=hb(n,yb|bb),o=vb(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function wb(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function il(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=lo.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Cb(){let e=al();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function zu(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 ll(e){let t=zu(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 cl(e){let t=zu(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 r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Ab=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function dl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Ab}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,u.appendChild(x),g.appendChild(u);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let w=1;w<=5;w++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),I.title=l[w-1],I.dataset.rating=String(w),I.innerHTML=`
23
+ `,n.addEventListener("click",t);let r=o=>{var M,L,I,A,P,F,B,W,U,V,oe,We,Je;let a=(M=o.launcher)!=null?M:{},i=un(o),d=n.querySelector("[data-role='launcher-title']");if(d){let ve=(L=a.title)!=null?L:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ve=(I=a.subtitle)!=null?I:"Get answers fast";l.textContent=ve,l.setAttribute("title",ve)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ve=(A=a.agentIconSize)!=null?A:"40px";if(u.style.height=ve,u.style.width=ve,u.innerHTML="",a.agentIconName){let Re=parseFloat(ve)||24,he=Ce(a.agentIconName,Re*.6,"var(--persona-text-inverse, #ffffff)",2);he?(u.appendChild(he),u.style.display=""):(u.textContent=(P=a.agentIconText)!=null?P:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ve=(B=a.agentIconSize)!=null?B:"40px";f.style.height=ve,f.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ve=(W=a.callToActionIconSize)!=null?W:"32px";m.style.height=ve,m.style.width=ve,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Re=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Re=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let he=parseFloat(ve)||24,He=Math.max(he-Re,8),Le=Ce(a.callToActionIconName,He,"currentColor",2);Le?m.appendChild(Le):m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&Sr[a.position]?Sr[a.position]:Sr["bottom-right"],x="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",w="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?w:`${x} ${v}`,i||(n.style.zIndex=String((oe=a.zIndex)!=null?oe:vn));let S="1px solid var(--persona-border, #e5e7eb)",H="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=(We=a.border)!=null?We:S,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:H,i?(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=(Je=a.collapsedMaxWidth)!=null?Je:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var Qh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ja=(e,t={})=>{var x,w,S,H,M,L;let{showClose:n=!0,wrapperClassName:r=Qh,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(w=s!=null?s:a.closeButtonSize)!=null?w:"32px",d=h("div",r),l=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");l.style.height=i,l.style.width=i,l.type="button";let p=(S=a.closeButtonTooltipText)!=null?S:"Close chat",u=(H=a.closeButtonShowTooltip)!=null?H:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(M=a.closeButtonIconName)!=null?M:"x",m=(L=a.closeButtonIconText)!=null?L:"\xD7";l.style.color=a.closeButtonColor||kn.actionIconColor;let v=Ce(f,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let I=a.closeButtonBorderWidth||"0px",A=a.closeButtonBorderColor||"transparent";l.style.border=`${I} solid ${A}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&p){let I=null,A=()=>{if(I)return;let F=l.ownerDocument,B=F.body;if(!B)return;I=Lr(F,"div","persona-clear-chat-tooltip"),I.textContent=p;let W=Lr(F,"div");W.className="persona-clear-chat-tooltip-arrow",I.appendChild(W);let U=l.getBoundingClientRect();I.style.position="fixed",I.style.zIndex=String(oo),I.style.left=`${U.left+U.width/2}px`,I.style.top=`${U.top-8}px`,I.style.transform="translate(-50%, -100%)",B.appendChild(I)},P=()=>{I&&I.parentNode&&(I.parentNode.removeChild(I),I=null)};d.addEventListener("mouseenter",A),d.addEventListener("mouseleave",P),l.addEventListener("focus",A),l.addEventListener("blur",P),d._cleanupTooltip=()=>{P(),d.removeEventListener("mouseenter",A),d.removeEventListener("mouseleave",P),l.removeEventListener("focus",A),l.removeEventListener("blur",P)}}return{button:l,wrapper:d}},Yh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ga=(e,t={})=>{var I,A,P,F,B,W,U,V,oe,We,Je,ve,Re;let{wrapperClassName:n=Yh,buttonSize:r,iconSize:s="20px"}=t,a=(A=((I=e==null?void 0:e.launcher)!=null?I:{}).clearChat)!=null?A:{},i=(P=r!=null?r:a.size)!=null?P:"32px",d=(F=a.iconName)!=null?F:"refresh-cw",l=(B=a.iconColor)!=null?B:"",p=(W=a.backgroundColor)!=null?W:"",u=(U=a.borderWidth)!=null?U:"",f=(V=a.borderColor)!=null?V:"",m=(oe=a.borderRadius)!=null?oe:"",v=(We=a.paddingX)!=null?We:"",x=(Je=a.paddingY)!=null?Je:"",w=(ve=a.tooltipText)!=null?ve:"Clear chat",S=(Re=a.showTooltip)!=null?Re:!0,H=h("div",n),M=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");M.style.height=i,M.style.width=i,M.type="button",M.setAttribute("aria-label",w),M.style.color=l||kn.actionIconColor;let L=Ce(d,s,"currentColor",1);if(L&&(L.style.display="block",M.appendChild(L)),p&&(M.style.backgroundColor=p,M.classList.remove("hover:persona-bg-gray-100")),u||f){let he=u||"0px",He=f||"transparent";M.style.border=`${he} solid ${He}`,M.classList.remove("persona-border-none")}if(m&&(M.style.borderRadius=m,M.classList.remove("persona-rounded-full")),v&&(M.style.paddingLeft=v,M.style.paddingRight=v),x&&(M.style.paddingTop=x,M.style.paddingBottom=x),H.appendChild(M),S&&w){let he=null,He=()=>{if(he)return;let K=M.ownerDocument,pe=K.body;if(!pe)return;he=Lr(K,"div","persona-clear-chat-tooltip"),he.textContent=w;let z=Lr(K,"div");z.className="persona-clear-chat-tooltip-arrow",he.appendChild(z);let ce=M.getBoundingClientRect();he.style.position="fixed",he.style.zIndex=String(oo),he.style.left=`${ce.left+ce.width/2}px`,he.style.top=`${ce.top-8}px`,he.style.transform="translate(-50%, -100%)",pe.appendChild(he)},Le=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};H.addEventListener("mouseenter",He),H.addEventListener("mouseleave",Le),M.addEventListener("focus",He),M.addEventListener("blur",Le),H._cleanupTooltip=()=>{Le(),H.removeEventListener("mouseenter",He),H.removeEventListener("mouseleave",Le),M.removeEventListener("focus",He),M.removeEventListener("blur",Le)}}return{button:M,wrapper:H}};var kn={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=e=>{var I,A,P,F,B,W,U,V,oe,We,Je,ve,Re,he,He,Le;let{config:t,showClose:n=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(I=t==null?void 0:t.launcher)!=null?I:{},o=(A=s.headerIconSize)!=null?A:"48px",a=(P=s.closeButtonPlacement)!=null?P:"inline",i=(F=s.headerIconHidden)!=null?F:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let K=parseFloat(o)||24,pe=Ce(d,K*.6,"currentColor",1);pe?l.replaceChildren(pe):l.textContent=(W=(B=t==null?void 0:t.launcher)==null?void 0:B.agentIconText)!=null?W:"\u{1F4AC}"}else if((U=t==null?void 0:t.launcher)!=null&&U.iconUrl){let K=h("img");K.src=t.launcher.iconUrl,K.alt="",K.className="persona-rounded-xl persona-object-cover",K.style.height=o,K.style.width=o,l.replaceChildren(K)}else l.textContent=(oe=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?oe:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=h("span","persona-text-base persona-font-semibold");u.style.color=kn.titleColor,u.textContent=(Je=(We=t==null?void 0:t.launcher)==null?void 0:We.title)!=null?Je:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=kn.subtitleColor,f.textContent=(Re=(ve=t==null?void 0:t.launcher)==null?void 0:ve.subtitle)!=null?Re:"Here to help you get answers fast",p.append(u,f),i?r.append(p):r.append(l,p);let m=(he=s.clearChat)!=null?he:{},v=(He=m.enabled)!=null?He:!0,x=(Le=m.placement)!=null?Le:"inline",w=null,S=null;if(v){let pe=Ga(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=pe.button,S=pe.wrapper,x==="top-right"&&(S.style.right="48px"),x==="inline"&&r.appendChild(S)}let H=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="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:L}=Ja(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&r.appendChild(L),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:M,closeButtonWrapper:L,clearChatButton:w,clearChatButtonWrapper:S}},ts=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Wo(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(oo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let w=document.createElement("hr");a.appendChild(w)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let w=Ce(m.icon,16,"currentColor",1.5);w&&v.appendChild(w)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",w=>{w.stopPropagation(),p(),n(m.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function Kt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ce(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Xa(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=Ce(t,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let u=h("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function Qa(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Kt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=h("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),o.appendChild(u)}function l(p){a=p,d()}return{element:o,setSelected:l}}function Vi(e){var m,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=Ce(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,w;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(w=d.border)!=null?w:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Wo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let w=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",w?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var du=e=>{var r;let t=io({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function Zh(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=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(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=Ce(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=Wo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var pu=e=>{var H,M,L,I,A,P,F,B,W;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(H=t==null?void 0:t.launcher)!=null?H:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,p;if(d)l=Vi({label:(M=a.title)!=null?M:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=kn.titleColor,p=(L=l.querySelector(".persona-combo-btn-label"))!=null?L:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=kn.titleColor,p.textContent=(I=a.title)!=null?I:"Chat Assistant",l.appendChild(p),Zh(l,s==null?void 0:s.trailingActions,(A=s==null?void 0:s.onAction)!=null?A:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=s.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||V()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),V())})}let U=s==null?void 0:s.titleRowHover;U&&(l.style.borderRadius=(P=U.borderRadius)!=null?P:"10px",l.style.padding=(F=U.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,oe;l.style.backgroundColor=(V=U.background)!=null?V:"",l.style.borderColor=(oe=U.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(B=a.closeButtonSize)!=null?B:"32px",f=h("div",""),m=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");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||kn.actionIconColor;let v=(W=a.closeButtonIconName)!=null?W:"x",x=Ce(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let w=h("div");w.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:w,headerTitle:p,headerSubtitle:S,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Ki={default:du,minimal:pu},uu=e=>{var t;return(t=Ki[e])!=null?t:Ki.default},Qs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=h("div");p.style.display="none";let u=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=uu(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Ya=e=>{var a,i;let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"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-primary 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,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}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:o}},Za=e=>{var I,A,P,F,B,W,U,V,oe,We,Je,ve;let t=(I=e==null?void 0:e.sendButton)!=null?I:{},n=(A=t.useIcon)!=null?A:!1,r=(P=t.iconText)!=null?P:"\u2191",s=t.iconName,o=(F=t.stopIconName)!=null?F:"square",a=(B=t.tooltipText)!=null?B:"Send message",i=(W=t.stopTooltipText)!=null?W:"Stop generating",d=(V=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?V:"Send",l=(We=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?We:"Stop",p=(Je=t.showTooltip)!=null?Je:!1,u=(ve=t.size)!=null?ve:"40px",f=t.backgroundColor,m=t.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let w=null,S=null;if(n){x.style.width=u,x.style.height=u,x.style.minWidth=u,x.style.minHeight=u,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let Re=parseFloat(u)||24,he=(m==null?void 0:m.trim())||"currentColor";s?(w=Ce(s,Re,he,2),w?x.appendChild(w):x.textContent=r):x.textContent=r,S=Ce(o,Re,he,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let H=null;p&&a&&(H=h("div","persona-send-button-tooltip"),H.textContent=a,v.appendChild(H)),x.setAttribute("aria-label",a),v.appendChild(x);let M="send";return{button:x,wrapper:v,setMode:Re=>{if(Re===M)return;M=Re;let he=Re==="stop"?i:a;if(x.setAttribute("aria-label",he),H&&(H.textContent=he),n){if(w&&S){let He=Re==="stop"?S:w;x.replaceChildren(He)}}else x.textContent=Re==="stop"?l:d}}},ei=e=>{var H,M,L,I,A,P,F,B,W,U,V,oe;let t=(H=e==null?void 0:e.voiceRecognition)!=null?H:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((M=t.provider)==null?void 0:M.type)==="runtype";if(!(r||s))return null;let a=(I=(L=e==null?void 0:e.sendButton)==null?void 0:L.size)!=null?I:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(A=t.iconName)!=null?A:"mic",p=(P=t.iconSize)!=null?P:a,u=parseFloat(p)||24,f=(B=t.backgroundColor)!=null?B:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,m=(U=t.iconColor)!=null?U:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=Ce(l,u,m||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let w=(V=t.tooltipText)!=null?V:"Start voice recognition";if(((oe=t.showTooltip)!=null?oe:!1)&&w){let We=h("div","persona-send-button-tooltip");We.textContent=w,i.appendChild(We)}return{button:d,wrapper:i}},ti=e=>{var v,x,w,S,H,M,L,I;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(w=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?w:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((S=t.allowedTypes)!=null?S:$r).join(","),s.multiple=((H=t.maxFiles)!=null?H:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(M=t.buttonTooltipText)!=null?M:"Attach file");let i=(L=t.buttonIconName)!=null?L:"paperclip",d=n,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let u=Ce(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",A=>{A.preventDefault(),s.click()}),o.appendChild(a);let f=(I=t.buttonTooltipText)!=null?I:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,o.appendChild(m),{button:a,wrapper:o,input:s,previewsContainer:r}},ni=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=h("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},ri=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ys=e=>{var v,x,w,S,H,M;let{config:t}=e,n=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let r=ri(),s=h("form","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");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Ya(t);a();let i=Za(t),d=ei(t),l=ti(t),p=ni(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let u=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),u.append(f,m),s.append(u),s.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(l==null?void 0:l.button)&&L.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(H=l==null?void 0:l.input)!=null?H:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var mu=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=h("span","persona-pill-peek__icon"),n=Ce("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=Ce("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},gu=e=>{var v,x,w,S,H,M;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=ri();r.style.display="none";let s=ni(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Ya(t);o.style.maxHeight="100px",a();let i=Za(t),d=ei(t),l=ti(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(l==null?void 0:l.button)&&L.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(u,o,f),l&&n.append(l.previewsContainer),n.append(p,r,s);let m=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(H=l==null?void 0:l.input)!=null?H:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var fu=e=>{var p,u,f,m,v,x,w,S,H,M,L,I,A,P,F,B,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=un(e);if(ao(e)){let U=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},V=h("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=U.expandedSize)!=null?v:"anchored",V.style.zIndex=String((w=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?w:vn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",V.appendChild(oe);let We=h("div","persona-widget-pill-root");return We.setAttribute("data-persona-composer-bar",""),We.dataset.state="collapsed",We.dataset.expandedSize=(S=U.expandedSize)!=null?S:"anchored",We.style.zIndex=String((M=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?M:vn),{wrapper:V,panel:oe,pillRoot:We}}if(n){let U=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(V),{wrapper:U,panel:V}}if(!t){let U=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(I=(L=e==null?void 0:e.launcher)==null?void 0:L.width)!=null?I:"100%";return U.style.width=oe,V.style.width="100%",U.appendChild(V),{wrapper:U,panel:V}}let s=(A=e==null?void 0:e.launcher)!=null?A:{},o=s.position&&Sr[s.position]?Sr[s.position]:Sr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((F=(P=e==null?void 0:e.launcher)==null?void 0:P.zIndex)!=null?F:vn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(B=e==null?void 0:e.launcher)==null?void 0:B.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:pr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},eb=(e,t)=>{var L,I,A,P,F,B,W,U,V;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:r,wrapper:s}=Ja(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(A=(I=(L=e==null?void 0:e.launcher)==null?void 0:L.clearChat)==null?void 0:I.enabled)!=null?A:!0,a=null,i=null;if(o){let oe=Ga(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","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");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let u=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(F=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeTitle)!=null?F:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(W=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",p.append(u,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,m);let w=h("div","persona-composer-overlay persona-pointer-events-none");w.setAttribute("data-persona-composer-overlay",""),w.style.position="absolute",w.style.left="0",w.style.right="0",w.style.bottom="0",w.style.zIndex="20";let S=gu({config:e}),{root:H,textNode:M}=mu();return n.append(d,s,l,w),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:w,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,introTitle:u,introSubtitle:f,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode,peekBanner:H,peekTextNode:M}},hu=(e,t=!0)=>{var w,S,H,M,L,I,A,P,F;if(ao(e))return eb(e,t);let n=h("div","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");n.setAttribute("data-persona-theme-zone","container");let r=(w=e==null?void 0:e.layout)==null?void 0:w.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=r?Qs(e,r,{showClose:t}):io({config:e,showClose:t}),a=h("div","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");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=un(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(M=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?M:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(I=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),u=(A=e==null?void 0:e.layout)==null?void 0:A.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((P=e==null?void 0:e.copy)==null?void 0:P.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let m=Ys({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;s?ts(n,o,e):(o.header.style.display="none",ts(n,o,e)),n.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(m.footer.style.display="none"),n.append(m.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var tb=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}},nb=(e,t)=>{if(!e)return null;let n=tb(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},rb=(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},ob=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Ji=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(":"))},Gi=320,yu=320,sb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),ab=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),lb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),cb=(e,t,n)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=h("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Gi}px`,l.style.maxHeight=`${yu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),ob(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},db=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(r=>{if(!Ji(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Gi}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},pb=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(r=>{if(!Ji(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Gi}px`,s.style.maxHeight=`${yu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ub=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(r=>{if(!Ji(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ns=()=>{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 r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},xu=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ns};if(t){let s=t(r);if(s!==null)return s}return ns()},mb=(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"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,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},bu=(e,t)=>{let n=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},gb=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];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-primary","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-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"),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-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},vu=(e,t,n)=>{var m,v,x,w,S,H;let r=(m=t.showCopy)!=null?m:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let M=h("div");return M.style.display="none",M.id=`actions-${e.id}`,M.setAttribute("data-actions-for",e.id),M}let a=(w=t.visibility)!=null?w:"hover",i=(S=t.align)!=null?S:"right",d=(H=t.layout)!=null?H:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(M,L,I)=>{let A=Kt({icon:M,label:L,size:14,className:"persona-message-action-btn"});return A.setAttribute("data-action",I),A};return r&&u.appendChild(f("copy","Copy message","copy")),s&&u.appendChild(f("thumbs-up","Upvote","upvote")),o&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},Zs=(e,t,n,r,s,o)=>{var K,pe,z,ce,ie,se,Ae,qe,Q,te,le,ye,ue,re,Ye,Ie,ge;let a=n!=null?n:{},i=(K=a.layout)!=null?K:"bubble",d=a.avatar,l=a.timestamp,p=(pe=d==null?void 0:d.show)!=null?pe:!1,u=(z=l==null?void 0:l.show)!=null?z:!1,f=(ce=d==null?void 0:d.position)!=null?ce:"left",m=(ie=l==null?void 0:l.position)!=null?ie:"below",v=gb(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let w=sb(e),S=(Ae=(se=e.content)==null?void 0:se.trim())!=null?Ae:"",M=w.length>0&&S===Ia,L=qa((Q=(qe=o==null?void 0:o.widgetConfig)==null?void 0:qe.features)==null?void 0:Q.streamAnimation),I=(ye=(le=(te=o==null?void 0:o.widgetConfig)==null?void 0:te.features)==null?void 0:le.streamAnimation)==null?void 0:ye.plugins,A=e.role==="assistant"&&L.type!=="none"?Vs(L.type,I):null,P=e.role==="assistant"&&((ue=A==null?void 0:A.isAnimating)==null?void 0:ue.call(A,e))===!0,F=e.role==="assistant"&&A!==null&&(!!e.streaming||P);F&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let B=document.createElement("div");B.classList.add("persona-message-content"),F&&A&&(A.containerClass&&B.classList.add(A.containerClass),B.style.setProperty("--persona-stream-step",`${L.speed}ms`),B.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let W=F?za((re=e.content)!=null?re:"",L.buffer,A,e,!!e.streaming):(Ye=e.content)!=null?Ye:"",U=t({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=U;F&&(A==null?void 0:A.wrap)==="char"?V=Ks(U,"char",e.id,{skipTags:A.skipTags}):F&&(A==null?void 0:A.wrap)==="word"&&(V=Ks(U,"word",e.id,{skipTags:A.skipTags}));let oe=null;if(M?(oe=document.createElement("div"),oe.innerHTML=V,oe.style.display="none",B.appendChild(oe)):B.innerHTML=V,F&&(A!=null&&A.useCaret)&&!M&&S){let G=Va(),Fe=B.querySelectorAll(".persona-stream-char, .persona-stream-word"),Rt=Fe[Fe.length-1];if(Rt!=null&&Rt.parentNode)Rt.parentNode.insertBefore(G,Rt.nextSibling);else{let fe=B.lastElementChild;fe?fe.appendChild(G):B.appendChild(G)}}if(u&&m==="inline"&&e.createdAt){let G=bu(e,l);G.classList.add("persona-ml-2","persona-inline"),B.appendChild(G)}if(w.length>0){let G=cb(w,!M&&!!S,()=>{M&&oe&&(oe.style.display="")});G?x.appendChild(G):M&&oe&&(oe.style.display="")}let We=ab(e);if(We.length>0){let G=db(We);G&&x.appendChild(G)}let Je=ib(e);if(Je.length>0){let G=pb(Je);G&&x.appendChild(G)}let ve=lb(e);if(ve.length>0){let G=ub(ve);G&&x.appendChild(G)}if(x.appendChild(B),u&&m==="below"&&e.createdAt){let G=bu(e,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let Re=e.role==="assistant"?nb(e.stopReason,(ge=(Ie=o==null?void 0:o.widgetConfig)==null?void 0:Ie.copy)==null?void 0:ge.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(W&&W.trim()),Fe=L.placeholder==="skeleton",Rt=Fe&&L.buffer==="line"&&G;if(G)Rt&&x.appendChild(Js());else if(Fe)x.appendChild(Js());else{let fe=xu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);fe&&x.appendChild(fe)}}if(Re&&e.stopReason&&!e.streaming&&(S||(B.style.display="none"),x.appendChild(rb(e.stopReason,Re))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let G=vu(e,r,s);x.appendChild(G)}if(!p||e.role==="system")return x;let He=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Le=mb(d,e.role);return f==="right"||f==="left"&&e.role==="user"?He.append(x,Le):He.append(Le,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),He},fb=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Zs(e,t,n,r,s,o)};var rs=new Set,hb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),bb=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
24
+ `):""},wu=(e,t)=>{let n=rs.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ce(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},Xi=(e,t)=>{var Je,ve,Re,he,He,Le,K,pe,z,ce,ie;let n=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(ve=(Je=t==null?void 0:t.features)==null?void 0:Je.reasoningDisplay)!=null?ve:{},o=s.expandable!==!1,a=o&&rs.has(e.id),i=n.status!=="complete",d=bb(e,(Re=s.previewMaxLines)!=null?Re:3),l=h("button",o?"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");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(he=t==null?void 0:t.reasoning)!=null?he:{},v=String((He=n.startedAt)!=null?He:Date.now()),x=()=>{let se=h("span","");return se.setAttribute("data-tool-elapsed",v),se.textContent=Ma(n),se},w=(Le=m.renderCollapsedSummary)==null?void 0:Le.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ma(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(u.textContent=w,p.appendChild(u)):w instanceof HTMLElement?p.appendChild(w):(u.textContent=f,p.appendChild(u));let S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=Np(n),p.appendChild(S);let H=(K=s.loadingAnimation)!=null?K:"none",M=m.activeTextTemplate,L=m.completeTextTemplate,I=i?M:L,A=w instanceof HTMLElement,P=(se,Ae,qe)=>{let Q=qe;for(let te of Ae){let le=h("span","persona-tool-char");le.style.setProperty("--char-index",String(Q)),le.textContent=te===" "?"\xA0":te,se.appendChild(le),Q++}return Q},F=(se,Ae)=>{u.textContent="";let qe=ka(se,""),Q=0;for(let te of qe){let le=te.styles.length>0?(()=>{let ye=h("span",te.styles.map(ue=>`persona-tool-text-${ue}`).join(" "));return u.appendChild(ye),ye})():u;if(te.isDuration&&i)le.appendChild(x());else{let ye=te.isDuration?Ma(n):te.text;Ae?Q=P(le,ye,Q):le.appendChild(document.createTextNode(ye))}}};if(!A&&I)if(S.style.display="none",u.style.display="",i&&H!=="none"){let se=(pe=m.loadingAnimationDuration)!=null?pe:2e3;u.setAttribute("data-preserve-animation","true"),H==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${se}ms`),F(I,!1)):(u.classList.add(`persona-tool-loading-${H}`),u.style.setProperty("--persona-tool-anim-duration",`${se}ms`),H==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),F(I,!0))}else F(I,!1);else if(!A&&i&&H!=="none"){u.style.display="";let se=(z=m.loadingAnimationDuration)!=null?z:2e3;if(u.setAttribute("data-preserve-animation","true"),H==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${se}ms`);else{u.classList.add(`persona-tool-loading-${H}`),u.style.setProperty("--persona-tool-anim-duration",`${se}ms`),H==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let Ae=u.textContent||f;u.textContent="",P(u,Ae,0)}n.status==="complete"&&(u.style.display="none")}else A||(n.status==="complete"?u.style.display="none":u.style.display="");let B=null;if(o){B=h("div","persona-flex persona-items-center");let Ae=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);Ae?B.appendChild(Ae):B.textContent=a?"Hide":"Show";let qe=h("div","persona-flex persona-items-center persona-ml-auto");qe.append(B),l.append(p,qe)}else l.append(p);let W=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let se=(ie=(ce=t==null?void 0:t.reasoning)==null?void 0:ce.renderCollapsedPreview)==null?void 0:ie.call(ce,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});hb(W,se)||(W.textContent=d),W.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,W),r;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");U.style.display=a?"":"none";let V=n.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=V||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),B){B.innerHTML="";let Ae=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);Ae?B.appendChild(Ae):B.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(l,W,U),r};var os=new Set,yb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),xb=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
+ `);let s=Go(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},vb=(e,t)=>{var p,u,f,m,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",o=xb(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Op(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return s==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Li(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Li(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Cu=(e,t,n)=>{var p;let r=os.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=s.toggleTextColor||s.headerTextColor||"currentColor",f=Ce(r?"chevron-up":"chevron-down",16,u,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Qi=(e,t)=>{var V,oe,We,Je,ve,Re,he,He,Le;let n=e.toolCall,r=(V=t==null?void 0:t.toolCall)!=null?V:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let o=(We=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?We:{},a=o.expandable!==!1,i=a&&os.has(e.id),{summary:d,previewText:l,isActive:p}=vb(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",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((Je=n.startedAt)!=null?Je:Date.now()),x=()=>{let K=h("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Hs(n),K},w=(Re=r.renderCollapsedSummary)==null?void 0:Re.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ve=o.collapsedMode)!=null?ve:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Hs(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(m.textContent=w,f.appendChild(m)):w instanceof HTMLElement?f.appendChild(w):(m.textContent=d,f.appendChild(m));let S=(he=o.loadingAnimation)!=null?he:"none",H=r.activeTextTemplate,M=r.completeTextTemplate,L=p?H:M,I=w instanceof HTMLElement,A=(K,pe,z)=>{let ce=z;for(let ie of pe){let se=h("span","persona-tool-char");se.style.setProperty("--char-index",String(ce)),se.textContent=ie===" "?"\xA0":ie,K.appendChild(se),ce++}return ce},P=(K,pe)=>{var se;m.textContent="";let z=((se=n.name)==null?void 0:se.trim())||"tool",ce=ka(K,z),ie=0;for(let Ae of ce){let qe=Ae.styles.length>0?(()=>{let Q=h("span",Ae.styles.map(te=>`persona-tool-text-${te}`).join(" "));return m.appendChild(Q),Q})():m;if(Ae.isDuration&&p)qe.appendChild(x());else{let Q=Ae.isDuration?Hs(n):Ae.text;pe?ie=A(qe,Q,ie):qe.appendChild(document.createTextNode(Q))}}};if(!I)if(p&&S!=="none"){let K=(He=r.loadingAnimationDuration)!=null?He:2e3;if(m.setAttribute("data-preserve-animation","true"),S==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),L&&P(L,!1);else if(m.classList.add(`persona-tool-loading-${S}`),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),L)P(L,!0);else{let pe=m.textContent||d;m.textContent="",A(m,pe,0)}}else L&&P(L,!1);let F=null;if(a){F=h("div","persona-flex persona-items-center");let K=r.toggleTextColor||r.headerTextColor||"currentColor",pe=Ce(i?"chevron-up":"chevron-down",16,K,2);pe?F.appendChild(pe):F.textContent=i?"Hide":"Show";let z=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");z.append(F),u.append(f,z)}else u.append(f);let B=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","tool"),B.style.display="none",B.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let K=(Le=r.renderCollapsedPreview)==null?void 0:Le.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});yb(B,K)||(B.textContent=l),B.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(u,B),s;let W=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",r.contentBackgroundColor&&(W.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(W.style.color=r.contentTextColor),r.contentPaddingX&&(W.style.paddingLeft=r.contentPaddingX,W.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(W.style.paddingTop=r.contentPaddingY,W.style.paddingBottom=r.contentPaddingY),n.name){let K=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?K.style.color=r.contentTextColor:r.headerTextColor&&(K.style.color=r.headerTextColor),K.textContent=n.name,W.appendChild(K)}if(n.args!==void 0){let K=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(pe.style.color=r.labelTextColor),pe.textContent="Arguments";let z=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");z.style.fontSize="0.75rem",z.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(z.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(z.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(z.style.color=r.codeBlockTextColor),z.textContent=Go(n.args),K.append(pe,z),W.appendChild(K)}if(n.chunks&&n.chunks.length){let K=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(pe.style.color=r.labelTextColor),pe.textContent="Activity";let z=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");z.style.fontSize="0.75rem",z.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(z.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(z.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(z.style.color=r.codeBlockTextColor),z.textContent=n.chunks.join(""),K.append(pe,z),W.appendChild(K)}if(n.status==="complete"&&n.result!==void 0){let K=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(pe.style.color=r.labelTextColor),pe.textContent="Result";let z=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");z.style.fontSize="0.75rem",z.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(z.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(z.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(z.style.color=r.codeBlockTextColor),z.textContent=Go(n.result),K.append(pe,z),W.appendChild(K)}if(n.status==="complete"&&typeof n.duration=="number"){let K=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(K.style.color=r.contentTextColor),K.textContent=`Duration: ${n.duration}ms`,W.appendChild(K)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let K=r.toggleTextColor||r.headerTextColor||"currentColor",pe=Ce(i?"chevron-up":"chevron-down",16,K,2);pe?F.appendChild(pe):F.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",B.style.display=i?"none":B.textContent||B.childNodes.length?"":"none"})(),s.append(u,B,W),s};import{parse as wb,ARR as Cb,OBJ as Ab,STR as Sb}from"partial-json";var Su="ask_user_question",Yi=8,ss="data-persona-ask-sheet-for",Tb="Other",Eb="Other\u2026",Tu="Type your own answer here",Eu="Send",Mb="Next",kb="Back",Lb="Submit all",Pb="Skip",Ib=3,Zi="data-ask-current-index",el="data-ask-question-count",Mu="data-ask-answers",tl="data-ask-grouped",ku="data-ask-layout",Wb=e=>e.layout==="pills"?"pills":"rows",Rb=e=>e.getAttribute(ku)==="pills"?"pills":"rows",Au=!1,Lu=e=>e.replace(/["\\]/g,"\\$&"),lo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Su,oi=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},co=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 r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=wb(s,Sb|Ab|Cb);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},ea=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Yi&&!Au&&(Au=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Yi}.`)),t.slice(0,Yi)},Hb=e=>{var t;return(t=ea(e)[0])!=null?t:null},Bb=(e,t)=>{var n;return(n=ea(e)[t])!=null?n:null},Pu=(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))},Iu=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Db=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Iu(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Nb=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},Ob=(e,t,n,r)=>{var p,u,f;let o=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");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<Ib;m++)o.appendChild(Nb(r));return o}if(d.forEach((m,v)=>{o.appendChild(Db(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?Tb:Eb;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),w=document.createElement("input");w.type="text",w.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",w.placeholder=(p=t.freeTextPlaceholder)!=null?p:Tu,w.setAttribute("data-ask-free-text-input","true"),w.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:m),x.appendChild(w),v.appendChild(x);let S=Iu(r,a,d.length);S&&v.appendChild(S),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=t.freeTextLabel)!=null?f:m,o.appendChild(v)}}return o},Wu=(e,t)=>{var o,a;let r=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");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:Tu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Eu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Fb=e=>{var r;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=(r=e.submitLabel)!=null?r:Eu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},$b=(e,t,n)=>{var l,p,u,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:kb,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=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=(p=n.skipLabel)!=null?p:Pb,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:Lb:(f=n.nextLabel)!=null?f:Mb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Ro=e=>{let t=e.getAttribute(Mu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Ru=(e,t)=>{e.setAttribute(Mu,JSON.stringify(t))},ur=e=>{var n;let t=Number((n=e.getAttribute(Zi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},_b=(e,t)=>{e.setAttribute(Zi,String(Math.max(0,Math.floor(t))))},as=e=>{var n;let t=Number((n=e.getAttribute(el))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},po=e=>e.getAttribute(tl)==="true",jb=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Ub=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},si=(e,t)=>{let{payload:n}=co(t),r=ea(n),s=Ro(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Hu=e=>{let t=Ro(e),n=ur(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Bu=e=>{if(!po(e))return;let t=Ro(e),n=ur(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},nl=(e,t,n)=>{let r=oi(n),s=Rb(e),{payload:o,complete:a}=co(t),i=po(e),d=ur(e),l=as(e),p=i?Bb(o,d):Hb(o),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let H=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=H,v.classList.toggle("persona-ask-question-skeleton",!H&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let H=Ob(p,r,a,s);x.replaceWith(H)}if(s!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(Wu(r,s))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(Fb(r)):(!u||i)&&w&&w.remove(),e.setAttribute("data-multi-select",u?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let H=$b(d,l,r);S?S.replaceWith(H):e.appendChild(H)}else S&&S.remove();Hu(e),Bu(e)},qb=(e,t,n)=>{let r=oi(t),s=Wb(r),o=e.toolCall.id,a=ea(n),i=Math.max(1,a.length),d=i>1,l=jb(e,a),p=d?Ub(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ss,o),u.setAttribute("data-tool-call-id",o),u.setAttribute("data-message-id",e.id),u.setAttribute(el,String(i)),u.setAttribute(Zi,String(p)),u.setAttribute(tl,d?"true":"false"),u.setAttribute(ku,s),Ru(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Pu(u,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=h("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),u.appendChild(f);let w=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),s!=="rows"&&u.appendChild(Wu(r,s)),nl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},zb=(e,t,n)=>{let{payload:r}=co(t),s=Math.max(1,ea(r).length);s>as(e)&&(e.setAttribute(el,String(s)),s>1&&!po(e)&&e.setAttribute(tl,"true")),nl(e,t,n)},Vb=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=oi(t);Pu(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=co(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},ta=(e,t,n)=>{if(!n||!lo(e)||oi(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${ss}]`).forEach(l=>{l.getAttribute(ss)!==s&&l.remove()});let a=n.querySelector(`[${ss}="${Lu(s)}"]`);if(a){zb(a,e,t);return}let{payload:i}=co(e),d=qb(e,t,i);n.appendChild(d)},Ho=(e,t)=>{if(!e)return;let n=t?`[${ss}="${Lu(t)}"]`:`[${ss}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},rl=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),uo=(e,t)=>{let n=Ro(e),r=ur(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Ru(e,n),Hu(e),Bu(e)},ai=(e,t,n,r)=>{let s=as(e),o=Math.max(0,Math.min(s-1,r));_b(e,o),nl(e,t,n)};var ii=new Map,Kb=e=>{let n=(e.startsWith(ro)?e.slice(ro.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Du=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Nu=(e,t)=>{var r,s,o;let n=(s=(r=Du(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=ii.get(e))!=null?o:n==="expanded"},Ou=(e,t,n)=>{var a,i;let r=Du(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let o=e.querySelector("[data-approval-details-chevron]");if(o){o.innerHTML="";let d=Ce(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},Fu=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=Nu(e,n);Ou(r,o,n),s.style.display=o?"":"none"};var li=(e,t)=>{var P,F,B,W,U,V,oe,We,Je,ve,Re,he,He,Le;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(P=r==null?void 0:r.backgroundColor)!=null?P:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(F=r==null?void 0:r.borderColor)!=null?F:"var(--persona-approval-border, #fef08a)",o.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(B=r==null?void 0:r.titleColor)!=null?B:"currentColor",p=Ce(d,20,l,2);p&&i.appendChild(p);let u=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(W=r==null?void 0:r.title)!=null?W:"Approval Required",f.appendChild(m),!s){let K=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");K.setAttribute("data-approval-status",n.status),n.status==="approved"?(K.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",K.style.color="var(--persona-palette-colors-success-700, #15803d)",K.textContent="Approved"):n.status==="denied"?(K.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",K.style.color="var(--persona-palette-colors-error-700, #b91c1c)",K.textContent="Denied"):n.status==="timeout"&&(K.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",K.style.color="var(--persona-palette-colors-warning-700, #b45309)",K.textContent="Timeout"),f.appendChild(K)}u.appendChild(f);let x=n.toolType==="webmcp"||n.toolName.startsWith(ro)?Mi(n.toolName):void 0,w=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{}}),S=!n.toolName,H=w||(S?n.description:`The assistant wants to use \u201C${x!=null?x:Kb(n.toolName)}\u201D.`),M=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");M.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(M.style.color=r.descriptionColor),M.textContent=H,u.appendChild(M);let L=(V=r==null?void 0:r.detailsDisplay)!=null?V:"collapsed",I=!!n.description&&!S,A=I||!!n.parameters;if(L!=="hidden"&&A){let K=Nu(e.id,t),pe=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");pe.type="button",pe.setAttribute("data-expand-header","true"),pe.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let z=h("span");z.setAttribute("data-approval-details-label","true");let ce=h("span","persona-inline-flex persona-items-center");ce.setAttribute("data-approval-details-chevron","true"),pe.append(z,ce),Ou(pe,K,t),u.appendChild(pe);let ie=h("div");if(ie.setAttribute("data-approval-details","true"),ie.style.display=K?"":"none",I){let se=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor),se.textContent=n.description,ie.appendChild(se)}if(n.parameters){let se=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");r!=null&&r.parameterBackgroundColor&&(se.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(se.style.color=r.parameterTextColor),se.style.fontSize="0.75rem",se.style.lineHeight="1rem",se.textContent=Go(n.parameters),ie.appendChild(se)}u.appendChild(ie)}if(s){let K=h("div","persona-flex persona-gap-2 persona-mt-2");K.setAttribute("data-approval-buttons","true");let pe=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");pe.type="button",pe.style.backgroundColor=(oe=r==null?void 0:r.approveButtonColor)!=null?oe:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(We=r==null?void 0:r.approveButtonTextColor)!=null?We:"#ffffff",pe.setAttribute("data-approval-action","approve");let z=Ce("shield-check",14,(Je=r==null?void 0:r.approveButtonTextColor)!=null?Je:"#ffffff",2);z&&(z.style.marginRight="4px",pe.appendChild(z));let ce=document.createTextNode((ve=r==null?void 0:r.approveLabel)!=null?ve:"Approve");pe.appendChild(ce);let ie=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");ie.type="button",ie.style.backgroundColor=(Re=r==null?void 0:r.denyButtonColor)!=null?Re:"transparent",ie.style.color=(he=r==null?void 0:r.denyButtonTextColor)!=null?he:"var(--persona-feedback-error, #dc2626)",ie.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ie.setAttribute("data-approval-action","deny");let se=Ce("shield-x",14,(He=r==null?void 0:r.denyButtonTextColor)!=null?He:"var(--persona-feedback-error, #dc2626)",2);se&&(se.style.marginRight="4px",ie.appendChild(se));let Ae=document.createTextNode((Le=r==null?void 0:r.denyLabel)!=null?Le:"Deny");ie.appendChild(Ae),K.append(pe,ie),u.appendChild(K)}return a.append(i,u),o.appendChild(a),o};var $u=e=>{let t=[];return{buttons:t,render:(r,s,o,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=s?s.isStreaming():!1,f=m=>{switch(m){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'}};r.forEach(m=>{let v=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");v.type="button",v.textContent=m,v.disabled=u,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var na=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){var n;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),(n=this.store)==null||n.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 r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.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(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ra=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 r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}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 r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}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(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Jb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Gb=new Set(["step_start","execution_start"]),Xb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Qb=new Set(["step_complete","agent_turn_complete"]),Yb=new Set(["flow_complete","agent_complete"]),_u=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Uu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Bo=(e,t)=>{let n=e[t];return Uu(n)?n:void 0};function ol(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ci(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Zb(e,t){return typeof t.type=="string"?t.type:e}function ey(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 ty(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 ju(e){var r,s,o,a,i;let t=Bo(e,"result"),n=[Bo(e,"tokens"),Bo(e,"totalTokens"),t?Bo(t,"tokens"):void 0,Bo(e,"usage"),t?Bo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?s:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Qn(e.outputTokens))!=null?o:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function ny(e){var n,r,s,o,a;let t=Bo(e,"result");return(a=(s=(r=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?r:Qn(e.execution_time))!=null?s:Qn(e.duration))!=null?a:t?(o=Qn(t.executionTime))!=null?o:Qn(t.executionTimeMs):void 0}function ry(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var oa=class{constructor(t=ry){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:ci(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){var o;if(!Uu(n)){_u.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Zb(t,n),s=this.now();if(Jb.has(r)){this.startRun(s);return}if(Gb.has(r)){this.run||this.startRun(s);return}if(Xb.has(r)){if(!ty(r,n))return;let a=ey(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+ol(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ci(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Qb.has(r)){if(!this.run)return;let a=this.run,i=ju(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+ol(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:ci(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Yb.has(r)){if(!this.run)return;let a=this.run,i=ju(n),d=i!=null?i:a.exactOutputTokens+ol(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:ci(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(_u.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=ny(n);return o!=null?o:r-t.startedAt}};function is(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var oy={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)"}},sy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ay=["flowName","stepName","reasoningText","text","name","tool","toolName"],iy=100;function ly(e,t){let n={...oy,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return sy}function cy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function dy(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function py(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function uy(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function my(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 gy(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function fy(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 hy(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=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]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function sl(e,t,n,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");is(l,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var V,oe;let m=h("div",""),v=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");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),w=Ce(d?"chevron-down":"chevron-right","14px","currentColor",2);w&&x.appendChild(w);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),H=(V=r.timestampFormat)!=null?V:"relative";S.textContent=H==="relative"?cy(e.timestamp,n):dy(e.timestamp);let M=null;r.showSequenceNumbers!==!1&&(M=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let L=ly(e.type,r.badgeColors),I=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");I.style.backgroundColor=L.bg,I.style.color=L.text,I.style.borderColor=L.text+"50",I.textContent=e.type;let A=(oe=r.descriptionFields)!=null?oe:ay,P=py(e.payload,A),F=null;P&&(F=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=P);let B=h("div","persona-flex-1 persona-min-w-0"),W=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"),U=Ce("clipboard","12px","currentColor",1.5);return U&&W.appendChild(U),W.addEventListener("click",async We=>{We.stopPropagation(),await uy(my(e)),W.innerHTML="";let Je=Ce("check","12px","currentColor",1.5);Je&&W.appendChild(Je),setTimeout(()=>{W.innerHTML="";let ve=Ce("clipboard","12px","currentColor",1.5);ve&&W.appendChild(ve)},1500)}),v.appendChild(x),v.appendChild(S),M&&v.appendChild(M),v.appendChild(I),F&&v.appendChild(F),v.appendChild(B),v.appendChild(W),m.appendChild(v),d&&m.appendChild(hy(e,a,i)),m}}function qu(e){var v,x,w,S,H;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(w=i==null?void 0:i.label)!=null?w:"",u=(H=(S=s==null?void 0:s.features)==null?void 0:S.eventStream)!=null?H:{},f=o.find(M=>M.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let M=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return m();function m(){let M=u.classNames,L=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");is(L,M==null?void 0:M.panel);let I=[],A="",P="",F=null,B=[],W={},U=0,V=_a(),oe=0,We=0,Je=!1,ve=null,Re=!1,he=0,He=new Set,Le=new Map,K="",pe="",z=null,ce,ie,se,Ae,qe,Q=null,te=null,le=null;function ye(){let ne=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),xe=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");is(xe,M==null?void 0:M.headerBar);let Tt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Tt.textContent="Events",ce=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"),ce.textContent="0",a){te=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),te.style.cursor="help";let Bn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Bn.textContent="Throughput",Q=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"),Q.textContent="-- tok/s",le=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"),le.style.display="none",le.style.pointerEvents="none";let Zn=te,Cn=le,Dn=()=>{if(!Cn.textContent)return;let Tr=Zn.getBoundingClientRect(),Nn=ne.getBoundingClientRect();Cn.style.left=`${Tr.left-Nn.left}px`,Cn.style.top=`${Tr.bottom-Nn.top+4}px`,Cn.style.display="block"},ht=()=>{Cn.style.display="none"};te.addEventListener("mouseenter",Dn),te.addEventListener("mouseleave",ht),te.appendChild(Bn),te.appendChild(Q)}let Vt=h("div","persona-flex-1");ie=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 tn=h("option","");tn.value="",tn.textContent="All events",ie.appendChild(tn),se=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"),se.type="button",se.title="Copy All";let It=Ce("clipboard-copy","12px","currentColor",1.5);It&&se.appendChild(It);let Mt=h("span","persona-text-xs");Mt.textContent="Copy All",se.appendChild(Mt),xe.appendChild(Tt),xe.appendChild(ce),te&&xe.appendChild(te),xe.appendChild(Vt),xe.appendChild(ie),xe.appendChild(se);let vt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");is(vt,M==null?void 0:M.searchBar);let Ct=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),Jt=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");Ct&&Jt.appendChild(Ct),Ae=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"),is(Ae,M==null?void 0:M.searchInput),Ae.type="text",Ae.placeholder="Search event payloads...",qe=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"),qe.type="button",qe.style.display="none";let rt=Ce("x","12px","currentColor",2);return rt&&qe.appendChild(rt),vt.appendChild(Jt),vt.appendChild(Ae),vt.appendChild(qe),ne.appendChild(xe),ne.appendChild(vt),le&&ne.appendChild(le),ne}let ue,re=o.find(ne=>ne.renderEventStreamToolbar);if(re!=null&&re.renderEventStreamToolbar&&s){let ne=re.renderEventStreamToolbar({config:s,defaultRenderer:()=>ye(),eventCount:t.getSize(),filteredCount:0,onFilterChange:xe=>{A=xe,Hn(),O()},onSearchChange:xe=>{P=xe,Hn(),O()}});ue=ne!=null?ne:ye()}else ue=ye();let Ye=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");Ye.style.display="none";function Ie(){if(!a||!Q||!te)return;let ne=a();Q.textContent=gy(ne);let xe=fy(ne);le&&(le.textContent=xe,xe||(le.style.display="none")),xe?te.setAttribute("aria-label",xe):te.removeAttribute("aria-label")}let ge=h("div","persona-flex-1 persona-min-h-0 persona-relative"),G=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let Fe=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");is(Fe,M==null?void 0:M.scrollIndicator),Fe.style.display="none",Fe.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Rt=Ce(l,"14px","currentColor",2);Rt&&Fe.appendChild(Rt);let fe=h("span","");fe.textContent=p,Fe.appendChild(fe);let de=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");de.style.display="none",ge.appendChild(G),ge.appendChild(de),ge.appendChild(Fe),L.setAttribute("tabindex","0"),L.appendChild(ue),L.appendChild(Ye),L.appendChild(ge);function Ln(){let ne=t.getAll(),xe={};for(let Mt of ne)xe[Mt.type]=(xe[Mt.type]||0)+1;let Tt=Object.keys(xe).sort(),Vt=Tt.length!==B.length||!Tt.every((Mt,vt)=>Mt===B[vt]),tn=!Vt&&Tt.some(Mt=>xe[Mt]!==W[Mt]),wn=ne.length!==Object.values(W).reduce((Mt,vt)=>Mt+vt,0);if(!Vt&&!tn&&!wn||(B=Tt,W=xe,!ie))return;let It=ie.value;if(ie.options[0].textContent="All events",Vt){for(;ie.options.length>1;)ie.remove(1);for(let Mt of Tt){let vt=h("option","");vt.value=Mt,vt.textContent=`${Mt} (${xe[Mt]||0})`,ie.appendChild(vt)}It&&Tt.includes(It)?ie.value=It:It&&(ie.value="",A="")}else for(let Mt=1;Mt<ie.options.length;Mt++){let vt=ie.options[Mt];vt.textContent=`${vt.value} (${xe[vt.value]||0})`}}function jt(){let ne=t.getAll();if(A&&(ne=ne.filter(xe=>xe.type===A)),P){let xe=P.toLowerCase();ne=ne.filter(Tt=>Tt.type.toLowerCase().includes(xe)||Tt.payload.toLowerCase().includes(xe))}return ne}function mn(){return A!==""||P!==""}function Hn(){U=0,oe=0,V.resume(),Fe.style.display="none"}function Yn(ne){He.has(ne)?He.delete(ne):He.add(ne),z=ne;let xe=G.scrollTop,Tt=V.isFollowing();Re=!0,V.pause(),O(),G.scrollTop=xe,Tt&&V.resume(),Re=!1}function je(){return Us(G,50)}function O(){We=Date.now(),Je=!1,Ie(),Ln();let ne=t.getEvictedCount();ne>0?(Ye.textContent=`${ne.toLocaleString()} older events truncated`,Ye.style.display=""):Ye.style.display="none",I=jt();let xe=I.length,Tt=t.getSize()>0;ce&&(ce.textContent=String(t.getSize())),xe===0&&Tt&&mn()?(de.textContent=P?`No events matching '${P}'`:"No events matching filter",de.style.display="",G.style.display="none"):(de.style.display="none",G.style.display=""),se&&(se.title=mn()?`Copy Filtered (${xe})`:"Copy All"),d&&!V.isFollowing()&&xe>U&&(oe+=xe-U,fe.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",Fe.style.display=""),U=xe;let Vt=t.getAll(),tn=Vt.length>0?Vt[0].timestamp:0,wn=new Set(I.map(vt=>vt.id));for(let vt of He)wn.has(vt)||He.delete(vt);let It=A!==K||P!==pe,Mt=Le.size===0&&I.length>0;if(It||Mt||I.length===0){G.innerHTML="",Le.clear();let vt=document.createDocumentFragment();for(let Ct=0;Ct<I.length;Ct++){let Jt=sl(I[Ct],Ct,tn,u,He,Yn,o,s);Le.set(I[Ct].id,Jt),vt.appendChild(Jt)}G.appendChild(vt),K=A,pe=P,z=null}else{if(z!==null){let Ct=Le.get(z);if(Ct&&Ct.parentNode===G){let Jt=I.findIndex(rt=>rt.id===z);if(Jt>=0){let rt=sl(I[Jt],Jt,tn,u,He,Yn,o,s);G.insertBefore(rt,Ct),Ct.remove(),Le.set(z,rt)}}z=null}let vt=new Set(I.map(Ct=>Ct.id));for(let[Ct,Jt]of Le)vt.has(Ct)||(Jt.remove(),Le.delete(Ct));for(let Ct=0;Ct<I.length;Ct++){let Jt=I[Ct];if(!Le.has(Jt.id)){let rt=sl(Jt,Ct,tn,u,He,Yn,o,s);Le.set(Jt.id,rt),G.appendChild(rt)}}}V.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Te(){if(Date.now()-We>=iy){ve!==null&&(cancelAnimationFrame(ve),ve=null),O();return}Je||(Je=!0,ve=requestAnimationFrame(()=>{ve=null,O()}))}let Be=(ne,xe)=>{if(!se)return;se.innerHTML="";let Tt=Ce(ne,"12px","currentColor",1.5);Tt&&se.appendChild(Tt);let Vt=h("span","persona-text-xs");Vt.textContent="Copy All",se.appendChild(Vt),setTimeout(()=>{se.innerHTML="";let tn=Ce("clipboard-copy","12px","currentColor",1.5);tn&&se.appendChild(tn);let wn=h("span","persona-text-xs");wn.textContent="Copy All",se.appendChild(wn),se.disabled=!1},xe)},De=async()=>{if(se){se.disabled=!0;try{let ne;mn()?ne=I:n?(ne=await n(),ne.length===0&&(ne=t.getAll())):ne=t.getAll();let xe=ne.map(Tt=>{try{return JSON.parse(Tt.payload)}catch{return Tt.payload}});await navigator.clipboard.writeText(JSON.stringify(xe,null,2)),Be("check",1500)}catch{Be("x",1500)}}},$e=()=>{ie&&(A=ie.value,Hn(),O())},ut=()=>{!Ae||!qe||(qe.style.display=Ae.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{P=Ae.value,Hn(),O()},150))},st=()=>{!Ae||!qe||(Ae.value="",P="",qe.style.display="none",F&&clearTimeout(F),Hn(),O())},Pt=()=>{if(Re)return;let ne=G.scrollTop,{action:xe,nextLastScrollTop:Tt}=ja({following:V.isFollowing(),currentScrollTop:ne,lastScrollTop:he,nearBottom:je(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=Tt,xe==="resume"?(V.resume(),oe=0,Fe.style.display="none"):xe==="pause"&&(V.pause(),d&&(fe.textContent=p,Fe.style.display=""))},zt=ne=>{let xe=Ua({following:V.isFollowing(),deltaY:ne.deltaY,nearBottom:je(),resumeWhenNearBottom:!0});xe==="pause"?(V.pause(),d&&(fe.textContent=p,Fe.style.display="")):xe==="resume"&&(V.resume(),oe=0,Fe.style.display="none")},q=()=>{d&&(G.scrollTop=G.scrollHeight,V.resume(),oe=0,Fe.style.display="none")},Ut=ne=>{let xe=ne.target;if(!xe||xe.closest("button"))return;let Tt=xe.closest("[data-event-id]");if(!Tt)return;let Vt=Tt.getAttribute("data-event-id");Vt&&Yn(Vt)},Ze=ne=>{if((ne.metaKey||ne.ctrlKey)&&ne.key==="f"){ne.preventDefault(),Ae==null||Ae.focus(),Ae==null||Ae.select();return}ne.key==="Escape"&&(Ae&&document.activeElement===Ae?(st(),Ae.blur(),L.focus()):r&&r())};se&&se.addEventListener("click",De),ie&&ie.addEventListener("change",$e),Ae&&Ae.addEventListener("input",ut),qe&&qe.addEventListener("click",st),G.addEventListener("scroll",Pt),G.addEventListener("wheel",zt,{passive:!0}),G.addEventListener("click",Ut),Fe.addEventListener("click",q),L.addEventListener("keydown",Ze);function Ft(){F&&clearTimeout(F),ve!==null&&(cancelAnimationFrame(ve),ve=null),Je=!1,Le.clear(),se&&se.removeEventListener("click",De),ie&&ie.removeEventListener("change",$e),Ae&&Ae.removeEventListener("input",ut),qe&&qe.removeEventListener("click",st),G.removeEventListener("scroll",Pt),G.removeEventListener("wheel",zt),G.removeEventListener("click",Ut),Fe.removeEventListener("click",q),L.removeEventListener("keydown",Ze)}return{element:L,update:Te,destroy:Ft}}}function zu(e,t){let n=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")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.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 l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(p,u),i.append(d,l),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Vu=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>zu(e,t)});if(p)return p}return zu(e,t)};var al=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},mo=new al;mo.register("PersonaArtifactCard",Vu);function by(e){var s;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 r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Ku(e,t){var ie,se,Ae,qe;let n=(se=(ie=e.features)==null?void 0:ie.artifacts)==null?void 0:se.layout,s=((Ae=n==null?void 0:n.toolbarPreset)!=null?Ae:"default")==="document",o=(qe=n==null?void 0:n.panePadding)==null?void 0:qe.trim(),a=e.markdown?Ko(e.markdown):null,i=Is(e.sanitize),d=Q=>{let te=a?a(Q):Jo(Q);return i?i(te):te},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};l&&l.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let u=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");u.setAttribute("data-persona-theme-zone","artifact-pane"),s&&u.classList.add("persona-artifact-pane-document");let f=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");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let x="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?Kt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Kt({icon:"eye",label:"Rendered view"}),H=s?Kt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Kt({icon:"code-2",label:"Source"}),M=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),L=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,I=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,A=n==null?void 0:n.documentToolbarCopyMenuItems,P=!!(I&&A&&A.length>0),F=null,B,W=null,U=null;if(s&&(L||I)&&!P){if(B=L?Xa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let Q=Ce("chevron-down",14,"currentColor",2);Q&&B.appendChild(Q)}}else s&&P?(F=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),B=L?Xa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=Kt({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"}}),F.append(B,W)):s?B=Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):B=Kt({icon:"copy",label:"Copy"});let V=s?Kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"refresh-cw",label:"Refresh"}),oe=s?Kt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"x",label:"Close"}),We=()=>{var ue,re,Ye;let Q=(ue=Le.find(Ie=>Ie.id===K))!=null?ue:Le[Le.length-1],te=(re=Q==null?void 0:Q.id)!=null?re:null,le=(Q==null?void 0:Q.artifactType)==="markdown"&&(Ye=Q.markdown)!=null?Ye:"",ye=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:le,jsonPayload:ye,id:te}},Je=async()=>{var ue;let{markdown:Q,jsonPayload:te}=We(),le=(ue=Le.find(re=>re.id===K))!=null?ue:Le[Le.length-1],ye=(le==null?void 0:le.artifactType)==="markdown"?Q:le?te:"";try{await navigator.clipboard.writeText(ye)}catch{}};if(B.addEventListener("click",async()=>{let Q=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Q&&P){let{markdown:te,jsonPayload:le,id:ye}=We();try{await Q({actionId:"primary",artifactId:ye,markdown:te,jsonPayload:le})}catch{}return}await Je()}),W&&(A!=null&&A.length)){let Q=()=>{var le;return(le=u.closest("[data-persona-root]"))!=null?le:document.body},te=()=>{U=Wo({items:A.map(le=>({id:le.id,label:le.label})),onSelect:async le=>{let{markdown:ye,jsonPayload:ue,id:re}=We(),Ye=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ye?await Ye({actionId:le,artifactId:re,markdown:ye,jsonPayload:ue}):le==="markdown"||le==="md"?await navigator.clipboard.writeText(ye):le==="json"||le==="source"?await navigator.clipboard.writeText(ue):await navigator.clipboard.writeText(ye||ue)}catch{}},anchor:F!=null?F:W,position:"bottom-right",portal:Q()})};u.isConnected?te():requestAnimationFrame(te),W.addEventListener("click",le=>{le.stopPropagation(),U==null||U.toggle()})}V.addEventListener("click",async()=>{var Q;try{await((Q=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Q.call(n))}catch{}z()}),oe.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let ve=()=>{s&&(S.setAttribute("aria-pressed",x==="rendered"?"true":"false"),H.setAttribute("aria-pressed",x==="source"?"true":"false"))};S.addEventListener("click",()=>{x="rendered",ve(),z()}),H.addEventListener("click",()=>{x="source",ve(),z()});let Re=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");s?(f.replaceChildren(),w.append(S,H),F?M.append(F,V,oe):M.append(B,V,oe),f.append(w,Re,M),ve()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let he=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"),He=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(he.style.paddingLeft=o,he.style.paddingRight=o,He.style.padding=o),u.appendChild(f),u.appendChild(he),u.appendChild(He);let Le=[],K=null,pe=!1,z=()=>{var ye,ue,re,Ye;let Q=s&&Le.length<=1;he.classList.toggle("persona-hidden",Q),he.replaceChildren();for(let Ie of Le){let ge=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");ge.type="button",ge.textContent=Ie.title||Ie.id.slice(0,8),Ie.id===K&&ge.classList.add("persona-bg-persona-container","persona-border-persona-border"),ge.addEventListener("click",()=>t.onSelect(Ie.id)),he.appendChild(ge)}He.replaceChildren();let te=K&&Le.find(Ie=>Ie.id===K)||Le[Le.length-1];if(!te)return;if(s){let Ie=te.artifactType==="markdown"?"MD":(ye=te.component)!=null?ye:"Component",G=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Re.textContent=`${G} \xB7 ${Ie}`}else m.textContent="Artifacts";if(te.artifactType==="markdown"){if(s&&x==="source"){let ge=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ge.textContent=(ue=te.markdown)!=null?ue:"",He.appendChild(ge);return}let Ie=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ie.innerHTML=d((re=te.markdown)!=null?re:""),He.appendChild(Ie);return}let le=te.component?mo.get(te.component):void 0;if(le){let ge={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let G=le((Ye=te.props)!=null?Ye:{},ge);if(G){He.appendChild(G);return}}catch{}}He.appendChild(by(te))},ce=()=>{var te;let Q=Le.length>0;if(u.classList.toggle("persona-hidden",!Q),l){let le=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,ue=((te=le==null?void 0:le.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Q&&ue&&pe?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(Q){var te,le,ye;Le=Q.artifacts,K=(ye=(le=Q.selectedId)!=null?le:(te=Q.artifacts[Q.artifacts.length-1])==null?void 0:te.id)!=null?ye:null,Le.length>0&&(pe=!0),z(),ce()},setMobileOpen(Q){pe=Q,!Q&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):ce()}}}function mr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Ju(e,t){var o,a,i,d;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"),!mr(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function yy(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")}function di(e,t){var d,l,p,u,f,m,v,x,w,S;if(!mr(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"),yy(e),Ju(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(w=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ju(e,t)}var Gu=["panel","seamless"];function pi(e,t){var i,d,l,p,u,f;for(let m of Gu)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!mr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",s=Gu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Xu(e,t){var n,r,s;return!t||!mr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function xy(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function vy(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function wy(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Cy(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function Qu(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Yu(e,t,n,r,s,o){let a=xy(s,200),i=Cy(t,n,r,200);i=Math.max(a,i);let d=vy(o);return d!==null&&(i=Math.min(i,d)),wy(e,a,i)}var Zu={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"}},il=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,w;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=Zu[a])!=null?x:Zu.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,d.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var A,P;let H=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");H.htmlFor=`${t.id}-${a}-${S.name}`;let M=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=S.label,H.appendChild(M);let L=(A=S.type)!=null?A:"text",I;L==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=L),I.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",I.id=`${t.id}-${a}-${S.name}`,I.name=S.name,I.placeholder=(P=S.placeholder)!=null?P:"",S.required&&(I.required=!0),H.appendChild(I),p.appendChild(H)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=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");m.type="submit",m.textContent=(w=i.submitLabel)!=null?w:"Submit",u.appendChild(f),u.appendChild(m),p.appendChild(u),o.replaceChildren(d,p),p.addEventListener("submit",async S=>{var I,A;S.preventDefault();let H=(I=n.formEndpoint)!=null?I:"/form",M=new FormData(p),L={};M.forEach((P,F)=>{L[F]=P}),L.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let P=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let F=await P.json();f.textContent=(A=F.message)!=null?A:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(P){f.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var ll=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},ui=new ll;var em=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ay=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Sy=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},mi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Ay(e),n=Sy(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},cl=e=>typeof e=="string"?e:e==null?"":String(e),ls={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:cl(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=cl(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:cl(n.text)}}},tm=e=>Array.isArray(e)?e.map(t=>String(t)):[],gi=e=>{let t=new Set(tm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(tm(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Ty=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Ey=e=>e.map(t=>({...t,streaming:!1})),My=e=>e.map(t=>({...t,status:"complete"})),dl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Ty(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?Ey(n.messages):void 0,artifacts:n.artifacts?My(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as ky,STR as Ly,OBJ as Py}from"partial-json";function Iy(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Wy(e,t){if(!Iy(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function pl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=ky(n,Ly|Py),o=Wy(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ry(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ul(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=mo.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Hy(){let e=pl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function nm(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 ml(e){let t=nm(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 gl(e){let t=nm(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 r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var By=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function fl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=By}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,m.appendChild(x),f.appendChild(m);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let A=1;A<=5;A++){let P=document.createElement("button");P.type="button",P.className="persona-feedback-rating-btn persona-feedback-star-btn",P.setAttribute("role","radio"),P.setAttribute("aria-checked","false"),P.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${l[A-1]}`),P.title=l[A-1],P.dataset.rating=String(A),P.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <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>
29
29
  </svg>
30
- `,I.addEventListener("click",()=>{m=w,T.forEach((O,$)=>{let B=$<w;O.classList.toggle("selected",B),O.setAttribute("aria-checked",$===w-1?"true":"false")})}),T.push(I),C.appendChild(I)}g.appendChild(C);let H=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=o,H.rows=3,H.setAttribute("aria-label","Additional comments"),w.appendChild(H),g.appendChild(w)}let L=document.createElement("div");L.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.addEventListener("click",()=>{n==null||n(),p.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(m===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let w=(H==null?void 0:H.value.trim())||void 0;await t(m,w),p.remove()}catch(w){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),L.appendChild(P),L.appendChild(W),g.appendChild(L),p.appendChild(g),p}function pl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,v.appendChild(C),u.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="persona-feedback-labels";let L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=l;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=p,H.appendChild(L),H.appendChild(P);let W=document.createElement("div");W.className="persona-feedback-numbers";let w=[];for(let j=0;j<=10;j++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${j} out of 10`),z.textContent=String(j),z.dataset.rating=String(j),j<=6?z.classList.add("persona-feedback-detractor"):j<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{g=j,w.forEach((oe,We)=>{oe.classList.toggle("selected",We===j),oe.setAttribute("aria-checked",We===j?"true":"false")})}),w.push(z),W.appendChild(z)}T.appendChild(H),T.appendChild(W),u.appendChild(T);let I=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),j.appendChild(I),u.appendChild(j)}let O=document.createElement("div");O.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{n==null||n(),m.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(g===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let j=(I==null?void 0:I.value.trim())||void 0;await t(g,j),m.remove()}catch(j){B.disabled=!1,B.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),O.appendChild($),O.appendChild(B),u.appendChild(O),m.appendChild(u),m}var rs="persona-chat-history",Sb=30*1e3,Tb={"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 Eb(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Tb[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function ui(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 Mb(e){var t,n,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function kb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var ul=e=>!e||typeof e!="object"?{}:{...e},Vu=e=>e.map(t=>({...t,streaming:!1})),Ku=(e,t,n)=>{let r=e!=null&&e.markdown?_o(e.markdown):null,s=Ts(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0: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."),o=>{var l,p,m;let a=(l=o.text)!=null?l:"",i=(p=o.message.rawContent)!=null?p:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(m=i!=null?i:o.text)!=null?m:""}):r?d=r(a):d=jo(a),s?s(d):d}};function Ju(e){var i,d,l,p;let t=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=be(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=h("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var ml=(e,t,n)=>{var Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,Ul,ql,zl,Vl,Kl,Jl,Gl,Xl,Ql,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc,Ac;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 r=Ii(t),s=ci.getForInstance(r.plugins);r.components&&lo.registerAll(r.components);let o=Uu(),i=r.persistState===!1?null:(Pl=r.storageAdapter)!=null?Pl:sl(),d={},l=null,p=!1,m=c=>{if(r.onStateLoaded)try{let f=r.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:y,open:b}=f;return b&&(p=!0),y}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let y=f!=null?f:{messages:[],metadata:{}};return m(y)});else{let f=c!=null?c:{messages:[],metadata:{}},y=m(f);y.metadata&&(d=ul(y.metadata)),(Il=y.messages)!=null&&Il.length&&(r={...r,initialMessages:y.messages}),(Wl=y.artifacts)!=null&&Wl.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Rl=y.selectedArtifactId)!=null?Rl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=m({messages:[],metadata:{}});(Hl=c.messages)!=null&&Hl.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,u=c=>{var y;d=(y=c({...d}))!=null?y:{},Ro()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[di],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick],C=pi({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let T=(Dl=(Bl=r.launcher)==null?void 0:Bl.enabled)!=null?Dl:!0,H=(Fl=(Nl=r.launcher)==null?void 0:Nl.autoExpand)!=null?Fl:!1,L=(Ol=r.autoFocusInput)!=null?Ol:!1,P=H,W=T,w=(_l=($l=r.layout)==null?void 0:$l.header)==null?void 0:_l.layout,I=!1,O=()=>no(r),$=()=>T||O(),B=O()?!1:T?H:!0,j=!1,z=null,oe=()=>{j=!0,z&&clearTimeout(z),z=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},We=Ku(r,C,oe),je=(Ul=(jl=r.features)==null?void 0:jl.showReasoning)!=null?Ul:!0,Ne=(zl=(ql=r.features)==null?void 0:ql.showToolCalls)!=null?zl:!0,ge=(Kl=(Vl=r.features)==null?void 0:Vl.showEventStreamToggle)!=null?Kl:!1,ye=(Gl=(Jl=r.features)==null?void 0:Jl.scrollToBottom)!=null?Gl:{},He=`${(Ql=typeof r.persistState=="object"?(Xl=r.persistState)==null?void 0:Xl.keyPrefix:void 0)!=null?Ql:"persona-"}event-stream`,ee=ge?new Xs(He):null,Pe=(ec=(Zl=(Yl=r.features)==null?void 0:Yl.eventStream)==null?void 0:Zl.maxEvents)!=null?ec:2e3,V=ge?new Gs(Pe,ee):null,le=ge?new Qs:null,ve=null,fe=!1,we=null,ze=0;ee==null||ee.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Q={onCopy:c=>{var f,y;o.emit("message:copy",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onCopy)==null||y.call(f,c)},onFeedback:c=>{var f,y;o.emit("message:feedback",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onFeedback)==null||y.call(f,c)}},te=(tc=r.statusIndicator)!=null?tc:{},se=c=>{var f,y,b,M;return c==="idle"?(f=te.idleText)!=null?f:gn.idle:c==="connecting"?(y=te.connectingText)!=null?y:gn.connecting:c==="connected"?(b=te.connectedText)!=null?b:gn.connected:c==="error"?(M=te.errorText)!=null?M:gn.error:gn[c]};function ue(c,f,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let M=document.createElement("a");M.href=y.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=f,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=f}let{wrapper:ie,panel:re,pillRoot:Qe}=lu(r),Ie=cu(r,$()),{container:ce,body:G,messagesWrapper:$e,suggestions:Et,textarea:de,sendButton:ae,sendButtonWrapper:Mn,composerForm:Ot,statusText:ln,introTitle:Hn,introSubtitle:Xn,closeButton:Ue,iconHolder:N,headerTitle:Ae,headerSubtitle:Be,header:De,footer:_e,actionsRow:dt,leftActions:rt,rightActions:At}=Ie,_t=Ie.setSendButtonMode,q=Ie.micButton,$t=Ie.micButtonWrapper,Ye=Ie.attachmentButton,Dt=Ie.attachmentButtonWrapper,ne=Ie.attachmentInput,me=Ie.attachmentPreviewsContainer;ce.classList.add("persona-relative"),G.classList.add("persona-relative");let vt=12,jt=()=>{var c;return(c=ye.label)!=null?c:""},Zt=()=>{var c;return(c=ye.iconName)!=null?c:"arrow-down"},hn=()=>ye.enabled!==!1,St=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");St.type="button",St.style.display="none",St.setAttribute("data-persona-scroll-to-bottom","true");let wt=h("span","persona-flex persona-items-center"),ft=h("span","");St.append(wt,ft),ce.appendChild(St);let yt=()=>{let f=_e.style.display==="none"?0:_e.offsetHeight;St.style.bottom=`${f+vt}px`};yt();let zt=()=>{let c=!!jt();St.setAttribute("aria-label",jt()||"Jump to latest"),St.title=jt(),St.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),wt.innerHTML="";let f=be(Zt(),"14px","currentColor",2);f?(wt.appendChild(f),wt.style.display=""):wt.style.display="none",ft.textContent=jt(),ft.style.display=c?"":"none"};zt();let tt=null,Bn=null,Qn=s.find(c=>c.renderHeader);if(Qn!=null&&Qn.renderHeader){let c=Qn.renderHeader({config:r,defaultRenderer:()=>{let f=ro({config:r,showClose:$()});return Go(ce,f,r),f.header},onClose:()=>Rt(!1,"user")});if(c){let f=ce.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),De=c)}}let yn=()=>{var f,y,b,M;if(!V)return;if(fe=!0,!ve&&V&&(ve=Ru({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>Dn(),config:r,plugins:s,getThroughput:()=>{var D;return(D=le==null?void 0:le.getMetric())!=null?D:{status:"idle"}}})),ve&&(G.style.display="none",(f=_e.parentNode)==null||f.insertBefore(ve.element,_e),ve.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${En.actionIconColor}`;let D=(M=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:M.toggleButtonActive;D&&D.split(/\s+/).forEach(F=>F&&ut.classList.add(F))}let c=()=>{if(!fe)return;let D=Date.now();D-ze>=200&&(ve==null||ve.update(),ze=D),we=requestAnimationFrame(c)};ze=0,we=requestAnimationFrame(c),Wr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Dn=()=>{var c,f,y;if(fe){if(fe=!1,ve&&ve.element.remove(),G.style.display="",ut){ut.style.boxShadow="";let b=(y=(f=(c=r.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(M=>M&&ut.classList.remove(M))}we!==null&&(cancelAnimationFrame(we),we=null),Wr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ge){let c=(rc=(nc=r.features)==null?void 0:nc.eventStream)==null?void 0:rc.classNames,f="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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=h("button",f),ut.style.width="28px",ut.style.height="28px",ut.style.color=En.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let y=be("activity","18px","currentColor",1.5);y&&ut.appendChild(y);let b=Ie.clearChatButtonWrapper,M=Ie.closeButtonWrapper,D=b||M;D&&D.parentNode===De?De.insertBefore(ut,D):De.appendChild(ut),ut.addEventListener("click",()=>{fe?Dn():yn()})}let xr=c=>{var b,M,D;let f=r.attachments;if(!(f!=null&&f.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let F=c.querySelector("[data-persona-composer-form]");F!=null&&F.parentNode?F.parentNode.insertBefore(y,F):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let F=h("input");F.type="file",F.accept=((b=f.allowedTypes)!=null?b:Nr).join(","),F.multiple=((M=f.maxFiles)!=null?M:4)>1,F.style.display="none",F.setAttribute("aria-label",(D=f.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(F)}},Nn=s.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=r.composer,f=Nn.renderComposer({config:r,defaultRenderer:()=>zs({config:r}).footer,onSubmit:y=>{var F;if(!S||S.isStreaming())return;let b=y.trim(),M=(F=tt==null?void 0:tt.hasAttachments())!=null?F:!1;if(!b&&!M)return;gs();let D;M&&(D=[],D.push(...tt.getContentParts()),b&&D.push(Ia(b))),S.sendMessage(b,{contentParts:D}),M&&tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ne==null||ne.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((oc=r.voiceRecognition)==null?void 0:oc.enabled)===!0?()=>{Bn==null||Bn()}:void 0});f&&(_e.replaceWith(f),_e=f)}let po=c=>{let f=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");f&&(Ot=f),y&&(de=y),b&&(ae=b),M&&(q=M,$t=M.parentElement),D&&(ln=D);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Et=F);let U=c.querySelector(".persona-attachment-button");U&&(Ye=U,Dt=U.parentElement),ne=c.querySelector('input[type="file"]'),me=c.querySelector(".persona-attachment-previews");let R=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");R&&(dt=R)};xr(_e),po(_e);let kn=(cc=(sc=r.layout)==null?void 0:sc.contentMaxWidth)!=null?cc:O()?(lc=(ic=(ac=r.launcher)==null?void 0:ac.composerBar)==null?void 0:ic.contentMaxWidth)!=null?lc:"720px":void 0;if(kn&&($e.style.maxWidth=kn,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),kn&&Ot&&!O()&&(Ot.style.maxWidth=kn,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),kn&&Et&&!O()&&(Et.style.maxWidth=kn,Et.style.marginLeft="auto",Et.style.marginRight="auto"),kn&&me&&!O()&&(me.style.maxWidth=kn,me.style.marginLeft="auto",me.style.marginRight="auto"),(dc=r.attachments)!=null&&dc.enabled&&ne&&me){tt=Ko.fromConfig(r.attachments),tt.setPreviewsContainer(me),ne.addEventListener("change",y=>{let b=y.target;tt==null||tt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,f=Ju(c);ce.appendChild(f)}(()=>{var b,M;let c=(M=(b=r.layout)==null?void 0:b.slots)!=null?M:{},f=D=>{switch(D){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return Et;case"composer":return Ot;case"footer-bottom":return ln;default:return null}},y=(D,F)=>{var U;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")De.insertBefore(F,De.firstChild);else if(D==="header-right")De.appendChild(F);else{let R=De.querySelector(".persona-flex-col");R?(U=R.parentNode)==null||U.insertBefore(F,R.nextSibling):De.appendChild(F)}break;case"body-top":{let R=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(F):G.insertBefore(F,G.firstChild);break}case"body-bottom":G.appendChild(F);break;case"footer-top":Et.replaceWith(F);break;case"footer-bottom":ln.replaceWith(F);break;default:break}};for(let[D,F]of Object.entries(c))if(F)try{let U=F({config:r,defaultContent:()=>f(D)});U&&y(D,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,U)}})();let Or=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let M=b.getAttribute("data-message-id");if(!M)return;let D=y.getAttribute("data-bubble-type");D==="reasoning"?(Qo.has(M)?Qo.delete(M):Qo.add(M),gu(M,b)):D==="tool"&&(Yo.has(M)?Yo.delete(M):Yo.add(M),fu(M,b,r)),dr.delete(M)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Or(c))}),$e.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Or(c))});let Er=new Map;$e.addEventListener("click",c=>{var F;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let M=b.getAttribute("data-actions-for");if(!M)return;let D=y.getAttribute("data-action");if(D==="copy"){let R=S.getMessages().find(Ce=>Ce.id===M);if(R&&Q.onCopy){let Ce=R.content||"";navigator.clipboard.writeText(Ce).then(()=>{y.classList.add("persona-message-action-success");let pe=be("check",14,"currentColor",2);pe&&(y.innerHTML="",y.appendChild(pe)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Z=be("copy",14,"currentColor",2);Z&&(y.innerHTML="",y.appendChild(Z))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),Q.onCopy(R)}}else if(D==="upvote"||D==="downvote"){let R=((F=Er.get(M))!=null?F:null)===D,Ce=D==="upvote"?"thumbs-up":"thumbs-down";if(R){Er.delete(M),y.classList.remove("persona-message-action-active");let pe=be(Ce,14,"currentColor",2);pe&&(y.innerHTML="",y.appendChild(pe))}else{let pe=D==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${pe}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Ge=be(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(Z.innerHTML="",Z.appendChild(Ge))}Er.set(M,D),y.classList.add("persona-message-action-active");let he=be(Ce,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(he)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Fe=S.getMessages().find(nt=>nt.id===M);Fe&&Q.onFeedback&&Q.onFeedback({type:D,messageId:Fe.id,message:Fe})}}}),$e.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let M=b.getAttribute("data-message-id");if(!M)return;let D=y.getAttribute("data-approval-action");if(!D)return;let F=D==="approve"?"approved":"denied",R=S.getMessages().find(pe=>pe.id===M);if(!(R!=null&&R.approval))return;let Ce=b.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),R.approval.toolType==="webmcp"?S.resolveWebMcpApproval(M,F):S.resolveApproval(R.approval,F)});let bt=null,Fn=null,On={artifacts:[],selectedId:null},bn=!1,Lt={current:null};$e.addEventListener("click",c=>{var Z,he,Se,Fe,nt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Se=(he=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Se.call(he,{type:"download",artifactId:b}))===!0)return;let D=S.getArtifactById(b),F=D==null?void 0:D.markdown,U=(D==null?void 0:D.title)||"artifact";if(!F){let Ge=y.closest("[data-open-artifact]"),at=Ge==null?void 0:Ge.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Me=S.getMessages().find(qe=>qe.id===it);if(Me!=null&&Me.rawContent)try{let qe=JSON.parse(Me.rawContent);F=(Fe=qe==null?void 0:qe.props)==null?void 0:Fe.markdown,U=((nt=qe==null?void 0:qe.props)==null?void 0:nt.title)||U}catch{}}}if(!F)return;let R=new Blob([F],{type:"text/markdown"}),Ce=URL.createObjectURL(R),pe=document.createElement("a");pe.href=Ce,pe.download=`${U}.md`,pe.click(),URL.revokeObjectURL(Ce)}),$e.addEventListener("click",c=>{var D,F,U;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((U=(F=(D=r.features)==null?void 0:D.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:U.call(F,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),bn=!1,S.selectArtifact(b),jn())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let Yn=Ie.composerOverlay,Zn=(c,f,y)=>{var U,R,Ce,pe;let b=f.trim();if(!b||!Lt.current)return;let M=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",D=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:b,answers:y.structured,values:(R=y.values)!=null?R:y.source==="multi"?b.split(", "):[b],isFreeText:D,source:y.source},bubbles:!0,composed:!0})),Lo(Yn,M);let F=Lt.current.getMessages().find(Z=>{var he;return((he=Z.toolCall)==null?void 0:he.id)===M});(Ce=F==null?void 0:F.agentMetadata)!=null&&Ce.awaitingLocalTool?Lt.current.resolveAskUserQuestion(F,(pe=y.structured)!=null?pe:b):Lt.current.sendMessage(b)},$n=c=>{var M;let f=Lt.current;if(!f)return;let y=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",b=f.getMessages().find(D=>{var F;return((F=D.toolCall)==null?void 0:F.id)===y});b&&f.persistAskUserQuestionProgress(b,{answers:oi(c,b),currentIndex:ar(c)})},$r=c=>Object.entries(c).map(([f,y])=>`${f}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Mr=c=>{var M,D,F;if(((D=(M=r.features)==null?void 0:M.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let f=ar(c),y=es(c);if(f>=y-1)return;let b=(F=Lt.current)==null?void 0:F.getMessages().find(U=>{var R;return((R=U.toolCall)==null?void 0:R.id)===c.getAttribute("data-tool-call-id")});b&&(si(c,b,r,f+1),$n(c))};Yn.addEventListener("click",c=>{var D,F,U,R,Ce,pe,Z,he,Se,Fe,nt,Ge,at,it;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let M=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let ke=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ke},bubbles:!0,composed:!0})),Lo(Yn,ke);let Me=(F=Lt.current)==null?void 0:F.getMessages().find(qe=>{var E;return((E=qe.toolCall)==null?void 0:E.id)===ke});(U=Me==null?void 0:Me.agentMetadata)!=null&&U.awaitingLocalTool&&((R=Lt.current)==null||R.markAskUserQuestionResolved(Me),(Ce=Lt.current)==null||Ce.resolveAskUserQuestion(Me,"(dismissed)"));return}if(M==="pick"){let ke=y.getAttribute("data-option-label");if(!ke)return;let Me=b.getAttribute("data-multi-select")==="true",qe=ao(b);if(qe&&Me){let E=ko(b)[ar(b)],Te=new Set(Array.isArray(E)?E:[]);Te.has(ke)?Te.delete(ke):Te.add(ke),io(b,Array.from(Te)),$n(b);return}if(qe){io(b,ke),$n(b),Mr(b);return}if(Me){let E=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",E?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!E);let Te=b.querySelector('[data-ask-user-action="submit-multi"]');Te&&(Te.disabled=Qi(b).length===0);return}Zn(b,ke,{source:"pick",values:[ke]});return}if(M==="submit-multi"){let ke=Qi(b);if(ke.length===0)return;Zn(b,ke.join(", "),{source:"multi",values:ke});return}if(M==="open-free-text"){let ke=b.querySelector('[data-ask-free-text-row="true"]');if(ke){ke.classList.remove("persona-hidden");let Me=ke.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus()}return}if(M==="focus-free-text"){let ke=b.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus();return}if(M==="submit-free-text"){let ke=b.querySelector('[data-ask-free-text-input="true"]'),Me=(pe=ke==null?void 0:ke.value)!=null?pe:"";if(!Me.trim())return;if(ao(b)){io(b,Me.trim()),$n(b),Mr(b);return}Zn(b,Me,{source:"free-text"});return}if(M==="next"||M==="back"){if(!Lt.current)return;let ke=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Me=Lt.current.getMessages().find(Ke=>{var xe;return((xe=Ke.toolCall)==null?void 0:xe.id)===ke});if(!Me)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),E=(Se=(he=qe==null?void 0:qe.value)==null?void 0:he.trim())!=null?Se:"";if(E){let Ke=ko(b)[ar(b)];(typeof Ke!="string"||Ke!==E)&&io(b,E)}let Te=M==="next"?1:-1,Re=ar(b)+Te;si(b,Me,r,Re),$n(b);return}if(M==="submit-all"){if(!Lt.current)return;let ke=(Fe=b.getAttribute("data-tool-call-id"))!=null?Fe:"",Me=Lt.current.getMessages().find(Ke=>{var xe;return((xe=Ke.toolCall)==null?void 0:xe.id)===ke});if(!Me)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),E=(Ge=(nt=qe==null?void 0:qe.value)==null?void 0:nt.trim())!=null?Ge:"";E&&io(b,E);let Te=oi(b,Me);Lt.current.persistAskUserQuestionProgress(Me,{answers:Te,currentIndex:ar(b)});let Re=$r(Te);Zn(b,Re||"(submitted)",{source:"submit-all",structured:Te});return}if(M==="skip"){if(!Lt.current)return;let ke=(at=b.getAttribute("data-tool-call-id"))!=null?at:"",Me=Lt.current.getMessages().find(xe=>{var kt;return((kt=xe.toolCall)==null?void 0:kt.id)===ke});if(!Me)return;let qe=ao(b),E=ar(b),Te=es(b),Re=E>=Te-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ke},bubbles:!0,composed:!0})),Lo(Yn,ke),(it=Me.agentMetadata)!=null&&it.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Me),Lt.current.resolveAskUserQuestion(Me,"(dismissed)"));return}io(b,"");let Ke=b.querySelector('[data-ask-free-text-input="true"]');if(Ke&&(Ke.value=""),Re){let xe=oi(b,Me),kt=$r(xe);Zn(b,kt||"(skipped)",{source:"submit-all",structured:xe});return}si(b,Me,r,E+1),$n(b);return}}),Yn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let y=c.target;if(!((D=y.matches)!=null&&D.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let M=y.value;if(M.trim()){if(ao(b)){io(b,M.trim()),$n(b),Mr(b);return}Zn(b,M,{source:"free-text"})}});let _r=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let y=Yn.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),D=y.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];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",_r);let _n=null,Wt=null,xn=null,er=null,jr=()=>{};function kr(){er==null||er(),er=null}let Ur=()=>{var F;if(!_n||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((F=e.ownerDocument.defaultView)!=null?F:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let b=_n.firstElementChild;if(!b||b===Wt)return;let M=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${M}px`,Wt.style.zIndex="5";let D=b.offsetWidth-M/2;Wt.style.left=`${Math.max(0,D)}px`},vr=()=>{},jn=()=>{var y,b,M,D,F;if(!bt||!ir(r))return;ii(e,r),li(e,r),vr();let c=(D=(M=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:M.narrowHostMaxWidth)!=null?D:520,f=re.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),bt.update(On),bn?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(F=bt.backdrop)==null||F.classList.add("persona-hidden")):On.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),jr()};if(ir(r)){re.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ce),bt=Du(r,{onSelect:y=>{var b;return(b=Lt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{bn=!0,jn()}}),bt.element.classList.add("persona-hidden"),_n=f,f.appendChild(c),f.appendChild(bt.element),bt.backdrop&&re.appendChild(bt.backdrop),re.appendChild(f),jr=()=>{var b,M,D,F;if(!_n||!bt)return;if(!(((D=(M=(b=r.features)==null?void 0:b.artifacts)==null?void 0:M.layout)==null?void 0:D.resizable)===!0)){xn==null||xn(),xn=null,kr(),Wt&&(Wt.remove(),Wt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Wt){let U=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let R=e.ownerDocument,Ce=(F=R.defaultView)!=null?F:window,pe=Z=>{var at,it;if(!bt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;Z.preventDefault(),kr();let he=Z.clientX,Se=bt.element.getBoundingClientRect().width,Fe=(it=(at=r.features)==null?void 0:at.artifacts)==null?void 0:it.layout,nt=ke=>{let Me=_n.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),E=qe?0:$u(_n,Ce),Te=qe?0:U.getBoundingClientRect().width||6,Re=Se-(ke.clientX-he),Ke=_u(Re,Me,E,Te,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);bt.element.style.width=`${Ke}px`,bt.element.style.maxWidth="none",Ur()},Ge=()=>{R.removeEventListener("pointermove",nt),R.removeEventListener("pointerup",Ge),R.removeEventListener("pointercancel",Ge),er=null;try{U.releasePointerCapture(Z.pointerId)}catch{}};er=Ge,R.addEventListener("pointermove",nt),R.addEventListener("pointerup",Ge),R.addEventListener("pointercancel",Ge);try{U.setPointerCapture(Z.pointerId)}catch{}};U.addEventListener("pointerdown",pe),Wt=U,_n.insertBefore(U,bt.element),xn=()=>{U.removeEventListener("pointerdown",pe)}}if(Wt){let U=On.artifacts.length>0&&!bn;Wt.classList.toggle("persona-hidden",!U),Ur()}},vr=()=>{var Ce,pe,Z,he,Se,Fe,nt,Ge,at,it,ke,Me,qe,E;if(!T||!bt||((pe=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?pe:!1)||an(r)&&yr(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,M=(Se=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?Se:!0,D=(nt=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?nt:640;if(M&&b.innerWidth<=D||!Ou(r,T))return;let F=(it=(at=(Ge=r.launcher)==null?void 0:Ge.width)!=null?at:r.launcherWidth)!=null?it:sr,U=(E=(qe=(Me=(ke=r.features)==null?void 0:ke.artifacts)==null?void 0:Me.layout)==null?void 0:qe.expandedPanelWidth)!=null?E:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!bn?(re.style.width=U,re.style.maxWidth=U):(re.style.width=F,re.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{jn()}),Fn.observe(re))}else re.appendChild(ce),O()&&Qe&&(Ie.peekBanner&&Qe.appendChild(Ie.peekBanner),Qe.appendChild(_e));e.appendChild(ie),Qe&&e.appendChild(Qe);let lr=()=>{var Ke,xe,kt,st,Qt,cn,It,Cn,dn,Ze,lt,An,un,yo,bo,xo,Oo,$o,Vt,vo,Zr,ht,Pn,Br,Sn,In,Ht,Ut;if(O()){re.style.width="100%",re.style.maxWidth="100%";let Bt=(xe=(Ke=r.launcher)==null?void 0:Ke.composerBar)!=null?xe:{},Kt=ie.dataset.state==="expanded",Wn=(kt=Bt.expandedSize)!=null?kt:"anchored";if(!(Kt&&Wn!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let tn=(Qt=(st=r.theme)==null?void 0:st.components)==null?void 0:Qt.panel,Ar=Hs(r),Dr=(wo,xa)=>{var Cs;return wo==null||wo===""?xa:(Cs=Jo(Ar,wo))!=null?Cs:wo},ha="1px solid var(--persona-border)",ya="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ba="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=Dr(tn==null?void 0:tn.border,ha),ce.style.borderRadius=Dr(tn==null?void 0:tn.borderRadius,ba),ce.style.boxShadow=Dr(tn==null?void 0:tn.shadow,ya),ce.style.overflow="hidden";return}let c=an(r),f=(It=(cn=r.launcher)==null?void 0:cn.sidebarMode)!=null?It:!1,y=c||f||((dn=(Cn=r.launcher)==null?void 0:Cn.fullHeight)!=null?dn:!1),b=((Ze=r.launcher)==null?void 0:Ze.enabled)===!1,M=(An=(lt=r.theme)==null?void 0:lt.components)==null?void 0:An.panel,D=Hs(r),F=(Bt,Kt)=>{var Wn;return Bt==null||Bt===""?Kt:(Wn=Jo(D,Bt))!=null?Wn:Bt},U=(un=e.ownerDocument.defaultView)!=null?un:window,R=(bo=(yo=r.launcher)==null?void 0:yo.mobileFullscreen)!=null?bo:!0,Ce=(Oo=(xo=r.launcher)==null?void 0:xo.mobileBreakpoint)!=null?Oo:640,pe=U.innerWidth<=Ce,Z=R&&pe&&T,he=(Vt=($o=r.launcher)==null?void 0:$o.position)!=null?Vt:"bottom-left",Se=he==="bottom-left"||he==="top-left",Fe=(Zr=(vo=r.launcher)==null?void 0:vo.zIndex)!=null?Zr:fn,nt=f||Z?"none":"1px solid var(--persona-border)",Ge=Z?"none":f?Se?"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))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(Ge="none",nt="none");let at=f||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=F(M==null?void 0:M.border,nt),ke=F(M==null?void 0:M.shadow,Ge),Me=F(M==null?void 0:M.borderRadius,at),qe=G.scrollTop;e.style.cssText="",ie.style.cssText="",re.style.cssText="",ce.style.cssText="",G.style.cssText="",_e.style.cssText="";let E=()=>{var Kt;if(qe<=0)return;((Kt=G.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(G.scrollTop===qe)return;let Wn=G.scrollHeight-G.clientHeight;Wn<=0||(G.scrollTop=Math.min(qe,Wn))})};if(Z){ie.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"),ie.style.cssText=`
30
+ `,P.addEventListener("click",()=>{u=A,S.forEach((F,B)=>{let W=B<A;F.classList.toggle("selected",W),F.setAttribute("aria-checked",B===A-1?"true":"false")})}),S.push(P),w.appendChild(P)}f.appendChild(w);let H=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=o,H.rows=3,H.setAttribute("aria-label","Additional comments"),A.appendChild(H),f.appendChild(A)}let M=document.createElement("div");M.className="persona-feedback-actions";let L=document.createElement("button");L.type="button",L.className="persona-feedback-btn persona-feedback-btn-skip",L.textContent=i,L.addEventListener("click",()=>{n==null||n(),p.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(u===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=(H==null?void 0:H.value.trim())||void 0;await t(u,A),p.remove()}catch(A){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),M.appendChild(L),M.appendChild(I),f.appendChild(M),p.appendChild(f),p}function hl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="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 f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=s,v.appendChild(w),m.appendChild(v);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let L=document.createElement("span");L.className="persona-feedback-label-high",L.textContent=p,H.appendChild(M),H.appendChild(L);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let U=0;U<=10;U++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${U} out of 10`),V.textContent=String(U),V.dataset.rating=String(U),U<=6?V.classList.add("persona-feedback-detractor"):U<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{f=U,A.forEach((oe,We)=>{oe.classList.toggle("selected",We===U),oe.setAttribute("aria-checked",We===U?"true":"false")})}),A.push(V),I.appendChild(V)}S.appendChild(H),S.appendChild(I),m.appendChild(S);let P=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=o,P.rows=3,P.setAttribute("aria-label","Additional comments"),U.appendChild(P),m.appendChild(U)}let F=document.createElement("div");F.className="persona-feedback-actions";let B=document.createElement("button");B.type="button",B.className="persona-feedback-btn persona-feedback-btn-skip",B.textContent=i,B.addEventListener("click",()=>{n==null||n(),u.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let U=(P==null?void 0:P.value.trim())||void 0;await t(f,U),u.remove()}catch(U){W.disabled=!1,W.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),F.appendChild(B),F.appendChild(W),m.appendChild(F),u.appendChild(m),u}var cs="persona-chat-history",Dy=30*1e3,Ny={"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 Oy(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Ny[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function fi(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 Fy(e){var t,n,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function $y(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var bl=e=>!e||typeof e!="object"?{}:{...e},rm=e=>e.map(t=>({...t,streaming:!1})),om=(e,t,n)=>{let r=e!=null&&e.markdown?Ko(e.markdown):null,s=Is(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0: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."),o=>{var l,p,u;let a=(l=o.text)!=null?l:"",i=(p=o.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(u=i!=null?i:o.text)!=null?u:""}):r?d=r(a):d=Jo(a),s?s(d):d}};function sm(e){var i,d,l,p;let t=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=Ce(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let u=h("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var yl=(e,t,n)=>{var Dl,Nl,Ol,Fl,$l,_l,jl,Ul,ql,zl,Vl,Kl,Jl,Gl,Xl,Ql,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,xc,vc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc;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 r=Ni(t),s=ui.getForInstance(r.plugins);r.components&&mo.registerAll(r.components);let o=em(),i=r.persistState===!1?null:(Dl=r.storageAdapter)!=null?Dl:dl(),d={},l=null,p=!1,u=c=>{if(r.onStateLoaded)try{let g=r.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:y}=g;return y&&(p=!0),b}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let b=g!=null?g:{messages:[],metadata:{}};return u(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=u(g);b.metadata&&(d=bl(b.metadata)),(Nl=b.messages)!=null&&Nl.length&&(r={...r,initialMessages:b.messages}),(Ol=b.artifacts)!=null&&Ol.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Fl=b.selectedArtifactId)!=null?Fl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=u({messages:[],metadata:{}});($l=c.messages)!=null&&$l.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var b;d=(b=c({...d}))!=null?b:{},Oo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[mi],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ls.message,ls.messageAndClick],w=gi({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let S=(jl=(_l=r.launcher)==null?void 0:_l.enabled)!=null?jl:!0,H=(ql=(Ul=r.launcher)==null?void 0:Ul.autoExpand)!=null?ql:!1,M=(zl=r.autoFocusInput)!=null?zl:!1,L=H,I=S,A=(Kl=(Vl=r.layout)==null?void 0:Vl.header)==null?void 0:Kl.layout,P=!1,F=()=>ao(r),B=()=>S||F(),W=F()?!1:S?H:!0,U=!1,V=null,oe=()=>{U=!0,V&&clearTimeout(V),V=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},We=om(r,w,oe),Je=(Gl=(Jl=r.features)==null?void 0:Jl.showReasoning)!=null?Gl:!0,ve=(Ql=(Xl=r.features)==null?void 0:Xl.showToolCalls)!=null?Ql:!0,Re=(Zl=(Yl=r.features)==null?void 0:Yl.showEventStreamToggle)!=null?Zl:!1,he=(tc=(ec=r.features)==null?void 0:ec.scrollToBottom)!=null?tc:{},Le=`${(rc=typeof r.persistState=="object"?(nc=r.persistState)==null?void 0:nc.keyPrefix:void 0)!=null?rc:"persona-"}event-stream`,K=Re?new ra(Le):null,pe=(ac=(sc=(oc=r.features)==null?void 0:oc.eventStream)==null?void 0:sc.maxEvents)!=null?ac:2e3,z=Re?new na(pe,K):null,ce=Re?new oa:null,ie=null,se=!1,Ae=null,qe=0;K==null||K.open().then(()=>z==null?void 0:z.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Q={onCopy:c=>{var g,b;o.emit("message:copy",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(b=(g=r.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;o.emit("message:feedback",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.messageId,c.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(b=(g=r.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},te=(ic=r.statusIndicator)!=null?ic:{},le=c=>{var g,b,y,T;return c==="idle"?(g=te.idleText)!=null?g:xn.idle:c==="connecting"?(b=te.connectingText)!=null?b:xn.connecting:c==="connected"?(y=te.connectedText)!=null?y:xn.connected:c==="error"?(T=te.errorText)!=null?T:xn.error:xn[c]};function ye(c,g,b,y){if(y==="idle"&&b.idleLink){c.textContent="";let T=document.createElement("a");T.href=b.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=g,T.style.color="inherit",T.style.textDecoration="none",c.appendChild(T)}else c.textContent=g}let{wrapper:ue,panel:re,pillRoot:Ye}=fu(r),Ie=hu(r,B()),{container:ge,body:G,messagesWrapper:Fe,suggestions:Rt,textarea:fe,sendButton:de,sendButtonWrapper:Ln,composerForm:jt,statusText:mn,introTitle:Hn,introSubtitle:Yn,closeButton:je,iconHolder:O,headerTitle:Te,headerSubtitle:Be,header:De,footer:$e,actionsRow:ut,leftActions:st,rightActions:Pt}=Ie,zt=Ie.setSendButtonMode,q=Ie.micButton,Ut=Ie.micButtonWrapper,Ze=Ie.attachmentButton,Ft=Ie.attachmentButtonWrapper,ne=Ie.attachmentInput,xe=Ie.attachmentPreviewsContainer;ge.classList.add("persona-relative"),G.classList.add("persona-relative");let Tt=12,Vt=()=>{var c;return(c=he.label)!=null?c:""},tn=()=>{var c;return(c=he.iconName)!=null?c:"arrow-down"},wn=()=>he.enabled!==!1,It=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");It.type="button",It.style.display="none",It.setAttribute("data-persona-scroll-to-bottom","true");let Mt=h("span","persona-flex persona-items-center"),vt=h("span","");It.append(Mt,vt),ge.appendChild(It);let Ct=()=>{let g=$e.style.display==="none"?0:$e.offsetHeight;It.style.bottom=`${g+Tt}px`};Ct();let Jt=()=>{let c=!!Vt();It.setAttribute("aria-label",Vt()||"Jump to latest"),It.title=Vt(),It.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Mt.innerHTML="";let g=Ce(tn(),"14px","currentColor",2);g?(Mt.appendChild(g),Mt.style.display=""):Mt.style.display="none",vt.textContent=Vt(),vt.style.display=c?"":"none"};Jt();let rt=null,Bn=null,Zn=s.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:r,defaultRenderer:()=>{let g=io({config:r,showClose:B()});return ts(ge,g,r),g.header},onClose:()=>Dt(!1,"user")});if(c){let g=ge.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),De=c)}}let Cn=()=>{var g,b,y,T;if(!z)return;if(se=!0,!ie&&z&&(ie=qu({buffer:z,getFullHistory:()=>z.getAllFromStore(),onClose:()=>Dn(),config:r,plugins:s,getThroughput:()=>{var D;return(D=ce==null?void 0:ce.getMetric())!=null?D:{status:"idle"}}})),ie&&(G.style.display="none",(g=$e.parentNode)==null||g.insertBefore(ie.element,$e),ie.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${kn.actionIconColor}`;let D=(T=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:T.toggleButtonActive;D&&D.split(/\s+/).forEach(N=>N&&ht.classList.add(N))}let c=()=>{if(!se)return;let D=Date.now();D-qe>=200&&(ie==null||ie.update(),qe=D),Ae=requestAnimationFrame(c)};qe=0,Ae=requestAnimationFrame(c),Dr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Dn=()=>{var c,g,b;if(se){if(se=!1,ie&&ie.element.remove(),G.style.display="",ht){ht.style.boxShadow="";let y=(b=(g=(c=r.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;y&&y.split(/\s+/).forEach(T=>T&&ht.classList.remove(T))}Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),Dr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Re){let c=(cc=(lc=r.features)==null?void 0:lc.eventStream)==null?void 0:cc.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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ht=h("button",g),ht.style.width="28px",ht.style.height="28px",ht.style.color=kn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let b=Ce("activity","18px","currentColor",1.5);b&&ht.appendChild(b);let y=Ie.clearChatButtonWrapper,T=Ie.closeButtonWrapper,D=y||T;D&&D.parentNode===De?De.insertBefore(ht,D):De.appendChild(ht),ht.addEventListener("click",()=>{se?Dn():Cn()})}let Tr=c=>{var y,T,D;let g=r.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(b,N):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=h("input");N.type="file",N.accept=((y=g.allowedTypes)!=null?y:$r).join(","),N.multiple=((T=g.maxFiles)!=null?T:4)>1,N.style.display="none",N.setAttribute("aria-label",(D=g.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(N)}},Nn=s.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=r.composer,g=Nn.renderComposer({config:r,defaultRenderer:()=>Ys({config:r}).footer,onSubmit:b=>{var N;if(!$||$.isStreaming())return;let y=b.trim(),T=(N=rt==null?void 0:rt.hasAttachments())!=null?N:!1;if(!y&&!T)return;vs();let D;T&&(D=[],D.push(...rt.getContentParts()),y&&D.push(Wa(y))),$.sendMessage(y,{contentParts:D}),T&&rt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ne==null||ne.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{r.composer={...r.composer,selectedModelId:b},r.agent&&(r.agent={...r.agent,model:b})},onVoiceToggle:((dc=r.voiceRecognition)==null?void 0:dc.enabled)===!0?()=>{Bn==null||Bn()}:void 0});g&&($e.replaceWith(g),$e=g)}let fo=c=>{let g=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),T=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");g&&(jt=g),b&&(fe=b),y&&(de=y),T&&(q=T,Ut=T.parentElement),D&&(mn=D);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Rt=N);let j=c.querySelector(".persona-attachment-button");j&&(Ze=j,Ft=j.parentElement),ne=c.querySelector('input[type="file"]'),xe=c.querySelector(".persona-attachment-previews");let R=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");R&&(ut=R)};Tr($e),fo($e);let Pn=(fc=(pc=r.layout)==null?void 0:pc.contentMaxWidth)!=null?fc:F()?(gc=(mc=(uc=r.launcher)==null?void 0:uc.composerBar)==null?void 0:mc.contentMaxWidth)!=null?gc:"720px":void 0;if(Pn&&(Fe.style.maxWidth=Pn,Fe.style.marginLeft="auto",Fe.style.marginRight="auto",Fe.style.width="100%"),Pn&&jt&&!F()&&(jt.style.maxWidth=Pn,jt.style.marginLeft="auto",jt.style.marginRight="auto"),Pn&&Rt&&!F()&&(Rt.style.maxWidth=Pn,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),Pn&&xe&&!F()&&(xe.style.maxWidth=Pn,xe.style.marginLeft="auto",xe.style.marginRight="auto"),(hc=r.attachments)!=null&&hc.enabled&&ne&&xe){rt=Zo.fromConfig(r.attachments),rt.setPreviewsContainer(xe),ne.addEventListener("change",b=>{let y=b.target;rt==null||rt.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,g=sm(c);ge.appendChild(g)}(()=>{var y,T;let c=(T=(y=r.layout)==null?void 0:y.slots)!=null?T:{},g=D=>{switch(D){case"body-top":return ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Fe;case"footer-top":return Rt;case"composer":return jt;case"footer-bottom":return mn;default:return null}},b=(D,N)=>{var j;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")De.insertBefore(N,De.firstChild);else if(D==="header-right")De.appendChild(N);else{let R=De.querySelector(".persona-flex-col");R?(j=R.parentNode)==null||j.insertBefore(N,R.nextSibling):De.appendChild(N)}break;case"body-top":{let R=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(N):G.insertBefore(N,G.firstChild);break}case"body-bottom":G.appendChild(N);break;case"footer-top":Rt.replaceWith(N);break;case"footer-bottom":mn.replaceWith(N);break;default:break}};for(let[D,N]of Object.entries(c))if(N)try{let j=N({config:r,defaultContent:()=>g(D)});j&&b(D,j)}catch(j){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,j)}})();let jr=c=>{var N,j;let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let y=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let T=y.getAttribute("data-message-id");if(!T)return;let D=b.getAttribute("data-bubble-type");if(D==="reasoning")rs.has(T)?rs.delete(T):rs.add(T),wu(T,y);else if(D==="tool")os.has(T)?os.delete(T):os.add(T),Cu(T,y,r);else if(D==="approval"){let R=r.approval!==!1?r.approval:void 0,Se=((N=R==null?void 0:R.detailsDisplay)!=null?N:"collapsed")==="expanded",me=(j=ii.get(T))!=null?j:Se;ii.set(T,!me),Fu(T,y,r)}be.delete(T)};Fe.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),jr(c))}),Fe.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),jr(c))});let Ir=new Map;Fe.addEventListener("click",c=>{var N;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest("[data-actions-for]");if(!y)return;let T=y.getAttribute("data-actions-for");if(!T)return;let D=b.getAttribute("data-action");if(D==="copy"){let R=$.getMessages().find(Se=>Se.id===T);if(R&&Q.onCopy){let Se=R.content||"";navigator.clipboard.writeText(Se).then(()=>{b.classList.add("persona-message-action-success");let me=Ce("check",14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let Z=Ce("copy",14,"currentColor",2);Z&&(b.innerHTML="",b.appendChild(Z))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),Q.onCopy(R)}}else if(D==="upvote"||D==="downvote"){let R=((N=Ir.get(T))!=null?N:null)===D,Se=D==="upvote"?"thumbs-up":"thumbs-down";if(R){Ir.delete(T),b.classList.remove("persona-message-action-active");let me=Ce(Se,14,"currentColor",2);me&&(b.innerHTML="",b.appendChild(me))}else{let me=D==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${me}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=Ce(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}Ir.set(T,D),b.classList.add("persona-message-action-active");let we=Ce(Se,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(we)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let _e=$.getMessages().find(ot=>ot.id===T);_e&&Q.onFeedback&&Q.onFeedback({type:D,messageId:_e.id,message:_e})}}}),Fe.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest(".persona-approval-bubble");if(!y)return;let T=y.getAttribute("data-message-id");if(!T)return;let D=b.getAttribute("data-approval-action");if(!D)return;let N=D==="approve"?"approved":"denied",R=$.getMessages().find(me=>me.id===T);if(!(R!=null&&R.approval))return;let Se=y.querySelector("[data-approval-buttons]");Se&&Se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),R.approval.toolType==="webmcp"?$.resolveWebMcpApproval(T,N):$.resolveApproval(R.approval,N)});let At=null,On=null,Fn={artifacts:[],selectedId:null},An=!1,kt={current:null};Fe.addEventListener("click",c=>{var Z,we,Ee,_e,ot;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||((Ee=(we=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Ee.call(we,{type:"download",artifactId:y}))===!0)return;let D=$.getArtifactById(y),N=D==null?void 0:D.markdown,j=(D==null?void 0:D.title)||"artifact";if(!N){let ze=b.closest("[data-open-artifact]"),mt=ze==null?void 0:ze.closest("[data-message-id]"),dt=mt==null?void 0:mt.getAttribute("data-message-id");if(dt){let ke=$.getMessages().find(Ue=>Ue.id===dt);if(ke!=null&&ke.rawContent)try{let Ue=JSON.parse(ke.rawContent);N=(_e=Ue==null?void 0:Ue.props)==null?void 0:_e.markdown,j=((ot=Ue==null?void 0:Ue.props)==null?void 0:ot.title)||j}catch{}}}if(!N)return;let R=new Blob([N],{type:"text/markdown"}),Se=URL.createObjectURL(R),me=document.createElement("a");me.href=Se,me.download=`${j}.md`,me.click(),URL.revokeObjectURL(Se)}),Fe.addEventListener("click",c=>{var D,N,j;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((j=(N=(D=r.features)==null?void 0:D.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:j.call(N,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),An=!1,$.selectArtifact(y),jn())}),Fe.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let er=Ie.composerOverlay,tr=(c,g,b)=>{var j,R,Se,me;let y=g.trim();if(!y||!kt.current)return;let T=(j=c.getAttribute("data-tool-call-id"))!=null?j:"",D=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:y,answers:b.structured,values:(R=b.values)!=null?R:b.source==="multi"?y.split(", "):[y],isFreeText:D,source:b.source},bubbles:!0,composed:!0})),Ho(er,T);let N=kt.current.getMessages().find(Z=>{var we;return((we=Z.toolCall)==null?void 0:we.id)===T});(Se=N==null?void 0:N.agentMetadata)!=null&&Se.awaitingLocalTool?kt.current.resolveAskUserQuestion(N,(me=b.structured)!=null?me:y):kt.current.sendMessage(y)},$n=c=>{var T;let g=kt.current;if(!g)return;let b=(T=c.getAttribute("data-tool-call-id"))!=null?T:"",y=g.getMessages().find(D=>{var N;return((N=D.toolCall)==null?void 0:N.id)===b});y&&g.persistAskUserQuestionProgress(y,{answers:si(c,y),currentIndex:ur(c)})},Ur=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Wr=c=>{var T,D,N;if(((D=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let g=ur(c),b=as(c);if(g>=b-1)return;let y=(N=kt.current)==null?void 0:N.getMessages().find(j=>{var R;return((R=j.toolCall)==null?void 0:R.id)===c.getAttribute("data-tool-call-id")});y&&(ai(c,y,r,g+1),$n(c))};er.addEventListener("click",c=>{var D,N,j,R,Se,me,Z,we,Ee,_e,ot,ze,mt,dt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;let T=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),T==="dismiss"){let Pe=(D=y.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Ho(er,Pe);let ke=(N=kt.current)==null?void 0:N.getMessages().find(Ue=>{var Qe;return((Qe=Ue.toolCall)==null?void 0:Qe.id)===Pe});(j=ke==null?void 0:ke.agentMetadata)!=null&&j.awaitingLocalTool&&((R=kt.current)==null||R.markAskUserQuestionResolved(ke),(Se=kt.current)==null||Se.resolveAskUserQuestion(ke,"(dismissed)"));return}if(T==="pick"){let Pe=b.getAttribute("data-option-label");if(!Pe)return;let ke=y.getAttribute("data-multi-select")==="true",Ue=po(y);if(Ue&&ke){let Qe=Ro(y)[ur(y)],xt=new Set(Array.isArray(Qe)?Qe:[]);xt.has(Pe)?xt.delete(Pe):xt.add(Pe),uo(y,Array.from(xt)),$n(y);return}if(Ue){uo(y,Pe),$n(y),Wr(y);return}if(ke){let Qe=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",Qe?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!Qe);let xt=y.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=rl(y).length===0);return}tr(y,Pe,{source:"pick",values:[Pe]});return}if(T==="submit-multi"){let Pe=rl(y);if(Pe.length===0)return;tr(y,Pe.join(", "),{source:"multi",values:Pe});return}if(T==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let ke=Pe.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(T==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(T==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),ke=(me=Pe==null?void 0:Pe.value)!=null?me:"";if(!ke.trim())return;if(po(y)){uo(y,ke.trim()),$n(y),Wr(y);return}tr(y,ke,{source:"free-text"});return}if(T==="next"||T==="back"){if(!kt.current)return;let Pe=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",ke=kt.current.getMessages().find(Ne=>{var ee;return((ee=Ne.toolCall)==null?void 0:ee.id)===Pe});if(!ke)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(Ee=(we=Ue==null?void 0:Ue.value)==null?void 0:we.trim())!=null?Ee:"";if(Qe){let Ne=Ro(y)[ur(y)];(typeof Ne!="string"||Ne!==Qe)&&uo(y,Qe)}let xt=T==="next"?1:-1,k=ur(y)+xt;ai(y,ke,r,k),$n(y);return}if(T==="submit-all"){if(!kt.current)return;let Pe=(_e=y.getAttribute("data-tool-call-id"))!=null?_e:"",ke=kt.current.getMessages().find(Ne=>{var ee;return((ee=Ne.toolCall)==null?void 0:ee.id)===Pe});if(!ke)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(ze=(ot=Ue==null?void 0:Ue.value)==null?void 0:ot.trim())!=null?ze:"";Qe&&uo(y,Qe);let xt=si(y,ke);kt.current.persistAskUserQuestionProgress(ke,{answers:xt,currentIndex:ur(y)});let k=Ur(xt);tr(y,k||"(submitted)",{source:"submit-all",structured:xt});return}if(T==="skip"){if(!kt.current)return;let Pe=(mt=y.getAttribute("data-tool-call-id"))!=null?mt:"",ke=kt.current.getMessages().find(ee=>{var tt;return((tt=ee.toolCall)==null?void 0:tt.id)===Pe});if(!ke)return;let Ue=po(y),Qe=ur(y),xt=as(y),k=Qe>=xt-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Ho(er,Pe),(dt=ke.agentMetadata)!=null&&dt.awaitingLocalTool&&(kt.current.markAskUserQuestionResolved(ke),kt.current.resolveAskUserQuestion(ke,"(dismissed)"));return}uo(y,"");let Ne=y.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),k){let ee=si(y,ke),tt=Ur(ee);tr(y,tt||"(skipped)",{source:"submit-all",structured:ee});return}ai(y,ke,r,Qe+1),$n(y);return}}),er.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let b=c.target;if(!((D=b.matches)!=null&&D.call(b,'[data-ask-free-text-input="true"]')))return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let T=b.value;if(T.trim()){if(po(y)){uo(y,T.trim()),$n(y),Wr(y);return}tr(y,T,{source:"free-text"})}});let qr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let b=er.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),D=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",qr);let _n=null,Bt=null,Sn=null,nr=null,zr=()=>{};function Rr(){nr==null||nr(),nr=null}let Vr=()=>{var N;if(!_n||!Bt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){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 y=_n.firstElementChild;if(!y||y===Bt)return;let T=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${T}px`,Bt.style.zIndex="5";let D=y.offsetWidth-T/2;Bt.style.left=`${Math.max(0,D)}px`},Er=()=>{},jn=()=>{var b,y,T,D,N;if(!At||!mr(r))return;di(e,r),pi(e,r),Er();let c=(D=(T=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.layout)==null?void 0:T.narrowHostMaxWidth)!=null?D:520,g=re.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),At.update(Fn),An?(At.setMobileOpen(!1),At.element.classList.add("persona-hidden"),(N=At.backdrop)==null||N.classList.add("persona-hidden")):Fn.artifacts.length>0&&(At.element.classList.remove("persona-hidden"),At.setMobileOpen(!0)),zr()};if(mr(r)){re.style.position="relative";let c=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");c.appendChild(ge),At=Ku(r,{onSelect:b=>{var y;return(y=kt.current)==null?void 0:y.selectArtifact(b)},onDismiss:()=>{An=!0,jn()}}),At.element.classList.add("persona-hidden"),_n=g,g.appendChild(c),g.appendChild(At.element),At.backdrop&&re.appendChild(At.backdrop),re.appendChild(g),zr=()=>{var y,T,D,N;if(!_n||!At)return;if(!(((D=(T=(y=r.features)==null?void 0:y.artifacts)==null?void 0:T.layout)==null?void 0:D.resizable)===!0)){Sn==null||Sn(),Sn=null,Rr(),Bt&&(Bt.remove(),Bt=null),At.element.style.removeProperty("width"),At.element.style.removeProperty("maxWidth");return}if(!Bt){let j=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");j.setAttribute("role","separator"),j.setAttribute("aria-orientation","vertical"),j.setAttribute("aria-label","Resize artifacts panel"),j.tabIndex=0;let R=e.ownerDocument,Se=(N=R.defaultView)!=null?N:window,me=Z=>{var mt,dt;if(!At||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Se.innerWidth<=640)return;Z.preventDefault(),Rr();let we=Z.clientX,Ee=At.element.getBoundingClientRect().width,_e=(dt=(mt=r.features)==null?void 0:mt.artifacts)==null?void 0:dt.layout,ot=Pe=>{let ke=_n.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),Qe=Ue?0:Qu(_n,Se),xt=Ue?0:j.getBoundingClientRect().width||6,k=Ee-(Pe.clientX-we),Ne=Yu(k,ke,Qe,xt,_e==null?void 0:_e.resizableMinWidth,_e==null?void 0:_e.resizableMaxWidth);At.element.style.width=`${Ne}px`,At.element.style.maxWidth="none",Vr()},ze=()=>{R.removeEventListener("pointermove",ot),R.removeEventListener("pointerup",ze),R.removeEventListener("pointercancel",ze),nr=null;try{j.releasePointerCapture(Z.pointerId)}catch{}};nr=ze,R.addEventListener("pointermove",ot),R.addEventListener("pointerup",ze),R.addEventListener("pointercancel",ze);try{j.setPointerCapture(Z.pointerId)}catch{}};j.addEventListener("pointerdown",me),Bt=j,_n.insertBefore(j,At.element),Sn=()=>{j.removeEventListener("pointerdown",me)}}if(Bt){let j=Fn.artifacts.length>0&&!An;Bt.classList.toggle("persona-hidden",!j),Vr()}},Er=()=>{var Se,me,Z,we,Ee,_e,ot,ze,mt,dt,Pe,ke,Ue,Qe;if(!S||!At||((me=(Se=r.launcher)==null?void 0:Se.sidebarMode)!=null?me:!1)||un(r)&&Ar(r).reveal==="emerge")return;let y=(Z=e.ownerDocument.defaultView)!=null?Z:window,T=(Ee=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Ee:!0,D=(ot=(_e=r.launcher)==null?void 0:_e.mobileBreakpoint)!=null?ot:640;if(T&&y.innerWidth<=D||!Xu(r,S))return;let N=(dt=(mt=(ze=r.launcher)==null?void 0:ze.width)!=null?mt:r.launcherWidth)!=null?dt:pr,j=(Qe=(Ue=(ke=(Pe=r.features)==null?void 0:Pe.artifacts)==null?void 0:ke.layout)==null?void 0:Ue.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!An?(re.style.width=j,re.style.maxWidth=j):(re.style.width=N,re.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(On=new ResizeObserver(()=>{jn()}),On.observe(re))}else re.appendChild(ge),F()&&Ye&&(Ie.peekBanner&&Ye.appendChild(Ie.peekBanner),Ye.appendChild($e));e.appendChild(ue),Ye&&e.appendChild(Ye);let gr=()=>{var Ne,ee,tt,Ot,Nt,qt,at,ln,Kn,Ve,wt,Jn,on,cr,Gn,wo,zo,Vo,Gt,Co,to,no,Fr,Ao,nt,bn,gn,cn;if(F()){re.style.width="100%",re.style.maxWidth="100%";let gt=(ee=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?ee:{},it=ue.dataset.state==="expanded",Et=(tt=gt.expandedSize)!=null?tt:"anchored";if(!(it&&Et!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let en=(Nt=(Ot=r.theme)==null?void 0:Ot.components)==null?void 0:Nt.panel,kr=_s(r),sn=(To,Ca)=>{var ks;return To==null||To===""?Ca:(ks=es(kr,To))!=null?ks:To},En="1px solid var(--persona-border)",dr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",So="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=sn(en==null?void 0:en.border,En),ge.style.borderRadius=sn(en==null?void 0:en.borderRadius,So),ge.style.boxShadow=sn(en==null?void 0:en.shadow,dr),ge.style.overflow="hidden";return}let c=un(r),g=(at=(qt=r.launcher)==null?void 0:qt.sidebarMode)!=null?at:!1,b=c||g||((Kn=(ln=r.launcher)==null?void 0:ln.fullHeight)!=null?Kn:!1),y=((Ve=r.launcher)==null?void 0:Ve.enabled)===!1,T=(Jn=(wt=r.theme)==null?void 0:wt.components)==null?void 0:Jn.panel,D=_s(r),N=(gt,it)=>{var Et;return gt==null||gt===""?it:(Et=es(D,gt))!=null?Et:gt},j=(on=e.ownerDocument.defaultView)!=null?on:window,R=(Gn=(cr=r.launcher)==null?void 0:cr.mobileFullscreen)!=null?Gn:!0,Se=(zo=(wo=r.launcher)==null?void 0:wo.mobileBreakpoint)!=null?zo:640,me=j.innerWidth<=Se,Z=R&&me&&S,we=(Gt=(Vo=r.launcher)==null?void 0:Vo.position)!=null?Gt:"bottom-left",Ee=we==="bottom-left"||we==="top-left",_e=(to=(Co=r.launcher)==null?void 0:Co.zIndex)!=null?to:vn,ot=g||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":g?Ee?"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))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(ze="none",ot="none");let mt=g||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",dt=N(T==null?void 0:T.border,ot),Pe=N(T==null?void 0:T.shadow,ze),ke=N(T==null?void 0:T.borderRadius,mt),Ue=G.scrollTop;e.style.cssText="",ue.style.cssText="",re.style.cssText="",ge.style.cssText="",G.style.cssText="",$e.style.cssText="";let Qe=()=>{var it;if(Ue<=0)return;((it=G.ownerDocument.defaultView)!=null?it:window).requestAnimationFrame(()=>{if(G.scrollTop===Ue)return;let Et=G.scrollHeight-G.clientHeight;Et<=0||(G.scrollTop=Math.min(Ue,Et))})};if(Z){ue.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"),ue.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -37,7 +37,7 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
37
37
  padding: 0 !important;
38
38
  display: flex !important;
39
39
  flex-direction: column !important;
40
- z-index: ${Fe} !important;
40
+ z-index: ${_e} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
42
  `,re.style.cssText=`
43
43
  position: relative !important;
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
52
52
  padding: 0 !important;
53
53
  box-shadow: none !important;
54
54
  border-radius: 0 !important;
55
- `,ce.style.cssText=`
55
+ `,ge.style.cssText=`
56
56
  display: flex !important;
57
57
  flex-direction: column !important;
58
58
  flex: 1 1 0% !important;
@@ -63,19 +63,19 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",_e.style.flexShrink="0",I=!0,E();return}let Te=(Pn=(ht=r==null?void 0:r.launcher)==null?void 0:ht.width)!=null?Pn:r==null?void 0:r.launcherWidth,Re=Te!=null?Te:sr;if(!f&&!c)b&&y?(re.style.width="100%",re.style.maxWidth="100%"):(re.style.width=Re,re.style.maxWidth=Re);else if(c)if(yr(r).reveal==="emerge"){let Kt=yr(r).width;re.style.width=Kt,re.style.maxWidth=Kt}else re.style.width="100%",re.style.maxWidth="100%";if(vr(),re.style.boxShadow=ke,re.style.borderRadius=Me,ce.style.border=it,ce.style.borderRadius=Me,c&&!Z&&(M==null?void 0:M.border)===void 0&&(ce.style.border="none",yr(r).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.height="100%",b&&(ie.style.overflow="hidden"),re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.height="100%",re.style.overflow="hidden",ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",_e.style.flexShrink="0"),ie.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"),!f&&!b&&!c&&((Br=br[he])!=null?Br:br["bottom-right"]).split(" ").forEach(Kt=>ie.classList.add(Kt)),f){let Bt=(In=(Sn=r.launcher)==null?void 0:Sn.sidebarWidth)!=null?In:"420px";ie.style.cssText=`
66
+ `,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",$e.style.flexShrink="0",P=!0,Qe();return}let xt=(Fr=(no=r==null?void 0:r.launcher)==null?void 0:no.width)!=null?Fr:r==null?void 0:r.launcherWidth,k=xt!=null?xt:pr;if(!g&&!c)y&&b?(re.style.width="100%",re.style.maxWidth="100%"):(re.style.width=k,re.style.maxWidth=k);else if(c)if(Ar(r).reveal==="emerge"){let it=Ar(r).width;re.style.width=it,re.style.maxWidth=it}else re.style.width="100%",re.style.maxWidth="100%";if(Er(),re.style.boxShadow=Pe,re.style.borderRadius=ke,ge.style.border=dt,ge.style.borderRadius=ke,c&&!Z&&(T==null?void 0:T.border)===void 0&&(ge.style.border="none",Ar(r).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.height="100%",y&&(ue.style.overflow="hidden"),re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.height="100%",re.style.overflow="hidden",ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.overflow="hidden",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",$e.style.flexShrink="0"),ue.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&&!y&&!c&&((Ao=Sr[we])!=null?Ao:Sr["bottom-right"]).split(" ").forEach(it=>ue.classList.add(it)),g){let gt=(bn=(nt=r.launcher)==null?void 0:nt.sidebarWidth)!=null?bn:"420px";ue.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${Bt} !important;
70
+ width: ${gt} !important;
71
71
  height: 100vh !important;
72
72
  max-height: 100vh !important;
73
73
  margin: 0 !important;
74
74
  padding: 0 !important;
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
- z-index: ${Fe} !important;
78
- ${Se?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
77
+ z-index: ${_e} !important;
78
+ ${Ee?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
79
  `,re.style.cssText=`
80
80
  position: relative !important;
81
81
  display: flex !important;
@@ -87,9 +87,9 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
87
87
  min-height: 0 !important;
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
- box-shadow: ${ke} !important;
91
- border-radius: ${Me} !important;
92
- `,re.style.setProperty("width","100%","important"),re.style.setProperty("max-width","100%","important"),ce.style.cssText=`
90
+ box-shadow: ${Pe} !important;
91
+ border-radius: ${ke} !important;
92
+ `,re.style.setProperty("width","100%","important"),re.style.setProperty("max-width","100%","important"),ge.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
95
95
  flex: 1 1 0% !important;
@@ -98,29 +98,29 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
98
98
  min-height: 0 !important;
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
- border-radius: ${Me} !important;
102
- border: ${it} !important;
103
- `,_e.style.cssText=`
101
+ border-radius: ${ke} !important;
102
+ border: ${dt} !important;
103
+ `,$e.style.cssText=`
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!b&&!c){let Bt="max-height: -moz-available !important; max-height: stretch !important;",Kt=f?"":"padding-top: 1.25em !important;",Wn=f?"":`z-index: ${(Ut=(Ht=r.launcher)==null?void 0:Ht.zIndex)!=null?Ut:fn} !important;`;ie.style.cssText+=Bt+Kt+Wn}E()};lr(),Eo(e,r),ii(e,r),li(e,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",_r)});let Jt=null,Gt=null;gt.push(()=>{Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null}),Fn&&gt.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),gt.push(()=>{xn==null||xn(),xn=null,kr(),Wt&&(Wt.remove(),Wt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),ge&&gt.push(()=>{we!==null&&(cancelAnimationFrame(we),we=null),ve==null||ve.destroy(),ve=null,V==null||V.destroy(),V=null,ee=null});let Un=null,qr=()=>{Un&&(Un(),Un=null),r.colorScheme==="auto"&&(Un=Hi(()=>{Eo(e,r)}))};qr(),gt.push(()=>{Un&&(Un(),Un=null)});let tr=(pc=r.features)==null?void 0:pc.streamAnimation;if(tr!=null&&tr.type&&tr.type!=="none"){let c=Os(tr.type,tr.plugins);c&&(Ni(c,e),gt.push(()=>nu(e)))}let cr=Lu(Et),qn=null,S,zn=!1,dr=Xp(),Lr=new Map,wr=new Map,ss=0,pr=$a(),ur=0,mr=null,Pr=!1,uo=!1,Zs=4,as=24,ea=80,Wo=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=(mc=(uc=r.voiceRecognition)==null?void 0:uc.autoResume)!=null?mc:!1,nr=c=>{o.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Ln=()=>{u(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},ta=()=>{var b,M;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=ul(d.voiceState),f=!!c.active,y=Number((M=c.timestamp)!=null?M:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-y<Sb&&setTimeout(()=>{var D,F;mt.active||(mt.manuallyDeactivated=!1,((F=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:F.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("restore"),S.isVoiceActive()&&_()}):ho("restore"))},1e3)},na=()=>S?Vu(S.getMessages()).filter(c=>!c.__skipPersist):[];function Ro(c){if(!(i!=null&&i.save))return;let y={messages:c?Vu(c):S?na():[],metadata:d,artifacts:On.artifacts,selectedArtifactId:On.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Ir=null,ra=()=>ie.querySelector("#persona-scroll-container")||G,mo=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),Pr=!1},ls=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),uo=!1,mo()},Wr=()=>{if(!hn()||fe){St.parentNode&&St.remove(),St.style.display="none";return}St.parentNode!==ce&&ce.appendChild(St),yt();let c=Bs(G)>0;St.style.display=pr.isFollowing()||!c?"none":""},cs=()=>{pr.pause()&&(ls(),Wr())},zr=()=>{pr.resume(),Wr()},Vr=(c=!1)=>{pr.isFollowing()&&(!c&&!zn||(mr!==null&&(cancelAnimationFrame(mr),mr=null),uo=!0,mr=requestAnimationFrame(()=>{mr=null,uo=!1,pr.isFollowing()&&oa(ra(),c?220:140)})))},oa=(c,f=500)=>{let y=c.scrollTop,b=Bs(c),M=b-y;if(Math.abs(M)<1){ur=c.scrollTop;return}if(Math.abs(M)>=ea){mo(),Pr=!0,c.scrollTop=b,ur=c.scrollTop,Pr=!1;return}mo();let D=performance.now();Pr=!0;let F=R=>1-Math.pow(1-R,3),U=R=>{if(!pr.isFollowing()){mo();return}let Ce=Bs(c);Ce!==b&&(b=Ce,M=b-y);let pe=R-D,Z=Math.min(pe/f,1),he=F(Z),Se=y+M*he;c.scrollTop=Se,ur=c.scrollTop,Z<1?Ir=requestAnimationFrame(U):(c.scrollTop=b,ur=c.scrollTop,Ir=null,Pr=!1)};Ir=requestAnimationFrame(U)},sa=c=>{let f=new Map;c.forEach(y=>{let b=Wo.get(y.id);f.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Wo.clear(),f.forEach((y,b)=>{Wo.set(b,y)})},go=(c,f,y)=>{var Ge,at,it,ke,Me,qe;let b=document.createElement("div"),D=(()=>{var Te;let E=s.find(Re=>Re.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((Te=r.loadingIndicator)!=null&&Te.render)return r.loadingIndicator.render})(),F=(E,Te)=>Te==null?!1:typeof Te=="string"?(E.textContent=Te,!0):(E.appendChild(Te),!0),U=new Set,R=new Set,Ce=s.some(E=>E.renderAskUserQuestion),pe=[],Z=[],he=r.enableComponentStreaming!==!1;if(f.forEach(E=>{var Cn,dn,Ze,lt,An,un,yo,bo,xo,Oo,$o,Vt,vo,Zr;U.add(E.id);let Te=Ce&&oo(E),Re=!Te&&E.role==="assistant"&&!E.variant&&he&&ll(E);if(!Re&&wr.has(E.id)){let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),wr.delete(E.id)}let Ke=oo(E)?`:${(Cn=E.agentMetadata)!=null&&Cn.askUserQuestionAnswered?"a":"u"}:${(dn=E.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(E.agentMetadata.askUserQuestionAnswers).length:0}`:"",xe=Gp(E,ss)+Ke,kt=Te||Re?null:Qp(dr,E.id,xe);if(kt){b.appendChild(kt.cloneNode(!0)),oo(E)&&((Ze=E.toolCall)!=null&&Ze.id)&&((lt=E.agentMetadata)==null?void 0:lt.awaitingLocalTool)===!0&&!((An=E.agentMetadata)!=null&&An.askUserQuestionAnswered)&&(R.add(E.toolCall.id),Js(E,r,Ie.composerOverlay));return}let st=null,Qt=s.find(ht=>!!(E.variant==="reasoning"&&ht.renderReasoning||E.variant==="tool"&&ht.renderToolCall||E.variant==="approval"&&ht.renderApproval||!E.variant&&ht.renderMessage)),cn=(un=r.layout)==null?void 0:un.messages;if(oo(E)&&((yo=E.agentMetadata)==null?void 0:yo.askUserQuestionAnswered)===!0){Lr.delete(E.id);let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(oo(E)&&((xo=(bo=r.features)==null?void 0:bo.askUserQuestion)==null?void 0:xo.enabled)!==!1){let ht=s.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(ht&&Lt.current){let Pn=Lr.get(E.id),Br=Pn!==xe,Sn=null;if(Br){let{payload:Ut,complete:Bt}=so(E),Kt=E.id,Wn=()=>{var Kn;return(Kn=Lt.current)==null?void 0:Kn.getMessages().find(tn=>tn.id===Kt)};Sn=ht.renderAskUserQuestion({message:E,payload:Ut,complete:Bt,resolve:Kn=>{var Ar;let tn=Wn();tn&&((Ar=Lt.current)==null||Ar.resolveAskUserQuestion(tn,Kn))},dismiss:()=>{var tn,Ar,Dr;let Kn=Wn();(tn=Kn==null?void 0:Kn.agentMetadata)!=null&&tn.awaitingLocalTool&&((Ar=Lt.current)==null||Ar.markAskUserQuestionResolved(Kn),(Dr=Lt.current)==null||Dr.resolveAskUserQuestion(Kn,"(dismissed)"))},config:r})}let In=Pn!=null;if(Br&&Sn===null&&!In){((Oo=E.agentMetadata)==null?void 0:Oo.awaitingLocalTool)===!0&&!(($o=E.agentMetadata)!=null&&$o.askUserQuestionAnswered)&&(R.add(E.toolCall.id),Js(E,r,Ie.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${E.id}`,Ht.setAttribute("data-wrapper-id",E.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),b.appendChild(Ht),pe.push({messageId:E.id,fingerprint:xe,bubble:Sn});return}else{((Vt=E.agentMetadata)==null?void 0:Vt.awaitingLocalTool)===!0&&!((vo=E.agentMetadata)!=null&&vo.askUserQuestionAnswered)&&(R.add(E.toolCall.id),Js(E,r,Ie.composerOverlay));return}}else if(Qt)if(E.variant==="reasoning"&&E.reasoning&&Qt.renderReasoning){if(!je)return;st=Qt.renderReasoning({message:E,defaultRenderer:()=>qi(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Qt.renderToolCall){if(!Ne)return;st=Qt.renderToolCall({message:E,defaultRenderer:()=>zi(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Qt.renderApproval){if(r.approval===!1)return;st=Qt.renderApproval({message:E,defaultRenderer:()=>Yi(E,r),config:r})}else Qt.renderMessage&&(st=Qt.renderMessage({message:E,defaultRenderer:()=>{let ht=Vs(E,y,cn,r.messageActions,Q,{loadingIndicatorRenderer:D,widgetConfig:r});return E.role!=="user"&&nl(ht,E,r,S),ht},config:r}));if(!st&&Re){let ht=cl(E);if(ht){let Pn=wr.get(E.id),Br=Pn!==xe,Sn=r.wrapComponentDirectiveInBubble!==!1,In=null;if(Br){let Ht=il(ht,{config:r,message:E,transform:y});if(Ht)if(Sn){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${E.id}`,Ut.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let Bt=document.createElement("div");Bt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Bt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),Ut.appendChild(Bt)}Ut.appendChild(Ht),In=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${E.id}`,Ut.setAttribute("data-message-id",E.id),Ut.setAttribute("data-persona-component-directive","true"),E.content&&E.content.trim()){let Bt=document.createElement("div");Bt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Bt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),Ut.appendChild(Bt)}Ut.appendChild(Ht),In=Ut}}if(In||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${E.id}`,Ht.setAttribute("data-wrapper-id",E.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),Sn||Ht.classList.add("persona-w-full"),b.appendChild(Ht),Z.push({messageId:E.id,fingerprint:xe,bubble:In});return}}}if(!st)if(E.variant==="reasoning"&&E.reasoning){if(!je)return;st=qi(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!Ne)return;st=zi(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;st=Yi(E,r)}else{let ht=(Zr=r.layout)==null?void 0:Zr.messages;ht!=null&&ht.renderUserMessage&&E.role==="user"?st=ht.renderUserMessage({message:E,config:r,streaming:!!E.streaming}):ht!=null&&ht.renderAssistantMessage&&E.role==="assistant"?st=ht.renderAssistantMessage({message:E,config:r,streaming:!!E.streaming}):st=Vs(E,y,ht,r.messageActions,Q,{loadingIndicatorRenderer:D,widgetConfig:r}),E.role!=="user"&&st&&nl(st,E,r,S)}let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-${E.id}`,It.setAttribute("data-wrapper-id",E.id),E.role==="user"&&It.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&It.classList.add("persona-w-full"),It.appendChild(st),Yp(dr,E.id,xe,It),b.appendChild(It)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let Re=Te.getAttribute("data-persona-ask-sheet-for");Re&&!R.has(Re)&&Lo(Ie.composerOverlay,Re)}),(at=(Ge=r.features)==null?void 0:Ge.toolCallDisplay)!=null&&at.grouped){let E=[],Te=[];f.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&Ne){Te.push(Re);return}Te.length>1&&E.push(Te),Te=[]}),Te.length>1&&E.push(Te),E.forEach((Re,Ke)=>{var dn,Ze;let xe=Re.map(lt=>Array.from(b.children).find(An=>An instanceof HTMLElement&&An.getAttribute("data-wrapper-id")===lt.id)).filter(lt=>!!lt);if(xe.length<2)return;let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-tool-group-${Ke}-${Re[0].id}`,kt.setAttribute("data-wrapper-id",`tool-group-${Ke}-${Re[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Qt=document.createElement("div");Qt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${Re.length} tools`,It=(Ze=(dn=r.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Ze.call(dn,{messages:Re,toolCalls:Re.map(lt=>lt.toolCall).filter(lt=>!!lt),defaultSummary:cn,config:r});F(Qt,It)||(Qt.textContent=cn);let Cn=document.createElement("div");Cn.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Qt,Cn),kt.appendChild(st),xe[0].before(kt),xe.forEach((lt,An)=>{let un=document.createElement("div");un.className="persona-tool-group-item persona-relative",un.setAttribute("data-persona-tool-group-item","true"),An<xe.length-1&&un.setAttribute("data-persona-tool-group-connector","true"),un.appendChild(lt),Cn.appendChild(un)})})}Zp(dr,U);let Se=f.some(E=>E.role==="assistant"&&E.streaming),Fe=f[f.length-1],nt=(Fe==null?void 0:Fe.role)==="assistant"&&!Fe.streaming&&Fe.variant!=="approval";if(zn&&f.some(E=>E.role==="user")&&!Se&&!nt){let E={config:r,streaming:!0,location:"standalone",defaultRenderer:Xo},Te=s.find(Ke=>Ke.renderLoadingIndicator),Re=null;if(Te!=null&&Te.renderLoadingIndicator&&(Re=Te.renderLoadingIndicator(E)),Re===null&&((it=r.loadingIndicator)!=null&&it.render)&&(Re=r.loadingIndicator.render(E)),Re===null&&(Re=Xo()),Re){let Ke=document.createElement("div"),xe=((ke=r.loadingIndicator)==null?void 0:ke.showBubble)!==!1;Ke.className=xe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ke.setAttribute("data-typing-indicator","true"),Ke.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ke.appendChild(Re);let kt=document.createElement("div");kt.className="persona-flex",kt.id="wrapper-typing-indicator",kt.setAttribute("data-wrapper-id","typing-indicator"),kt.appendChild(Ke),b.appendChild(kt)}}if(!zn&&f.length>0){let E=f[f.length-1],Te={config:r,lastMessage:E,messageCount:f.length},Re=s.find(xe=>xe.renderIdleIndicator),Ke=null;if(Re!=null&&Re.renderIdleIndicator&&(Ke=Re.renderIdleIndicator(Te)),Ke===null&&((Me=r.loadingIndicator)!=null&&Me.renderIdle)&&(Ke=r.loadingIndicator.renderIdle(Te)),Ke){let xe=document.createElement("div"),kt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;xe.className=kt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),xe.setAttribute("data-idle-indicator","true"),xe.appendChild(Ke);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(xe),b.appendChild(st)}}if(Fa(c,b),pe.length>0)for(let{messageId:E,fingerprint:Te,bubble:Re}of pe){let Ke=c.querySelector(`#wrapper-${E}`);Ke&&Re!==null&&(Ke.replaceChildren(Re),Ke.setAttribute("data-bubble-fp",Te),Lr.set(E,Te))}if(Lr.size>0)for(let E of Lr.keys())U.has(E)||Lr.delete(E);if(Z.length>0)for(let{messageId:E,fingerprint:Te,bubble:Re}of Z){let Ke=c.querySelector(`#wrapper-${E}`);Ke&&Re!==null&&(Ke.replaceChildren(Re),Ke.setAttribute("data-bubble-fp",Te),wr.set(E,Te))}if(wr.size>0)for(let E of wr.keys())U.has(E)||wr.delete(E)},Kr=null,aa=()=>{var y;if(Kr)return;let c=b=>{let M=b.composedPath();M.includes(ie)||Qe&&M.includes(Qe)||Rt(!1,"user")};Kr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},ds=()=>{var f;if(!Kr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Kr,!0),Kr=null};gt.push(()=>ds());let Jr=null,ia=()=>{var y;if(Jr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Rt(!1,"user"))};Jr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},ps=()=>{var f;if(!Jr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Jr,!0),Jr=null};gt.push(()=>ps());let Gr=!1,us=new Set,la=()=>{var f,y,b,M;let c=(b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((M=r.features)==null?void 0:M.streamAnimation)},Rr=()=>{var at,it,ke,Me;if(!O())return;let c=Ie.peekBanner,f=Ie.peekTextNode;if(!c||!f)return;if(B){c.classList.remove("persona-pill-peek--visible");return}let y=(at=S==null?void 0:S.getMessages())!=null?at:[],b;for(let qe=y.length-1;qe>=0;qe--){let E=y[qe];if(E.role==="assistant"&&E.content){b=E;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let M=b.content,D=!!b.streaming,F=la(),U=Ua(F),R=U.type!=="none"?Os(U.type,F==null?void 0:F.plugins):null,Ce=((it=R==null?void 0:R.isAnimating)==null?void 0:it.call(R,b))===!0,pe=R!==null&&(D||Ce);pe&&R&&!us.has(R.name)&&(Ni(R,e),us.add(R.name));let Z=pe&&(R!=null&&R.containerClass)?R.containerClass:null,he=(ke=f.dataset.personaPeekStreamClass)!=null?ke:null;he&&he!==Z&&(f.classList.remove(he),delete f.dataset.personaPeekStreamClass),Z&&he!==Z&&(f.classList.add(Z),f.dataset.personaPeekStreamClass=Z),pe?(f.style.setProperty("--persona-stream-step",`${U.speed}ms`),f.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Se=pe?qa(M,U.buffer,R,b,D):M;if(pe&&U.placeholder==="skeleton"&&D&&(!Se||!Se.trim())){let qe=document.createElement("div"),E=_s();E.classList.add("persona-pill-peek__skeleton"),qe.appendChild(E),Fa(f,qe)}else{let qe=Math.max(0,Se.length-100),E=Se.length>100?Se.slice(-100):Se,Te=jo(E);if(!pe||!R){let Re=Se.length>100?`\u2026${E}`:E;f.textContent!==Re&&(f.textContent=Re)}else{let Re=Te;(R.wrap==="char"||R.wrap==="word")&&(Re=$s(Te,R.wrap,`peek-${b.id}`,{skipTags:R.skipTags,startIndex:qe}));let Ke=document.createElement("div");if(Ke.innerHTML=Re,R.useCaret&&E.length>0){let xe=za(),kt=Ke.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=kt[kt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(xe,st.nextSibling):Ke.appendChild(xe)}Fa(f,Ke),(Me=R.onAfterRender)==null||Me.call(R,{container:f,bubble:c,messageId:b.id,message:b,speed:U.speed,duration:U.duration})}}let Ge=zn||Gr;c.classList.toggle("persona-pill-peek--visible",Ge)};if(O()){let c=Ie.peekBanner;if(c){let b=M=>{M.preventDefault(),M.stopPropagation(),Rt(!0,"user")};c.addEventListener("pointerdown",b),gt.push(()=>{c.removeEventListener("pointerdown",b)})}let f=()=>{Gr||(Gr=!0,Rr())},y=()=>{Gr&&(Gr=!1,Rr())};re.addEventListener("pointerenter",f),re.addEventListener("pointerleave",y),gt.push(()=>{re.removeEventListener("pointerenter",f),re.removeEventListener("pointerleave",y)}),Qe&&(Qe.addEventListener("pointerenter",f),Qe.addEventListener("pointerleave",y),gt.push(()=>{Qe.removeEventListener("pointerenter",f),Qe.removeEventListener("pointerleave",y)}))}let ca=c=>{var he,Se,Fe,nt,Ge,at,it,ke;let f=(Se=(he=r.launcher)==null?void 0:he.composerBar)!=null?Se:{},y=(Fe=f.expandedSize)!=null?Fe:"anchored",b=(nt=f.bottomOffset)!=null?nt:"16px",M=f.collapsedMaxWidth,D=(Ge=f.expandedMaxWidth)!=null?Ge:"880px",F=(at=f.expandedTopOffset)!=null?at:"5vh",U=(it=f.modalMaxWidth)!=null?it:"880px",R=(ke=f.modalMaxHeight)!=null?ke:"min(90vh, 800px)",Ce="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",Z=ie.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Qe){let Me=Qe.style;Me.bottom=b,Me.width=M!=null?M:""}if(c&&y!=="fullscreen"){if(y==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=U,Z.maxWidth=Ce,Z.maxHeight=R,Z.height=R;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${pe})`,Z.top=F,Z.width=D,Z.maxWidth=Ce}},Xr=()=>{var R,Ce,pe,Z,he,Se,Fe,nt;if(!$())return;if(O()){let at=(pe=((Ce=(R=r.launcher)==null?void 0:R.composerBar)!=null?Ce:{}).expandedSize)!=null?pe:"anchored",it=B?"expanded":"collapsed";ie.dataset.state=it,ie.dataset.expandedSize=at,Qe&&(Qe.dataset.state=it,Qe.dataset.expandedSize=at),ie.style.removeProperty("display"),ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ca(B),ce.style.display=B?"flex":"none",lr(),B?(aa(),ia()):(ds(),ps()),Rr();return}let c=an(r),f=(Z=e.ownerDocument.defaultView)!=null?Z:window,y=(Se=(he=r.launcher)==null?void 0:he.mobileBreakpoint)!=null?Se:640,b=(nt=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?nt:!0,M=f.innerWidth<=y,D=b&&M&&T,F=yr(r).reveal;B?(ie.style.removeProperty("display"),ie.style.display=c?"flex":"",ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-95","persona-opacity-0"),re.classList.add("persona-scale-100","persona-opacity-100"),Ee?Ee.element.style.display="none":Je&&(Je.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!D?(ie.style.removeProperty("display"),ie.style.display="flex",ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ie.style.setProperty("display","none","important"),ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ie.style.display="",ie.classList.add("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100"),re.classList.add("persona-scale-95","persona-opacity-0")),Ee?Ee.element.style.display=c?"none":"":Je&&(Je.style.display=c?"none":""))},Rt=(c,f="user")=>{var D,F;if(!$()||B===c)return;let y=B;B=c,Xr();let b=(()=>{var Fe,nt,Ge,at,it,ke,Me,qe,E,Te;let U=(nt=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?nt:!1,R=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,Ce=(it=(at=r.launcher)==null?void 0:at.mobileFullscreen)!=null?it:!0,pe=(Me=(ke=r.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Me:640,Z=R.innerWidth<=pe,he=an(r)&&Ce&&Z,Se=O()&&((Te=(E=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:E.expandedSize)!=null?Te:"fullscreen")==="fullscreen";return U||Ce&&Z&&T||he||Se})();if(B&&b){if(!Jt){let U=e.getRootNode(),R=U instanceof ShadowRoot?U.host:e.closest(".persona-host");R&&(Jt=Fi(R,(F=(D=r.launcher)==null?void 0:D.zIndex)!=null?F:fn))}Gt||(Gt=Oi(e.ownerDocument))}else B||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null);B&&(Pt(),Vr(!0));let M={open:B,source:f,timestamp:Date.now()};B&&!y?o.emit("widget:opened",M):!B&&y&&o.emit("widget:closed",M),o.emit("widget:state",{open:B,launcherEnabled:T,voiceActive:mt.active,streaming:S.isStreaming()})},Ho=c=>{_t(c?"stop":"send"),q&&(q.disabled=c),cr.buttons.forEach(f=>{f.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Bo=()=>{mt.active||de&&de.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Bo(),200)});let ms=()=>{var y,b,M,D,F,U,R,Ce,pe,Z,he;Hn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",Xn.textContent=(D=(M=r.copy)==null?void 0:M.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",de.placeholder=(U=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?U:"How can I help...";let c=G.querySelector("[data-persona-intro-card]");if(c){let Se=((R=r.copy)==null?void 0:R.showWelcomeCard)!==!1;c.style.display=Se?"":"none",Se?(G.classList.remove("persona-gap-3"),G.classList.add("persona-gap-6")):(G.classList.remove("persona-gap-6"),G.classList.add("persona-gap-3"))}!((pe=(Ce=r.sendButton)==null?void 0:Ce.useIcon)!=null&&pe)&&!(S!=null&&S.isStreaming())&&(ae.textContent=(he=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?he:"Send"),de.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',de.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(f=>({...f,sessionId:c}))}});let Cr=null,da=()=>{Cr==null&&(Cr=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Cr),Cr=null;return}let f=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=Ta(f-b))})},100))};if(S=new Is(r,{onMessagesChanged(c){go($e,c,We),da(),S&&(c.some(M=>M.role==="user")?cr.render([],S,de,c):cr.render(r.suggestionChips,S,de,c,r.suggestionChipsConfig)),Vr(!zn),sa(c);let f=[...c].reverse().find(b=>b.role==="user"),y=mt.lastUserMessageId;f&&f.id!==y&&(mt.lastUserMessageId=f.id,o.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Ro(c),Rr()},onStatusChanged(c){var b;let f=(b=r.statusIndicator)!=null?b:{};ue(ln,(M=>{var D,F,U,R;return M==="idle"?(D=f.idleText)!=null?D:gn.idle:M==="connecting"?(F=f.connectingText)!=null?F:gn.connecting:M==="connected"?(U=f.connectedText)!=null?U:gn.connected:M==="error"?(R=f.errorText)!=null?R:gn.error:gn[M]})(c),f,c)},onStreamingChanged(c){zn=c,Ho(c),S&&go($e,S.getMessages(),We),c||Vr(!0),Rr()},onVoiceStatusChanged(c){var f,y;if(((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":K(),k();break;case"speaking":K(),Y();break;default:c==="idle"&&S.isBargeInActive()?(K(),_(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,K(),nr("system"),Ln());break}},onArtifactsState(c){On=c,jn(),Ro()}}),Lt.current=S,((fc=(gc=r.voiceRecognition)==null?void 0:gc.provider)==null?void 0:fc.type)==="runtype")try{S.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&S.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(V||r.onSSEEvent)&&S.setSSEEventCallback((c,f)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,f),le==null||le.processEvent(c,f),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,y,b;c&&(c.metadata&&(d=ul(c.metadata),C.syncFromMetadata()),(f=c.messages)!=null&&f.length&&S.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&S.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var f,y,b;!O()||B||!((b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Rt(!0,"auto")},fs=c=>{var M;if(c.preventDefault(),S.isStreaming()){S.cancel(),le==null||le.reset(),ve==null||ve.update();return}let f=de.value.trim(),y=(M=tt==null?void 0:tt.hasAttachments())!=null?M:!1;if(!f&&!y)return;gs();let b;y&&(b=[],b.push(...tt.getContentParts()),f&&b.push(Ia(f))),de.value="",de.style.height="auto",fo(),S.sendMessage(f,{contentParts:b}),y&&tt.clearAttachments()},pa=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Do={...Oa},No=!1,fo=()=>{Do={...Oa}},ua=()=>S.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),ma=c=>{if(!de)return;No=!0,de.value=c,de.dispatchEvent(new Event("input",{bubbles:!0})),No=!1;let f=de.value.length;de.setSelectionRange(f,f)},hs=()=>{No||fo()},ys=c=>{if(de){if(pa()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=de.selectionStart===0&&de.selectionEnd===0,y=Jp({direction:c.key==="ArrowUp"?"up":"down",history:ua(),currentValue:de.value,atStart:f,state:Do});if(Do=y.state,y.handled){c.preventDefault(),y.value!==void 0&&ma(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(S.isStreaming()){c.preventDefault();return}fo(),c.preventDefault(),ae.click()}}},bs=c=>{c.key!=="Escape"||c.isComposing||S.isStreaming()&&c.composedPath().includes(ce)&&(S.cancel(),le==null||le.reset(),ve==null||ve.update(),fo(),c.preventDefault(),c.stopImmediatePropagation())},xs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!tt)return;let f=Eb(c.clipboardData);f.length!==0&&(c.preventDefault(),await tt.handleFiles(f))},vn=null,Vn=!1,Hr=null,ot=null,vs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ho=(c="user")=>{var D,F,U,R,Ce,pe,Z;if(Vn||S.isStreaming())return;let f=vs();if(!f)return;vn=new f;let b=(F=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?F:2e3;vn.continuous=!0,vn.interimResults=!0,vn.lang="en-US";let M=de.value;vn.onresult=he=>{let Se="",Fe="";for(let Ge=0;Ge<he.results.length;Ge++){let at=he.results[Ge],it=at[0].transcript;at.isFinal?Se+=it+" ":Fe=it}let nt=M+Se+Fe;de.value=nt,Hr&&clearTimeout(Hr),(Se||Fe)&&(Hr=window.setTimeout(()=>{let Ge=de.value.trim();Ge&&vn&&Vn&&(gr(),de.value="",de.style.height="auto",S.sendMessage(Ge,{viaVoice:!0}))},b))},vn.onerror=he=>{he.error!=="no-speech"&&gr()},vn.onend=()=>{if(Vn){let he=de.value.trim();he&&he!==M.trim()&&(de.value="",de.style.height="auto",S.sendMessage(he,{viaVoice:!0})),gr()}};try{if(vn.start(),Vn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),nr(c),Ln(),q){let he=(U=r.voiceRecognition)!=null?U:{};ot={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(R=he.iconName)!=null?R:"mic",iconSize:parseFloat((Z=(pe=he.iconSize)!=null?pe:(Ce=r.sendButton)==null?void 0:Ce.size)!=null?Z:"40")||24};let Se=he.recordingBackgroundColor,Fe=he.recordingIconColor,nt=he.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Se!=null?Se:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let Ge=q.querySelector("svg");Ge&&Ge.setAttribute("stroke",Fe)}nt&&(q.style.borderColor=nt),q.setAttribute("aria-label","Stop voice recognition")}}catch{gr("system")}},gr=(c="user")=>{if(Vn){if(Vn=!1,Hr&&(clearTimeout(Hr),Hr=null),vn){try{vn.stop()}catch{}vn=null}if(mt.active=!1,nr(c),Ln(),q){if(q.classList.remove("persona-voice-recording"),ot){q.style.backgroundColor=ot.backgroundColor,q.style.color=ot.color,q.style.borderColor=ot.borderColor;let f=q.querySelector("svg");f&&f.setAttribute("stroke",ot.color||"currentColor"),ot=null}q.setAttribute("aria-label","Start voice recognition")}}},ga=(c,f)=>{var at,it,ke,Me,qe,E,Te,Re;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((at=c==null?void 0:c.provider)==null?void 0:at.type)==="runtype";if(!(y||b))return null;let D=h("div","persona-send-button-wrapper"),F=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let U=(it=c==null?void 0:c.iconName)!=null?it:"mic",R=(ke=f==null?void 0:f.size)!=null?ke:"40px",Ce=(Me=c==null?void 0:c.iconSize)!=null?Me:R,pe=parseFloat(Ce)||24,Z=(qe=c==null?void 0:c.backgroundColor)!=null?qe:f==null?void 0:f.backgroundColor,he=(E=c==null?void 0:c.iconColor)!=null?E:f==null?void 0:f.textColor;F.style.width=Ce,F.style.height=Ce,F.style.minWidth=Ce,F.style.minHeight=Ce,F.style.fontSize="18px",F.style.lineHeight="1",he?F.style.color=he:F.style.color="var(--persona-text, #111827)";let Fe=be(U,pe,he||"currentColor",1.5);Fe?F.appendChild(Fe):F.textContent="\u{1F3A4}",Z?F.style.backgroundColor=Z:F.style.backgroundColor="",c!=null&&c.borderWidth&&(F.style.borderWidth=c.borderWidth,F.style.borderStyle="solid"),c!=null&&c.borderColor&&(F.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(F.style.paddingLeft=c.paddingX,F.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(F.style.paddingTop=c.paddingY,F.style.paddingBottom=c.paddingY),D.appendChild(F);let nt=(Te=c==null?void 0:c.tooltipText)!=null?Te:"Start voice recognition";if(((Re=c==null?void 0:c.showTooltip)!=null?Re:!1)&&nt){let Ke=h("div","persona-send-button-tooltip");Ke.textContent=nt,D.appendChild(Ke)}return{micButton:F,micButtonWrapper:D}},Qr=()=>{var f,y,b,M,D;if(!q||ot)return;let c=(f=r.voiceRecognition)!=null?f:{};ot={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((D=(M=c.iconSize)!=null?M:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},Ve=(c,f)=>{var D,F,U,R,Ce;if(!q)return;let y=q.querySelector("svg");y&&y.remove();let b=(Ce=ot==null?void 0:ot.iconSize)!=null?Ce:parseFloat((R=(U=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?U:(F=r.sendButton)==null?void 0:F.size)!=null?R:"40")||24,M=be(c,b,f,1.5);M&&q.appendChild(M)},A=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},_=()=>{var M;if(!q)return;Qr();let c=(M=r.voiceRecognition)!=null?M:{},f=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(A(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let D=q.querySelector("svg");D&&D.setAttribute("stroke",y)}b&&(q.style.borderColor=b),q.setAttribute("aria-label","Stop voice recognition")},k=()=>{var U,R,Ce,pe,Z,he,Se,Fe;if(!q)return;Qr();let c=(U=r.voiceRecognition)!=null?U:{},f=S.getVoiceInterruptionMode(),y=(R=c.processingIconName)!=null?R:"loader",b=(pe=(Ce=c.processingIconColor)!=null?Ce:ot==null?void 0:ot.color)!=null?pe:"",M=(he=(Z=c.processingBackgroundColor)!=null?Z:ot==null?void 0:ot.backgroundColor)!=null?he:"",D=(Fe=(Se=c.processingBorderColor)!=null?Se:ot==null?void 0:ot.borderColor)!=null?Fe:"";A(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=M,q.style.borderColor=D;let F=b||"currentColor";q.style.color=F,Ve(y,F),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},Y=()=>{var Ce,pe,Z,he,Se,Fe,nt,Ge,at,it,ke,Me;if(!q)return;Qr();let c=(Ce=r.voiceRecognition)!=null?Ce:{},f=S.getVoiceInterruptionMode(),y=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=(pe=c.speakingIconName)!=null?pe:y,M=(Fe=c.speakingIconColor)!=null?Fe:f==="barge-in"?(he=(Z=c.recordingIconColor)!=null?Z:ot==null?void 0:ot.color)!=null?he:"":(Se=ot==null?void 0:ot.color)!=null?Se:"",D=(at=c.speakingBackgroundColor)!=null?at:f==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(Ge=ot==null?void 0:ot.backgroundColor)!=null?Ge:"",F=(Me=c.speakingBorderColor)!=null?Me:f==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(ke=ot==null?void 0:ot.borderColor)!=null?ke:"";A(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=D,q.style.borderColor=F;let U=M||"currentColor";q.style.color=U,Ve(b,U);let R=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",R),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},K=()=>{var c,f,y;q&&(A(),ot&&(q.style.backgroundColor=(c=ot.backgroundColor)!=null?c:"",q.style.color=(f=ot.color)!=null?f:"",q.style.borderColor=(y=ot.borderColor)!=null?y:"",Ve(ot.iconName,ot.color||"currentColor"),ot=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},J=()=>{var c,f;if(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let y=S.getVoiceStatus(),b=S.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){S.stopVoicePlayback();return}if(S.isBargeInActive()){S.stopVoicePlayback(),S.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Ln(),nr("user"),K()});return}S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),mt.manuallyDeactivated=!S.isVoiceActive(),Ln(),nr("user"),S.isVoiceActive()?_():K()});return}if(Vn){let y=de.value.trim();mt.manuallyDeactivated=!0,Ln(),gr("user"),y&&(de.value="",de.style.height="auto",S.sendMessage(y))}else mt.manuallyDeactivated=!1,Ln(),ho("user")};Bn=J,q&&(q.addEventListener("click",J),gt.push(()=>{var c,f;((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(S.isVoiceActive()&&S.toggleVoice(),K()):gr("system"),q&&q.removeEventListener("click",J)}));let Xe=o.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("auto"),S.isVoiceActive()&&_()}):ho("auto"))},600))});gt.push(Xe);let Oe=o.on("action:resubmit",()=>{setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)});gt.push(Oe);let et=()=>{Rt(!B,"user")},Ee=null,Je=null;if(T&&!O()){let c=s.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:r,defaultRenderer:()=>Us(r,et).element,onToggle:et});f&&(Je=f)}Je||(Ee=Us(r,et))}Ee?e.appendChild(Ee.element):Je&&e.appendChild(Je),Xr(),cr.render(r.suggestionChips,S,de,void 0,r.suggestionChipsConfig),ms(),Ho(S.isStreaming()),Vr(!0),ta(),L&&(!T||O()?setTimeout(()=>Bo(),0):B&&setTimeout(()=>Bo(),200));let Pt=()=>{var R,Ce,pe,Z,he,Se,Fe,nt,Ge,at,it,ke,Me,qe,E,Te,Re,Ke,xe,kt,st,Qt;if(O()){yt(),Xr();return}let c=an(r),f=(Ce=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?Ce:!1,y=c||f||((Z=(pe=r.launcher)==null?void 0:pe.fullHeight)!=null?Z:!1),b=(he=e.ownerDocument.defaultView)!=null?he:window,M=(Fe=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?Fe:!0,D=(Ge=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?Ge:640,F=b.innerWidth<=D,U=M&&F&&T;try{if(U){lr(),Eo(e,r);return}if(I&&(I=!1,lr(),Eo(e,r)),!T&&!c){re.style.height="",re.style.width="";return}if(!f&&!c){let cn=(it=(at=r==null?void 0:r.launcher)==null?void 0:at.width)!=null?it:r==null?void 0:r.launcherWidth,It=cn!=null?cn:sr;re.style.width=It,re.style.maxWidth=It}if(vr(),!y){let cn=b.innerHeight,It=64,Cn=(Me=(ke=r.launcher)==null?void 0:ke.heightOffset)!=null?Me:0,dn=Math.max(200,cn-It),Ze=Math.min(640,dn),lt=Math.max(200,Ze-Cn);re.style.height=`${lt}px`}}finally{if(yt(),Xr(),B&&T){let It=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Te=(E=r.launcher)==null?void 0:E.mobileBreakpoint)!=null?Te:640),Cn=(Ke=(Re=r.launcher)==null?void 0:Re.sidebarMode)!=null?Ke:!1,dn=(kt=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?kt:!0,Ze=an(r)&&dn&&It,lt=Cn||dn&&It&&T||Ze;if(lt&&!Gt){let An=e.getRootNode(),un=An instanceof ShadowRoot?An.host:e.closest(".persona-host");un&&!Jt&&(Jt=Fi(un,(Qt=(st=r.launcher)==null?void 0:st.zIndex)!=null?Qt:fn)),Gt=Oi(e.ownerDocument)}else lt||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null)}}};Pt();let nn=(hc=e.ownerDocument.defaultView)!=null?hc:window;if(nn.addEventListener("resize",Pt),gt.push(()=>nn.removeEventListener("resize",Pt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yt()});c.observe(_e),gt.push(()=>c.disconnect())}ur=G.scrollTop;let Ct=G.scrollHeight,Mt=()=>{let c=G.scrollTop,f=G.scrollHeight,y=f<Ct;Ct=f;let{action:b,nextLastScrollTop:M}=_a({following:pr.isFollowing(),currentScrollTop:c,lastScrollTop:ur,nearBottom:Ds(G,as),userScrollThreshold:Zs,isAutoScrolling:Pr||uo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ur=M,b==="resume"){zr();return}b==="pause"&&cs()};G.addEventListener("scroll",Mt,{passive:!0}),gt.push(()=>G.removeEventListener("scroll",Mt));let rn=c=>{let f=ja({following:pr.isFollowing(),deltaY:c.deltaY,nearBottom:Ds(G,as),resumeWhenNearBottom:!0});f==="pause"?cs():f==="resume"&&zr()};G.addEventListener("wheel",rn,{passive:!0}),gt.push(()=>G.removeEventListener("wheel",rn)),St.addEventListener("click",()=>{G.scrollTop=G.scrollHeight,ur=G.scrollTop,zr(),Vr(!0)}),gt.push(()=>St.remove()),gt.push(()=>{ls()});let pn=()=>{Ue&&(qn&&(Ue.removeEventListener("click",qn),qn=null),$()?(Ue.style.display="",qn=()=>{Rt(!1,"user")},Ue.addEventListener("click",qn)):Ue.style.display="none")};pn(),(()=>{let{clearChatButton:c}=Ie;c&&c.addEventListener("click",()=>{S.clearMessages(),dr.clear(),zr(),Lo(Ie.composerOverlay);try{localStorage.removeItem(rs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},C.syncFromMetadata(),V==null||V.clear(),le==null||le.reset(),ve==null||ve.update()})})(),Ot&&Ot.addEventListener("submit",fs),de==null||de.addEventListener("keydown",ys),de==null||de.addEventListener("input",hs),de==null||de.addEventListener("paste",xs);let Xt=(yc=e.ownerDocument)!=null?yc:document;Xt.addEventListener("keydown",bs,!0);let rr="persona-attachment-drop-active",ws=0,Ci=()=>{ws=0,ce.classList.remove(rr)},Fo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&tt!==null},Sl=c=>{!ui(c.dataTransfer)||!Fo()||(ws++,ws===1&&ce.classList.add(rr))},Tl=c=>{!ui(c.dataTransfer)||!Fo()||(ws--,ws<=0&&Ci())},El=c=>{!ui(c.dataTransfer)||!Fo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Ml=c=>{var y;if(!ui(c.dataTransfer)||!Fo())return;c.preventDefault(),c.stopPropagation(),Ci();let f=Array.from((y=c.dataTransfer.files)!=null?y:[]);f.length!==0&&tt.handleFiles(f)},Yr=!0;ce.addEventListener("dragenter",Sl,Yr),ce.addEventListener("dragleave",Tl,Yr),e.addEventListener("dragover",El,Yr),e.addEventListener("drop",Ml,Yr);let fa=e.ownerDocument,kl=c=>{Fo()&&c.preventDefault()},Ll=c=>{Fo()&&c.preventDefault()};fa.addEventListener("dragover",kl),fa.addEventListener("drop",Ll),gt.push(()=>{Ot&&Ot.removeEventListener("submit",fs),de==null||de.removeEventListener("keydown",ys),de==null||de.removeEventListener("input",hs),de==null||de.removeEventListener("paste",xs),Xt.removeEventListener("keydown",bs,!0)}),gt.push(()=>{ce.removeEventListener("dragenter",Sl,Yr),ce.removeEventListener("dragleave",Tl,Yr),e.removeEventListener("dragover",El,Yr),e.removeEventListener("drop",Ml,Yr),fa.removeEventListener("dragover",kl),fa.removeEventListener("drop",Ll),Ci()}),gt.push(()=>{S.cancel()}),Ee?gt.push(()=>{Ee==null||Ee.destroy()}):Je&&gt.push(()=>{Je==null||Je.remove()});let en={update(c){var tn,Ar,Dr,ha,ya,ba,wo,xa,Cs,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp;let f=r.toolCall,y=r.messageActions,b=(tn=r.layout)==null?void 0:tn.messages,M=r.colorScheme,D=r.loadingIndicator,F=r.iterationDisplay,U=(Ar=r.features)==null?void 0:Ar.showReasoning,R=(Dr=r.features)==null?void 0:Dr.showToolCalls,Ce=(ha=r.features)==null?void 0:ha.toolCallDisplay,pe=(ya=r.features)==null?void 0:ya.reasoningDisplay;r={...r,...c},lr(),Eo(e,r),ii(e,r),li(e,r),jn(),r.colorScheme!==M&&qr();let Z=ci.getForInstance(r.plugins);s.length=0,s.push(...Z),T=(wo=(ba=r.launcher)==null?void 0:ba.enabled)!=null?wo:!0,H=(Cs=(xa=r.launcher)==null?void 0:xa.autoExpand)!=null?Cs:!1,je=(Tc=(Sc=r.features)==null?void 0:Sc.showReasoning)!=null?Tc:!0,Ne=(Mc=(Ec=r.features)==null?void 0:Ec.showToolCalls)!=null?Mc:!0,ye=(Lc=(kc=r.features)==null?void 0:kc.scrollToBottom)!=null?Lc:{},zt(),Wr();let he=ge;if(ge=(Ic=(Pc=r.features)==null?void 0:Pc.showEventStreamToggle)!=null?Ic:!1,ge&&!he){if(V||(ee=new Xs(He),V=new Gs(Pe,ee),le=le!=null?le:new Qs,ee.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),S.setSSEEventCallback((X,xt)=>{var Nt;(Nt=r.onSSEEvent)==null||Nt.call(r,X,xt),le==null||le.processEvent(X,xt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!ut&&De){let X=(Rc=(Wc=r.features)==null?void 0:Wc.eventStream)==null?void 0:Rc.classNames,xt="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"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");ut=h("button",xt),ut.style.width="28px",ut.style.height="28px",ut.style.color=En.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Nt=be("activity","18px","currentColor",1.5);Nt&&ut.appendChild(Nt);let ct=Ie.clearChatButtonWrapper,Tt=Ie.closeButtonWrapper,on=ct||Tt;on&&on.parentNode===De?De.insertBefore(ut,on):De.appendChild(ut),ut.addEventListener("click",()=>{fe?Dn():yn()})}}else!ge&&he&&(Dn(),ut&&(ut.remove(),ut=null),V==null||V.clear(),ee==null||ee.destroy(),V=null,ee=null,le==null||le.reset(),le=null);if(((Hc=r.launcher)==null?void 0:Hc.enabled)===!1&&Ee&&(Ee.destroy(),Ee=null),((Bc=r.launcher)==null?void 0:Bc.enabled)===!1&&Je&&(Je.remove(),Je=null),((Dc=r.launcher)==null?void 0:Dc.enabled)!==!1&&!Ee&&!Je){let X=s.find(xt=>xt.renderLauncher);if(X!=null&&X.renderLauncher){let xt=X.renderLauncher({config:r,defaultRenderer:()=>Us(r,et).element,onToggle:et});xt&&(Je=xt,e.appendChild(Je))}Je||(Ee=Us(r,et),e.appendChild(Ee.element))}Ee&&Ee.update(r),Ae&&((Nc=r.launcher)==null?void 0:Nc.title)!==void 0&&(Ae.textContent=r.launcher.title),Be&&((Fc=r.launcher)==null?void 0:Fc.subtitle)!==void 0&&(Be.textContent=r.launcher.subtitle);let Se=(Oc=r.layout)==null?void 0:Oc.header;if((Se==null?void 0:Se.layout)!==w&&De){let X=Se?qs(r,Se,{showClose:$(),onClose:()=>Rt(!1,"user")}):ro({config:r,showClose:$(),onClose:()=>Rt(!1,"user")});De.replaceWith(X.header),De=X.header,N=X.iconHolder,Ae=X.headerTitle,Be=X.headerSubtitle,Ue=X.closeButton,w=Se==null?void 0:Se.layout}else if(Se&&(N&&(N.style.display=Se.showIcon===!1?"none":""),Ae&&(Ae.style.display=Se.showTitle===!1?"none":""),Be&&(Be.style.display=Se.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=Se.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let X=Se.showClearChat;if(X!==void 0){Ie.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:xt}=Ie;xt&&!xt.classList.contains("persona-absolute")&&(X?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let nt=(($c=r.layout)==null?void 0:$c.showHeader)!==!1;De&&(De.style.display=nt?"":"none");let Ge=((_c=r.layout)==null?void 0:_c.showFooter)!==!1;_e&&(_e.style.display=Ge?"":"none"),yt(),Wr(),T!==W?T?Rt(H,"auto"):(B=!0,Xr()):H!==P&&Rt(H,"auto"),P=H,W=T,Pt(),pn();let ke=JSON.stringify(c.toolCall)!==JSON.stringify(f),Me=JSON.stringify(r.messageActions)!==JSON.stringify(y),qe=JSON.stringify((jc=r.layout)==null?void 0:jc.messages)!==JSON.stringify(b),E=((Uc=r.loadingIndicator)==null?void 0:Uc.render)!==(D==null?void 0:D.render)||((qc=r.loadingIndicator)==null?void 0:qc.renderIdle)!==(D==null?void 0:D.renderIdle)||((zc=r.loadingIndicator)==null?void 0:zc.showBubble)!==(D==null?void 0:D.showBubble),Te=r.iterationDisplay!==F,Re=((Kc=(Vc=r.features)==null?void 0:Vc.showReasoning)!=null?Kc:!0)!==(U!=null?U:!0)||((Gc=(Jc=r.features)==null?void 0:Jc.showToolCalls)!=null?Gc:!0)!==(R!=null?R:!0)||JSON.stringify((Xc=r.features)==null?void 0:Xc.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Qc=r.features)==null?void 0:Qc.reasoningDisplay)!==JSON.stringify(pe);(ke||Me||qe||E||Te||Re)&&S&&(ss++,go($e,S.getMessages(),We));let xe=(Yc=r.launcher)!=null?Yc:{},kt=(Zc=xe.headerIconHidden)!=null?Zc:!1,st=(td=(ed=r.layout)==null?void 0:ed.header)==null?void 0:td.showIcon,Qt=kt||st===!1,cn=xe.headerIconName,It=(nd=xe.headerIconSize)!=null?nd:"48px";if(N){let X=ce.querySelector(".persona-border-b-persona-divider"),xt=X==null?void 0:X.querySelector(".persona-flex-col");if(Qt)N.style.display="none",X&&xt&&!X.contains(xt)&&X.insertBefore(xt,X.firstChild);else{if(N.style.display="",N.style.height=It,N.style.width=It,X&&xt&&(X.contains(N)?N.nextSibling!==xt&&(N.remove(),X.insertBefore(N,xt)):X.insertBefore(N,xt)),cn){let ct=parseFloat(It)||24,Tt=be(cn,ct*.6,"#ffffff",2);Tt?N.replaceChildren(Tt):N.textContent=(rd=xe.agentIconText)!=null?rd:"\u{1F4AC}"}else if(xe.iconUrl){let ct=N.querySelector("img");if(ct)ct.src=xe.iconUrl,ct.style.height=It,ct.style.width=It;else{let Tt=document.createElement("img");Tt.src=xe.iconUrl,Tt.alt="",Tt.className="persona-rounded-xl persona-object-cover",Tt.style.height=It,Tt.style.width=It,N.replaceChildren(Tt)}}else{let ct=N.querySelector("svg"),Tt=N.querySelector("img");(ct||Tt)&&N.replaceChildren(),N.textContent=(od=xe.agentIconText)!=null?od:"\u{1F4AC}"}let Nt=N.querySelector("img");Nt&&(Nt.style.height=It,Nt.style.width=It)}}let Cn=(ad=(sd=r.layout)==null?void 0:sd.header)==null?void 0:ad.showTitle,dn=(ld=(id=r.layout)==null?void 0:id.header)==null?void 0:ld.showSubtitle;if(Ae&&(Ae.style.display=Cn===!1?"none":""),Be&&(Be.style.display=dn===!1?"none":""),Ue){((dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let xt=(pd=xe.closeButtonSize)!=null?pd:"32px",Nt=(ud=xe.closeButtonPlacement)!=null?ud:"inline";Ue.style.height=xt,Ue.style.width=xt;let{closeButtonWrapper:ct}=Ie,Tt=Nt==="top-right",on=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&Tt!==on)if(ct.remove(),Tt)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(ct);else{let pt=(gd=(md=xe.clearChat)==null?void 0:md.placement)!=null?gd:"inline",sn=(hd=(fd=xe.clearChat)==null?void 0:fd.enabled)!=null?hd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Rn=ce.querySelector(".persona-border-b-persona-divider");Rn&&Rn.appendChild(ct)}if(Ue.style.color=xe.closeButtonColor||En.actionIconColor,xe.closeButtonBackgroundColor?(Ue.style.backgroundColor=xe.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let pt=xe.closeButtonBorderWidth||"0px",sn=xe.closeButtonBorderColor||"transparent";Ue.style.border=`${pt} solid ${sn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");xe.closeButtonBorderRadius?(Ue.style.borderRadius=xe.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(Ue.style.paddingLeft=xe.closeButtonPaddingX,Ue.style.paddingRight=xe.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),xe.closeButtonPaddingY?(Ue.style.paddingTop=xe.closeButtonPaddingY,Ue.style.paddingBottom=xe.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let mn=(yd=xe.closeButtonIconName)!=null?yd:"x",fr=(bd=xe.closeButtonIconText)!=null?bd:"\xD7";Ue.innerHTML="";let Tn=be(mn,"28px","currentColor",1);Tn?Ue.appendChild(Tn):Ue.textContent=fr;let Yt=(xd=xe.closeButtonTooltipText)!=null?xd:"Close chat",Jn=(vd=xe.closeButtonShowTooltip)!=null?vd:!0;if(Ue.setAttribute("aria-label",Yt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Jn&&Yt)){let pt=null,sn=()=>{if(pt||!Ue)return;let Co=Ue.ownerDocument,As=Co.body;if(!As)return;pt=Sr(Co,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Ss=Sr(Co,"div");Ss.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ss);let Ao=Ue.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(eo),pt.style.left=`${Ao.left+Ao.width/2}px`,pt.style.top=`${Ao.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Rn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Rn),Ue.addEventListener("focus",sn),Ue.addEventListener("blur",Rn),ct._cleanupTooltip=()=>{Rn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Rn)),Ue&&(Ue.removeEventListener("focus",sn),Ue.removeEventListener("blur",Rn))}}}let{clearChatButton:Ze,clearChatButtonWrapper:lt}=Ie;if(Ze){let X=(wd=xe.clearChat)!=null?wd:{},xt=(Cd=X.enabled)!=null?Cd:!0,Nt=(Sd=(Ad=r.layout)==null?void 0:Ad.header)==null?void 0:Sd.showClearChat,ct=Nt!==void 0?Nt:xt,Tt=(Td=X.placement)!=null?Td:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:on}=Ie;!O()&&on&&!on.classList.contains("persona-absolute")&&(ct?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let mn=Tt==="top-right",fr=lt.classList.contains("persona-absolute");if(!O()&&mn!==fr&&ct){if(lt.remove(),mn)lt.className="persona-absolute persona-top-4 persona-z-50",lt.style.right="48px",ce.style.position="relative",ce.appendChild(lt);else{lt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",lt.style.right="";let Yt=ce.querySelector(".persona-border-b-persona-divider"),Jn=Ie.closeButtonWrapper;Yt&&Jn&&Jn.parentElement===Yt?Yt.insertBefore(lt,Jn):Yt&&Yt.appendChild(lt)}let Tn=Ie.closeButtonWrapper;Tn&&!Tn.classList.contains("persona-absolute")&&(mn?Tn.classList.add("persona-ml-auto"):Tn.classList.remove("persona-ml-auto"))}}if(ct){if(!O()){let pt=(Ed=X.size)!=null?Ed:"32px";Ze.style.height=pt,Ze.style.width=pt}let on=(Md=X.iconName)!=null?Md:"refresh-cw",mn=(kd=X.iconColor)!=null?kd:"";Ze.style.color=mn||En.actionIconColor,Ze.innerHTML="";let fr=O()?"14px":"20px",Tn=be(on,fr,"currentColor",2);if(Tn&&Ze.appendChild(Tn),X.backgroundColor?(Ze.style.backgroundColor=X.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let pt=X.borderWidth||"0px",sn=X.borderColor||"transparent";Ze.style.border=`${pt} solid ${sn}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");X.borderRadius?(Ze.style.borderRadius=X.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),X.paddingX?(Ze.style.paddingLeft=X.paddingX,Ze.style.paddingRight=X.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),X.paddingY?(Ze.style.paddingTop=X.paddingY,Ze.style.paddingBottom=X.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let Yt=(Ld=X.tooltipText)!=null?Ld:"Clear chat",Jn=(Pd=X.showTooltip)!=null?Pd:!0;if(Ze.setAttribute("aria-label",Yt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Jn&&Yt)){let pt=null,sn=()=>{if(pt||!Ze)return;let Co=Ze.ownerDocument,As=Co.body;if(!As)return;pt=Sr(Co,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Ss=Sr(Co,"div");Ss.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ss);let Ao=Ze.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(eo),pt.style.left=`${Ao.left+Ao.width/2}px`,pt.style.top=`${Ao.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Rn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",Rn),Ze.addEventListener("focus",sn),Ze.addEventListener("blur",Rn),lt._cleanupTooltip=()=>{Rn(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",Rn)),Ze&&(Ze.removeEventListener("focus",sn),Ze.removeEventListener("blur",Rn))}}}}let An=r.actionParsers&&r.actionParsers.length?r.actionParsers:[di],un=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick];C=pi({parsers:An,handlers:un,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),We=Ku(r,C,oe),S.updateConfig(r),go($e,S.getMessages(),We),cr.render(r.suggestionChips,S,de,void 0,r.suggestionChipsConfig),ms(),Ho(S.isStreaming());let yo=((Id=r.voiceRecognition)==null?void 0:Id.enabled)===!0,bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),xo=((Rd=(Wd=r.voiceRecognition)==null?void 0:Wd.provider)==null?void 0:Rd.type)==="runtype";if(yo&&(bo||xo))if(!q||!$t){let X=ga(r.voiceRecognition,r.sendButton);X&&(q=X.micButton,$t=X.micButtonWrapper,At.insertBefore($t,Mn),q.addEventListener("click",J),q.disabled=S.isStreaming())}else{let X=(Hd=r.voiceRecognition)!=null?Hd:{},xt=(Bd=r.sendButton)!=null?Bd:{},Nt=(Dd=X.iconName)!=null?Dd:"mic",ct=(Nd=xt.size)!=null?Nd:"40px",Tt=(Fd=X.iconSize)!=null?Fd:ct,on=parseFloat(Tt)||24;q.style.width=Tt,q.style.height=Tt,q.style.minWidth=Tt,q.style.minHeight=Tt;let mn=($d=(Od=X.iconColor)!=null?Od:xt.textColor)!=null?$d:"currentColor";q.innerHTML="";let fr=be(Nt,on,mn,2);fr?q.appendChild(fr):q.textContent="\u{1F3A4}";let Tn=(_d=X.backgroundColor)!=null?_d:xt.backgroundColor;Tn?q.style.backgroundColor=Tn:q.style.backgroundColor="",mn?q.style.color=mn:q.style.color="var(--persona-text, #111827)",X.borderWidth?(q.style.borderWidth=X.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),X.borderColor?q.style.borderColor=X.borderColor:q.style.borderColor="",X.paddingX?(q.style.paddingLeft=X.paddingX,q.style.paddingRight=X.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),X.paddingY?(q.style.paddingTop=X.paddingY,q.style.paddingBottom=X.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Yt=$t==null?void 0:$t.querySelector(".persona-send-button-tooltip"),Jn=(jd=X.tooltipText)!=null?jd:"Start voice recognition";if(((Ud=X.showTooltip)!=null?Ud:!1)&&Jn)if(Yt)Yt.textContent=Jn,Yt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Jn,$t==null||$t.insertBefore(sn,q)}else Yt&&(Yt.style.display="none");$t.style.display="",q.disabled=S.isStreaming()}else q&&$t&&($t.style.display="none",((zd=(qd=r.voiceRecognition)==null?void 0:qd.provider)==null?void 0:zd.type)==="runtype"?S.isVoiceActive()&&S.toggleVoice():Vn&&gr());if(((Vd=r.attachments)==null?void 0:Vd.enabled)===!0)if(!Dt||!Ye){let X=(Kd=r.attachments)!=null?Kd:{},Nt=(Gd=((Jd=r.sendButton)!=null?Jd:{}).size)!=null?Gd:"40px";me||(me=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),me.style.display="none",Ot.insertBefore(me,de)),ne||(ne=document.createElement("input"),ne.type="file",ne.accept=((Xd=X.allowedTypes)!=null?Xd:Nr).join(","),ne.multiple=((Qd=X.maxFiles)!=null?Qd:4)>1,ne.style.display="none",ne.setAttribute("aria-label","Attach files"),Ot.insertBefore(ne,de)),Dt=h("div","persona-send-button-wrapper"),Ye=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ye.type="button",Ye.setAttribute("aria-label",(Yd=X.buttonTooltipText)!=null?Yd:"Attach file");let ct=(Zd=X.buttonIconName)!=null?Zd:"paperclip",Tt=Nt,on=parseFloat(Tt)||40,mn=Math.round(on*.6);Ye.style.width=Tt,Ye.style.height=Tt,Ye.style.minWidth=Tt,Ye.style.minHeight=Tt,Ye.style.fontSize="18px",Ye.style.lineHeight="1",Ye.style.backgroundColor="transparent",Ye.style.color="var(--persona-primary, #111827)",Ye.style.border="none",Ye.style.borderRadius="6px",Ye.style.transition="background-color 0.15s ease",Ye.addEventListener("mouseenter",()=>{Ye.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ye.addEventListener("mouseleave",()=>{Ye.style.backgroundColor="transparent"});let fr=be(ct,mn,"currentColor",1.5);fr?Ye.appendChild(fr):Ye.textContent="\u{1F4CE}",Ye.addEventListener("click",Jn=>{Jn.preventDefault(),ne==null||ne.click()}),Dt.appendChild(Ye);let Tn=(ep=X.buttonTooltipText)!=null?ep:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=Tn,Dt.appendChild(Yt),rt.append(Dt),!tt&&ne&&me&&(tt=Ko.fromConfig(X),tt.setPreviewsContainer(me),ne.addEventListener("change",async()=>{tt&&(ne!=null&&ne.files)&&(await tt.handleFileSelect(ne.files),ne.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Ju(X.dropOverlay))}else{Dt.style.display="";let X=(tp=r.attachments)!=null?tp:{};ne&&(ne.accept=((np=X.allowedTypes)!=null?np:Nr).join(","),ne.multiple=((rp=X.maxFiles)!=null?rp:4)>1),tt&&tt.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Dt&&(Dt.style.display="none"),tt&&tt.clearAttachments(),(op=ce.querySelector(".persona-attachment-drop-overlay"))==null||op.remove();let Vt=(sp=r.sendButton)!=null?sp:{},vo=(ap=Vt.useIcon)!=null?ap:!1,Zr=(ip=Vt.iconText)!=null?ip:"\u2191",ht=Vt.iconName,Pn=(lp=Vt.tooltipText)!=null?lp:"Send message",Br=(cp=Vt.showTooltip)!=null?cp:!1,Sn=(dp=Vt.size)!=null?dp:"40px",In=Vt.backgroundColor,Ht=Vt.textColor;if(vo){if(ae.style.width=Sn,ae.style.height=Sn,ae.style.minWidth=Sn,ae.style.minHeight=Sn,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Ht?ae.style.color=Ht:ae.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let X=parseFloat(Sn)||24,xt=(Ht==null?void 0:Ht.trim())||"currentColor",Nt=be(ht,X,xt,2);Nt?ae.appendChild(Nt):ae.textContent=Zr}else ae.textContent=Zr;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",In?(ae.style.backgroundColor=In,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=(up=(pp=r.copy)==null?void 0:pp.sendButtonLabel)!=null?up:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",In?(ae.style.backgroundColor=In,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Ht?ae.style.color=Ht:ae.classList.add("persona-text-white");Vt.borderWidth?(ae.style.borderWidth=Vt.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),Vt.borderColor?ae.style.borderColor=Vt.borderColor:ae.style.borderColor="",Vt.paddingX?(ae.style.paddingLeft=Vt.paddingX,ae.style.paddingRight=Vt.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),Vt.paddingY?(ae.style.paddingTop=Vt.paddingY,ae.style.paddingBottom=Vt.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let Ut=Mn==null?void 0:Mn.querySelector(".persona-send-button-tooltip");if(Br&&Pn)if(Ut)Ut.textContent=Pn,Ut.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Pn,Mn==null||Mn.insertBefore(X,ae)}else Ut&&(Ut.style.display="none");let Bt=(yp=(mp=r.layout)==null?void 0:mp.contentMaxWidth)!=null?yp:O()?(hp=(fp=(gp=r.launcher)==null?void 0:gp.composerBar)==null?void 0:fp.contentMaxWidth)!=null?hp:"720px":void 0;Bt?($e.style.maxWidth=Bt,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ot&&(Ot.style.maxWidth=Bt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Et&&(Et.style.maxWidth=Bt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let Kt=(bp=r.statusIndicator)!=null?bp:{},Wn=(xp=Kt.visible)!=null?xp:!0;if(ln.style.display=Wn?"":"none",S){let X=S.getStatus();ue(ln,(Nt=>{var ct,Tt,on,mn;return Nt==="idle"?(ct=Kt.idleText)!=null?ct:gn.idle:Nt==="connecting"?(Tt=Kt.connectingText)!=null?Tt:gn.connecting:Nt==="connected"?(on=Kt.connectedText)!=null?on:gn.connected:Nt==="error"?(mn=Kt.errorText)!=null?mn:gn.error:gn[Nt]})(X),Kt,X)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Kn=Kt.align==="left"?"persona-text-left":Kt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Kn)},open(){$()&&Rt(!0,"api")},close(){$()&&Rt(!1,"api")},toggle(){$()&&Rt(!B,"api")},clearChat(){bn=!1,S.clearMessages(),dr.clear(),zr();try{localStorage.removeItem(rs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rs}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},C.syncFromMetadata(),V==null||V.clear(),le==null||le.reset(),ve==null||ve.update()},setMessage(c){return!de||S.isStreaming()?!1:(!B&&$()&&Rt(!0,"system"),de.value=c,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(S.isStreaming())return!1;let f=(c==null?void 0:c.trim())||de.value.trim();return f?(!B&&$()&&Rt(!0,"system"),de.value="",de.style.height="auto",S.sendMessage(f),!0):!1},startVoiceRecognition(){var f,y;return S.isStreaming()?!1:((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype"?(S.isVoiceActive()||(!B&&$()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,Ln(),S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("user"),S.isVoiceActive()&&_()})),!0):Vn?!0:vs()?(!B&&$()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,Ln(),ho("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?S.isVoiceActive()?(S.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Ln(),nr("user"),K()}),!0):!1:Vn?(mt.manuallyDeactivated=!0,Ln(),gr("user"),!0):!1},injectMessage(c){return!B&&$()&&Rt(!0,"system"),S.injectMessage(c)},injectAssistantMessage(c){!B&&$()&&Rt(!0,"system");let f=S.injectAssistantMessage(c);return j&&(j=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)),f},injectUserMessage(c){return!B&&$()&&Rt(!0,"system"),S.injectUserMessage(c)},injectSystemMessage(c){return!B&&$()&&Rt(!0,"system"),S.injectSystemMessage(c)},injectMessageBatch(c){return!B&&$()&&Rt(!0,"system"),S.injectMessageBatch(c)},injectComponentDirective(c){return!B&&$()&&Rt(!0,"system"),S.injectComponentDirective(c)},injectTestMessage(c){!B&&$()&&Rt(!0,"system"),S.injectTestEvent(c)},async connectStream(c,f){return S.connectStream(c,f)},__pushEventStreamEvent(c){V&&(le==null||le.processEvent(c.type,c.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ge||!V||yn()},hideEventStream(){fe&&Dn()},isEventStreamVisible(){return fe},showArtifacts(){ir(r)&&(bn=!1,jn(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){ir(r)&&(bn=!0,jn())},upsertArtifact(c){return ir(r)?(bn=!1,S.upsertArtifact(c)):null},selectArtifact(c){ir(r)&&S.selectArtifact(c)},clearArtifacts(){ir(r)&&S.clearArtifacts()},getArtifacts(){var c;return(c=S==null?void 0:S.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=S==null?void 0:S.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!B&&!O()||!de?!1:(de.focus(),!0)},async resolveApproval(c,f){let b=S.getMessages().find(M=>{var D;return M.variant==="approval"&&((D=M.approval)==null?void 0:D.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){S.resolveWebMcpApproval(b.id,f);return}return S.resolveApproval(b.approval,f)},getMessages(){return S.getMessages()},getStatus(){return S.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,f){return o.on(c,f)},off(c,f){o.off(c,f)},isOpen(){return $()&&B},isVoiceActive(){return mt.active},getState(){return{open:$()&&B,launcherEnabled:T,voiceActive:mt.active,streaming:S.isStreaming()}},showCSATFeedback(c){!B&&$()&&Rt(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let y=dl({onSubmit:async(b,M)=>{var D;S.isClientTokenMode()&&await S.submitCSATFeedback(b,M),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!B&&$()&&Rt(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let y=pl({onSubmit:async(b,M)=>{var D;S.isClientTokenMode()&&await S.submitNPSFeedback(b,M),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return S.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return S.submitNPSFeedback(c,f)},destroy(){Cr!=null&&(clearInterval(Cr),Cr=null),gt.forEach(c=>c()),ie.remove(),Qe==null||Qe.remove(),Ee==null||Ee.destroy(),Je==null||Je.remove(),qn&&Ue.removeEventListener("click",qn)}};if((((bc=n==null?void 0:n.debugTools)!=null?bc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:y=>y?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=f,gt.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",f),gt.push(()=>{window.removeEventListener("persona:focusInput",f)}),ge){let U=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.showEventStream()},R=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",R),gt.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",R)})}let y=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&en.showArtifacts()},b=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&en.hideArtifacts()},M=U=>{let R=U.detail;R!=null&&R.instanceId&&R.instanceId!==c||R!=null&&R.artifact&&en.upsertArtifact(R.artifact)},D=U=>{let R=U.detail;R!=null&&R.instanceId&&R.instanceId!==c||typeof(R==null?void 0:R.id)=="string"&&en.selectArtifact(R.id)},F=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",F),gt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",F)})}let or=Mb(r.persistState);if(or&&$()){let c=kb(or.storage),f=`${or.keyPrefix}widget-open`,y=`${or.keyPrefix}widget-voice`,b=`${or.keyPrefix}widget-voice-mode`;if(c){let M=((xc=or.persist)==null?void 0:xc.openState)&&c.getItem(f)==="true",D=((vc=or.persist)==null?void 0:vc.voiceState)&&c.getItem(y)==="true",F=((wc=or.persist)==null?void 0:wc.voiceState)&&c.getItem(b)==="true";if(M&&setTimeout(()=>{en.open(),setTimeout(()=>{var U;if(D||F)en.startVoiceRecognition();else if((U=or.persist)!=null&&U.focusInput){let R=e.querySelector("textarea");R&&R.focus()}},100)},0),(Cc=or.persist)!=null&&Cc.openState&&(o.on("widget:opened",()=>{c.setItem(f,"true")}),o.on("widget:closed",()=>{c.setItem(f,"false")})),(Ac=or.persist)!=null&&Ac.voiceState&&(o.on("voice:state",U=>{c.setItem(y,U.active?"true":"false")}),o.on("user:message",U=>{c.setItem(b,U.viaVoice?"true":"false")})),or.clearOnChatClear){let U=()=>{c.removeItem(f),c.removeItem(y),c.removeItem(b)},R=()=>U();window.addEventListener("persona:clear-chat",R),gt.push(()=>{window.removeEventListener("persona:clear-chat",R)})}}}return p&&$()&&setTimeout(()=>{en.open()},0),Rr(),en};var Lb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Gu=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!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"},yl=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=""},Xu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",yl(e)},gl=e=>{e.style.transition=""},fl=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=""},hl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},mi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Pb=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Ib=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Qu=(e,t,n,r,s,o,a)=>{var v,x,C,T,H,L;let i=yr(o),d=i.reveal==="push";Pb(e,t,n,r,d),Ib(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.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",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,m=(T=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileBreakpoint)!=null?T:640,g=l!=null?l.innerWidth<=m:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),fl(t),gl(r),Xu(r),hl(n),mi(s,r),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",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((L=(H=o==null?void 0:o.launcher)==null?void 0:H.zIndex)!=null?L:fn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.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.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"),Xu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",fl(t),gl(r),hl(n),mi(s,r);let P=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":W;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=P,r.style.transform=w,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",gl(r),yl(r),mi(s,r);let P=Lb(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",I=i.side==="right"?a?`translateX(-${P}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${P}px)`;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=`${W+P}px`,t.style.transition=w,t.style.transform=I,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",fl(t),yl(r),hl(n),mi(s,r);let P=i.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${W}`,r.style.width=W,r.style.maxWidth=W,r.style.minWidth=W,r.style.minHeight="0",r.style.position="relative",r.style.overflow=P||I?"hidden":"visible",r.style.transition=w,P&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Wb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Gu(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Gu(n,r)},destroy(){n.remove()}}},Rb=(e,t)=>{var H,L,P,W;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),m=(L=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)==null||L?(W=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),yr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Qu(a,i,d,l,p,t,m)}),g.observe(a))},x=()=>{Qu(a,i,d,l,p,t,m),v()},C=a.ownerDocument.defaultView,T=()=>{x()};return C==null||C.addEventListener("resize",T),yr(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:p,shell:a,syncWidgetState(w){let I=w.launcherEnabled?w.open:!0;m!==I&&(m=I,x())},updateConfig(w){var I,O;t=w,((O=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)!=null?O:!0)===!1&&(m=!0),x()},destroy(){C==null||C.removeEventListener("resize",T),u(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},gi=(e,t)=>an(t)?Rb(e,t):Wb(e,t);var bl={},Yu=!1,Hb=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Bb=()=>{try{if(typeof bl!="undefined"&&bl.url)return new URL("../widget.css",bl.url).href}catch{}return null},Zu=(e,t)=>{let n=Bb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},em=e=>{let t=Hb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=gi(t,s),a,i=[],d=(C,T)=>{var W,w;let L=!((w=(W=T==null?void 0:T.launcher)==null?void 0:W.enabled)!=null?w:!0)||an(T),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),L&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let I=C.attachShadow({mode:"open"});I.appendChild(P),Zu(I,r)}else C.appendChild(P),Zu(C,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let C=d(o.host,s);a=ml(C,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(C=>C()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(Yu||(Yu=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let u=C=>{g(),o.destroy(),o=gi(t,C),s=C,m()},v={update(C){var w,I,O,$,B,j;let T={...s,...C,launcher:{...(w=s==null?void 0:s.launcher)!=null?w:{},...(I=C==null?void 0:C.launcher)!=null?I:{},dock:{...($=(O=s==null?void 0:s.launcher)==null?void 0:O.dock)!=null?$:{},...(j=(B=C==null?void 0:C.launcher)==null?void 0:B.dock)!=null?j:{}}}},H=an(s),L=an(T),P=no(s),W=no(T);if(H!==L||P!==W){u(T);return}s=T,o.updateConfig(s),a.update(C),l()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(C,T,H){if(T==="host")return o.host;if(T in C)return Reflect.get(C,T,H);let L=a[T];return typeof L=="function"?L.bind(a):L}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var sm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Db=new Set(["button","a","input","select","textarea","details","summary"]),Nb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),xl=/\b(product|card|item|listing|result)\b/i,wl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Fb=3e3,Ob=100;function am(e){let t=typeof e.className=="string"?e.className:"";if(xl.test(t)||e.id&&xl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&xl.test(r.value))return!0}return!1}function im(e){var t;return wl.test(((t=e.textContent)!=null?t:"").trim())}function lm(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function $b(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function tm(e){let t=e.match(wl);return t?t[0]:null}function nm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function _b(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var jb="commerce-card",Ub="result-card";function rm(e){return!am(e)||!im(e)||!lm(e)&&!$b(e)?0:5200}function om(e){var r;return!am(e)||im(e)||!lm(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var cm=[{id:jb,scoreElement(e){return rm(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||wl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(rm(e)===0)return null;let{title:n,href:r}=nm(e),s=(p=(l=tm(((d=e.textContent)!=null?d:"").trim()))!=null?l:tm(t.text))!=null?p:"",o=_b(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
- `)}},{id:Ub,scoreElement(e){return om(e)},formatSummary(e,t){if(om(e)===0)return null;let{title:n,href:r}=nm(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
- `)}}];function qb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function zb(e){var p,m,g,u,v,x,C,T,H,L,P,W,w;let t=(p=e.options)!=null?p:{},n=(g=(m=t.maxElements)!=null?m:e.maxElements)!=null?g:80,r=(v=(u=t.excludeSelector)!=null?u:e.excludeSelector)!=null?v:".persona-host",s=(C=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?C:200,o=(H=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?H:!0,a=(L=t.root)!=null?L:e.root,i=(P=t.mode)!=null?P:"structured",d=(W=t.maxCandidates)!=null?W:Math.max(500,n*10),l=(w=e.rules)!=null?w:cm;return i==="simple"&&e.rules&&e.rules.length>0?(qb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function vl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Vb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Kb(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Db.has(t)||n&&Nb.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function dm(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Jb(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function pm(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${vl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Vb){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${vl(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>vl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function Gb(e){return e==="static"?Ob:Fb}function um(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:pm(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Kb(e),attributes:Jb(e)}}function Xb(e,t,n,r){let s=Gb(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Qb(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function Yb(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(sm.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!dm(l)){i=a.nextNode();continue}let m=um(l,e.maxTextLength),g=m.text.length>0,u=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(C=>C==="role");if(!g&&!u){i=a.nextNode();continue}if(r.has(m.selector)){i=a.nextNode();continue}r.add(m.selector);let{score:v,formattingRule:x}=Xb(l,m,e.rules,n);s.push({el:l,domIndex:o,enriched:m,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;Qb(d,l)||d.push(l)}return d.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:m===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var g;let p;if((g=l.formattingRule)!=null&&g.formatSummary){let u=l.formattingRule.formatSummary(l.el,l.enriched,n);u&&(p=u)}let m={...l.enriched};return p&&(m.formattedSummary=p),m})}function Zb(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(sm.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!dm(d)){o=s.nextNode();continue}let p=um(d,e.maxTextLength),m=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(u=>u==="role");if(!m&&!g){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function ex(e={}){var r;let t=zb(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Zb(t,n):Yb(t,n):[]}var fi=100;function tx(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
107
+ `}if(!y&&!c){let gt="max-height: -moz-available !important; max-height: stretch !important;",it=g?"":"padding-top: 1.25em !important;",Et=g?"":`z-index: ${(cn=(gn=r.launcher)==null?void 0:gn.zIndex)!=null?cn:vn} !important;`;ue.style.cssText+=gt+it+Et}Qe()};gr(),Io(e,r),di(e,r),pi(e,r);let yt=[];yt.push(()=>{document.removeEventListener("keydown",qr)});let Xt=null,Qt=null;yt.push(()=>{Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null}),On&&yt.push(()=>{On==null||On.disconnect(),On=null}),yt.push(()=>{Sn==null||Sn(),Sn=null,Rr(),Bt&&(Bt.remove(),Bt=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),Re&&yt.push(()=>{Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),ie==null||ie.destroy(),ie=null,z==null||z.destroy(),z=null,K=null});let Un=null,Kr=()=>{Un&&(Un(),Un=null),r.colorScheme==="auto"&&(Un=$i(()=>{Io(e,r)}))};Kr(),yt.push(()=>{Un&&(Un(),Un=null)});let rr=(bc=r.features)==null?void 0:bc.streamAnimation;if(rr!=null&&rr.type&&rr.type!=="none"){let c=Vs(rr.type,rr.plugins);c&&(Ui(c,e),yt.push(()=>cu(e)))}let fr=$u(Rt),qn=null,$,or=!1,be=ru(),zn=new Map,sr=new Map,hr=new Map,ps=0,br=_a(),yr=0,xr=null,Hr=!1,ho=!1,aa=4,us=24,ia=80,No=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ms=(xc=(yc=r.voiceRecognition)==null?void 0:yc.autoResume)!=null?xc:!1,ar=c=>{o.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},In=()=>{m(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},la=()=>{var y,T;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=bl(d.voiceState),g=!!c.active,b=Number((T=c.timestamp)!=null?T:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<Dy&&setTimeout(()=>{var D,N;bt.active||(bt.manuallyDeactivated=!1,((N=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:N.type)==="runtype"?$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),ar("restore"),$.isVoiceActive()&&E()}):vo("restore"))},1e3)},ca=()=>$?rm($.getMessages()).filter(c=>!c.__skipPersist):[];function Oo(c){if(!(i!=null&&i.save))return;let b={messages:c?rm(c):$?ca():[],metadata:d,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let y=i.save(b);y instanceof Promise&&y.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Br=null,da=()=>ue.querySelector("#persona-scroll-container")||G,bo=()=>{Br!==null&&(cancelAnimationFrame(Br),Br=null),Hr=!1},gs=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null),ho=!1,bo()},Dr=()=>{if(!wn()||se){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==ge&&ge.appendChild(It),Ct();let c=js(G)>0;It.style.display=br.isFollowing()||!c?"none":""},fs=()=>{br.pause()&&(gs(),Dr())},Jr=()=>{br.resume(),Dr()},Gr=(c=!1)=>{br.isFollowing()&&(!c&&!or||(xr!==null&&(cancelAnimationFrame(xr),xr=null),ho=!0,xr=requestAnimationFrame(()=>{xr=null,ho=!1,br.isFollowing()&&pa(da(),c?220:140)})))},pa=(c,g=500)=>{let b=c.scrollTop,y=js(c),T=y-b;if(Math.abs(T)<1){yr=c.scrollTop;return}if(Math.abs(T)>=ia){bo(),Hr=!0,c.scrollTop=y,yr=c.scrollTop,Hr=!1;return}bo();let D=performance.now();Hr=!0;let N=R=>1-Math.pow(1-R,3),j=R=>{if(!br.isFollowing()){bo();return}let Se=js(c);Se!==y&&(y=Se,T=y-b);let me=R-D,Z=Math.min(me/g,1),we=N(Z),Ee=b+T*we;c.scrollTop=Ee,yr=c.scrollTop,Z<1?Br=requestAnimationFrame(j):(c.scrollTop=y,yr=c.scrollTop,Br=null,Hr=!1)};Br=requestAnimationFrame(j)},ua=c=>{let g=new Map;c.forEach(b=>{let y=No.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!y&&b.role==="assistant"&&o.emit("assistant:message",b),b.role==="assistant"&&(y!=null&&y.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(y?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),No.clear(),g.forEach((b,y)=>{No.set(y,b)})},yo=(c,g,b)=>{var dt,Pe,ke,Ue,Qe,xt;let y=document.createElement("div"),D=(()=>{var Ne;let k=s.find(ee=>ee.renderLoadingIndicator);if(k!=null&&k.renderLoadingIndicator)return k.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),N=(k,Ne)=>Ne==null?!1:typeof Ne=="string"?(k.textContent=Ne,!0):(k.appendChild(Ne),!0),j=new Set,R=new Set,Se=s.some(k=>k.renderAskUserQuestion),me=[],Z=[],we=r.enableComponentStreaming!==!1,Ee=s.some(k=>k.renderApproval)&&r.approval!==!1,_e=[];if(g.forEach(k=>{var wt,Jn,on,cr,Gn,wo,zo,Vo,Gt,Co,to,no,Fr,Ao;j.add(k.id);let Ne=Se&&lo(k),ee=Ee&&k.variant==="approval"&&!!k.approval,tt=!Ne&&k.role==="assistant"&&!k.variant&&we&&ml(k);if(!ee&&hr.has(k.id)){let nt=c.querySelector(`#wrapper-${k.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),hr.delete(k.id)}if(!tt&&sr.has(k.id)){let nt=c.querySelector(`#wrapper-${k.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),sr.delete(k.id)}let Ot=lo(k)?`:${(wt=k.agentMetadata)!=null&&wt.askUserQuestionAnswered?"a":"u"}:${(Jn=k.agentMetadata)!=null&&Jn.askUserQuestionAnswers?Object.keys(k.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt=nu(k,ps)+Ot,qt=Ne||ee||tt?null:ou(be,k.id,Nt);if(qt){y.appendChild(qt.cloneNode(!0)),lo(k)&&((on=k.toolCall)!=null&&on.id)&&((cr=k.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Gn=k.agentMetadata)!=null&&Gn.askUserQuestionAnswered)&&(R.add(k.toolCall.id),ta(k,r,Ie.composerOverlay));return}let at=null,ln=s.find(nt=>!!(k.variant==="reasoning"&&nt.renderReasoning||k.variant==="tool"&&nt.renderToolCall||!k.variant&&nt.renderMessage)),Kn=(wo=r.layout)==null?void 0:wo.messages;if(lo(k)&&((zo=k.agentMetadata)==null?void 0:zo.askUserQuestionAnswered)===!0){zn.delete(k.id);let nt=c.querySelector(`#wrapper-${k.id}`);nt==null||nt.removeAttribute("data-preserve-runtime");return}if(lo(k)&&((Gt=(Vo=r.features)==null?void 0:Vo.askUserQuestion)==null?void 0:Gt.enabled)!==!1){let nt=s.find(bn=>typeof bn.renderAskUserQuestion=="function");if(nt&&kt.current){let bn=zn.get(k.id),gn=bn!==Nt,cn=null;if(gn){let{payload:Et,complete:Wn}=co(k),en=k.id,kr=()=>{var sn;return(sn=kt.current)==null?void 0:sn.getMessages().find(En=>En.id===en)};cn=nt.renderAskUserQuestion({message:k,payload:Et,complete:Wn,resolve:sn=>{var dr;let En=kr();En&&((dr=kt.current)==null||dr.resolveAskUserQuestion(En,sn))},dismiss:()=>{var En,dr,So;let sn=kr();(En=sn==null?void 0:sn.agentMetadata)!=null&&En.awaitingLocalTool&&((dr=kt.current)==null||dr.markAskUserQuestionResolved(sn),(So=kt.current)==null||So.resolveAskUserQuestion(sn,"(dismissed)"))},config:r})}let gt=bn!=null;if(gn&&cn===null&&!gt){((Co=k.agentMetadata)==null?void 0:Co.awaitingLocalTool)===!0&&!((to=k.agentMetadata)!=null&&to.askUserQuestionAnswered)&&(R.add(k.toolCall.id),ta(k,r,Ie.composerOverlay));return}let it=document.createElement("div");it.className="persona-flex",it.id=`wrapper-${k.id}`,it.setAttribute("data-wrapper-id",k.id),it.setAttribute("data-ask-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),y.appendChild(it),me.push({messageId:k.id,fingerprint:Nt,bubble:cn});return}else{((no=k.agentMetadata)==null?void 0:no.awaitingLocalTool)===!0&&!((Fr=k.agentMetadata)!=null&&Fr.askUserQuestionAnswered)&&(R.add(k.toolCall.id),ta(k,r,Ie.composerOverlay));return}}else if(ee){let nt=s.find(gt=>typeof gt.renderApproval=="function"),gn=hr.get(k.id)!==Nt,cn=null;if(gn&&(nt!=null&&nt.renderApproval)){let gt=k.id,it=(Et,Wn)=>{var kr,sn,En;let en=(kr=kt.current)==null?void 0:kr.getMessages().find(dr=>dr.id===gt);en!=null&&en.approval&&(en.approval.toolType==="webmcp"?(sn=kt.current)==null||sn.resolveWebMcpApproval(en.id,Et):(En=kt.current)==null||En.resolveApproval(en.approval,Et,Wn))};cn=nt.renderApproval({message:k,defaultRenderer:()=>li(k,r),config:r,approve:Et=>it("approved",Et),deny:Et=>it("denied",Et)})}if(gn&&cn===null){let gt=c.querySelector(`#wrapper-${k.id}`);gt==null||gt.removeAttribute("data-preserve-runtime"),hr.delete(k.id),at=li(k,r)}else{let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${k.id}`,gt.setAttribute("data-wrapper-id",k.id),gt.setAttribute("data-approval-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),y.appendChild(gt),_e.push({messageId:k.id,fingerprint:Nt,bubble:cn});return}}else if(ln)if(k.variant==="reasoning"&&k.reasoning&&ln.renderReasoning){if(!Je)return;at=ln.renderReasoning({message:k,defaultRenderer:()=>Xi(k,r),config:r})}else if(k.variant==="tool"&&k.toolCall&&ln.renderToolCall){if(!ve)return;at=ln.renderToolCall({message:k,defaultRenderer:()=>Qi(k,r),config:r})}else ln.renderMessage&&(at=ln.renderMessage({message:k,defaultRenderer:()=>{let nt=Zs(k,b,Kn,r.messageActions,Q,{loadingIndicatorRenderer:D,widgetConfig:r});return k.role!=="user"&&il(nt,k,r,$),nt},config:r}));if(!at&&tt){let nt=gl(k);if(nt){let bn=sr.get(k.id),gn=bn!==Nt,cn=r.wrapComponentDirectiveInBubble!==!1,gt=null;if(gn){let it=ul(nt,{config:r,message:k,transform:b});if(it)if(cn){let Et=document.createElement("div");if(Et.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Et.id=`bubble-${k.id}`,Et.setAttribute("data-message-id",k.id),k.content&&k.content.trim()){let Wn=document.createElement("div");Wn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Wn.innerHTML=b({text:k.content,message:k,streaming:!!k.streaming,raw:k.rawContent}),Et.appendChild(Wn)}Et.appendChild(it),gt=Et}else{let Et=document.createElement("div");if(Et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Et.id=`bubble-${k.id}`,Et.setAttribute("data-message-id",k.id),Et.setAttribute("data-persona-component-directive","true"),k.content&&k.content.trim()){let Wn=document.createElement("div");Wn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Wn.innerHTML=b({text:k.content,message:k,streaming:!!k.streaming,raw:k.rawContent}),Et.appendChild(Wn)}Et.appendChild(it),gt=Et}}if(gt||bn!=null){let it=document.createElement("div");it.className="persona-flex",it.id=`wrapper-${k.id}`,it.setAttribute("data-wrapper-id",k.id),it.setAttribute("data-component-directive-stub","true"),it.setAttribute("data-preserve-runtime","true"),cn||it.classList.add("persona-w-full"),y.appendChild(it),Z.push({messageId:k.id,fingerprint:Nt,bubble:gt});return}}}if(!at)if(k.variant==="reasoning"&&k.reasoning){if(!Je)return;at=Xi(k,r)}else if(k.variant==="tool"&&k.toolCall){if(!ve)return;at=Qi(k,r)}else if(k.variant==="approval"&&k.approval){if(r.approval===!1)return;at=li(k,r)}else{let nt=(Ao=r.layout)==null?void 0:Ao.messages;nt!=null&&nt.renderUserMessage&&k.role==="user"?at=nt.renderUserMessage({message:k,config:r,streaming:!!k.streaming}):nt!=null&&nt.renderAssistantMessage&&k.role==="assistant"?at=nt.renderAssistantMessage({message:k,config:r,streaming:!!k.streaming}):at=Zs(k,b,nt,r.messageActions,Q,{loadingIndicatorRenderer:D,widgetConfig:r}),k.role!=="user"&&at&&il(at,k,r,$)}let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${k.id}`,Ve.setAttribute("data-wrapper-id",k.id),k.role==="user"&&Ve.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Ve.classList.add("persona-w-full"),Ve.appendChild(at),su(be,k.id,Nt,Ve),y.appendChild(Ve)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let ee=Ne.getAttribute("data-persona-ask-sheet-for");ee&&!R.has(ee)&&Ho(Ie.composerOverlay,ee)}),(Pe=(dt=r.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let k=[],Ne=[];g.forEach(ee=>{if(ee.variant==="tool"&&ee.toolCall&&ve){Ne.push(ee);return}Ne.length>1&&k.push(Ne),Ne=[]}),Ne.length>1&&k.push(Ne),k.forEach((ee,tt)=>{var wt,Jn;let Ot=ee.map(on=>Array.from(y.children).find(cr=>cr instanceof HTMLElement&&cr.getAttribute("data-wrapper-id")===on.id)).filter(on=>!!on);if(Ot.length<2)return;let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id=`wrapper-tool-group-${tt}-${ee[0].id}`,Nt.setAttribute("data-wrapper-id",`tool-group-${tt}-${ee[0].id}`);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 at=document.createElement("div");at.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let ln=`Called ${ee.length} tools`,Kn=(Jn=(wt=r.toolCall)==null?void 0:wt.renderGroupedSummary)==null?void 0:Jn.call(wt,{messages:ee,toolCalls:ee.map(on=>on.toolCall).filter(on=>!!on),defaultSummary:ln,config:r});N(at,Kn)||(at.textContent=ln);let Ve=document.createElement("div");Ve.className="persona-tool-group-stack persona-flex persona-flex-col",qt.append(at,Ve),Nt.appendChild(qt),Ot[0].before(Nt),Ot.forEach((on,cr)=>{let Gn=document.createElement("div");Gn.className="persona-tool-group-item persona-relative",Gn.setAttribute("data-persona-tool-group-item","true"),cr<Ot.length-1&&Gn.setAttribute("data-persona-tool-group-connector","true"),Gn.appendChild(on),Ve.appendChild(Gn)})})}au(be,j);let ot=g.some(k=>k.role==="assistant"&&k.streaming),ze=g[g.length-1],mt=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(or&&g.some(k=>k.role==="user")&&!ot&&!mt){let k={config:r,streaming:!0,location:"standalone",defaultRenderer:ns},Ne=s.find(tt=>tt.renderLoadingIndicator),ee=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(ee=Ne.renderLoadingIndicator(k)),ee===null&&((ke=r.loadingIndicator)!=null&&ke.render)&&(ee=r.loadingIndicator.render(k)),ee===null&&(ee=ns()),ee){let tt=document.createElement("div"),Ot=((Ue=r.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;tt.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),tt.setAttribute("data-typing-indicator","true"),tt.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",tt.appendChild(ee);let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id="wrapper-typing-indicator",Nt.setAttribute("data-wrapper-id","typing-indicator"),Nt.appendChild(tt),y.appendChild(Nt)}}if(!or&&g.length>0){let k=g[g.length-1],Ne={config:r,lastMessage:k,messageCount:g.length},ee=s.find(Ot=>Ot.renderIdleIndicator),tt=null;if(ee!=null&&ee.renderIdleIndicator&&(tt=ee.renderIdleIndicator(Ne)),tt===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(tt=r.loadingIndicator.renderIdle(Ne)),tt){let Ot=document.createElement("div"),Nt=((xt=r.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Ot.className=Nt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ot.setAttribute("data-idle-indicator","true"),Ot.appendChild(tt);let qt=document.createElement("div");qt.className="persona-flex",qt.id="wrapper-idle-indicator",qt.setAttribute("data-wrapper-id","idle-indicator"),qt.appendChild(Ot),y.appendChild(qt)}}if(Fa(c,y),me.length>0)for(let{messageId:k,fingerprint:Ne,bubble:ee}of me){let tt=c.querySelector(`#wrapper-${k}`);tt&&ee!==null&&(tt.replaceChildren(ee),tt.setAttribute("data-bubble-fp",Ne),zn.set(k,Ne))}if(zn.size>0)for(let k of zn.keys())j.has(k)||zn.delete(k);if(Z.length>0)for(let{messageId:k,fingerprint:Ne,bubble:ee}of Z){let tt=c.querySelector(`#wrapper-${k}`);tt&&ee!==null&&(tt.replaceChildren(ee),tt.setAttribute("data-bubble-fp",Ne),sr.set(k,Ne))}if(sr.size>0)for(let k of sr.keys())j.has(k)||sr.delete(k);if(_e.length>0)for(let{messageId:k,fingerprint:Ne,bubble:ee}of _e){let tt=c.querySelector(`#wrapper-${k}`);tt&&ee!==null&&(tt.replaceChildren(ee),tt.setAttribute("data-bubble-fp",Ne),hr.set(k,Ne))}if(hr.size>0)for(let k of hr.keys())j.has(k)||hr.delete(k)},Xr=null,ma=()=>{var b;if(Xr)return;let c=y=>{let T=y.composedPath();T.includes(ue)||Ye&&T.includes(Ye)||Dt(!1,"user")};Xr=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},hs=()=>{var g;if(!Xr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Xr,!0),Xr=null};yt.push(()=>hs());let Qr=null,ga=()=>{var b;if(Qr)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Dt(!1,"user"))};Qr=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},bs=()=>{var g;if(!Qr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",Qr,!0),Qr=null};yt.push(()=>bs());let Yr=!1,ys=new Set,fa=()=>{var g,b,y,T;let c=(y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:y.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},Nr=()=>{var mt,dt,Pe,ke;if(!F())return;let c=Ie.peekBanner,g=Ie.peekTextNode;if(!c||!g)return;if(W){c.classList.remove("persona-pill-peek--visible");return}let b=(mt=$==null?void 0:$.getMessages())!=null?mt:[],y;for(let Ue=b.length-1;Ue>=0;Ue--){let Qe=b[Ue];if(Qe.role==="assistant"&&Qe.content){y=Qe;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let T=y.content,D=!!y.streaming,N=fa(),j=qa(N),R=j.type!=="none"?Vs(j.type,N==null?void 0:N.plugins):null,Se=((dt=R==null?void 0:R.isAnimating)==null?void 0:dt.call(R,y))===!0,me=R!==null&&(D||Se);me&&R&&!ys.has(R.name)&&(Ui(R,e),ys.add(R.name));let Z=me&&(R!=null&&R.containerClass)?R.containerClass:null,we=(Pe=g.dataset.personaPeekStreamClass)!=null?Pe:null;we&&we!==Z&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),Z&&we!==Z&&(g.classList.add(Z),g.dataset.personaPeekStreamClass=Z),me?(g.style.setProperty("--persona-stream-step",`${j.speed}ms`),g.style.setProperty("--persona-stream-duration",`${j.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ee=me?za(T,j.buffer,R,y,D):T;if(me&&j.placeholder==="skeleton"&&D&&(!Ee||!Ee.trim())){let Ue=document.createElement("div"),Qe=Js();Qe.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(Qe),Fa(g,Ue)}else{let Ue=Math.max(0,Ee.length-100),Qe=Ee.length>100?Ee.slice(-100):Ee,xt=Jo(Qe);if(!me||!R){let k=Ee.length>100?`\u2026${Qe}`:Qe;g.textContent!==k&&(g.textContent=k)}else{let k=xt;(R.wrap==="char"||R.wrap==="word")&&(k=Ks(xt,R.wrap,`peek-${y.id}`,{skipTags:R.skipTags,startIndex:Ue}));let Ne=document.createElement("div");if(Ne.innerHTML=k,R.useCaret&&Qe.length>0){let ee=Va(),tt=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ot=tt[tt.length-1];Ot!=null&&Ot.parentNode?Ot.parentNode.insertBefore(ee,Ot.nextSibling):Ne.appendChild(ee)}Fa(g,Ne),(ke=R.onAfterRender)==null||ke.call(R,{container:g,bubble:c,messageId:y.id,message:y,speed:j.speed,duration:j.duration})}}let ze=or||Yr;c.classList.toggle("persona-pill-peek--visible",ze)};if(F()){let c=Ie.peekBanner;if(c){let y=T=>{T.preventDefault(),T.stopPropagation(),Dt(!0,"user")};c.addEventListener("pointerdown",y),yt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{Yr||(Yr=!0,Nr())},b=()=>{Yr&&(Yr=!1,Nr())};re.addEventListener("pointerenter",g),re.addEventListener("pointerleave",b),yt.push(()=>{re.removeEventListener("pointerenter",g),re.removeEventListener("pointerleave",b)}),Ye&&(Ye.addEventListener("pointerenter",g),Ye.addEventListener("pointerleave",b),yt.push(()=>{Ye.removeEventListener("pointerenter",g),Ye.removeEventListener("pointerleave",b)}))}let ha=c=>{var we,Ee,_e,ot,ze,mt,dt,Pe;let g=(Ee=(we=r.launcher)==null?void 0:we.composerBar)!=null?Ee:{},b=(_e=g.expandedSize)!=null?_e:"anchored",y=(ot=g.bottomOffset)!=null?ot:"16px",T=g.collapsedMaxWidth,D=(ze=g.expandedMaxWidth)!=null?ze:"880px",N=(mt=g.expandedTopOffset)!=null?mt:"5vh",j=(dt=g.modalMaxWidth)!=null?dt:"880px",R=(Pe=g.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Se="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",Z=ue.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Ye){let ke=Ye.style;ke.bottom=y,ke.width=T!=null?T:""}if(c&&b!=="fullscreen"){if(b==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=j,Z.maxWidth=Se,Z.maxHeight=R,Z.height=R;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${me})`,Z.top=N,Z.width=D,Z.maxWidth=Se}},Zr=()=>{var R,Se,me,Z,we,Ee,_e,ot;if(!B())return;if(F()){let mt=(me=((Se=(R=r.launcher)==null?void 0:R.composerBar)!=null?Se:{}).expandedSize)!=null?me:"anchored",dt=W?"expanded":"collapsed";ue.dataset.state=dt,ue.dataset.expandedSize=mt,Ye&&(Ye.dataset.state=dt,Ye.dataset.expandedSize=mt),ue.style.removeProperty("display"),ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ha(W),ge.style.display=W?"flex":"none",gr(),W?(ma(),ga()):(hs(),bs()),Nr();return}let c=un(r),g=(Z=e.ownerDocument.defaultView)!=null?Z:window,b=(Ee=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Ee:640,y=(ot=(_e=r.launcher)==null?void 0:_e.mobileFullscreen)!=null?ot:!0,T=g.innerWidth<=b,D=y&&T&&S,N=Ar(r).reveal;W?(ue.style.removeProperty("display"),ue.style.display=c?"flex":"",ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-95","persona-opacity-0"),re.classList.add("persona-scale-100","persona-opacity-100"),Xe?Xe.element.style.display="none":et&&(et.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!D?(ue.style.removeProperty("display"),ue.style.display="flex",ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ue.style.setProperty("display","none","important"),ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ue.style.display="",ue.classList.add("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100"),re.classList.add("persona-scale-95","persona-opacity-0")),Xe?Xe.element.style.display=c?"none":"":et&&(et.style.display=c?"none":""))},Dt=(c,g="user")=>{var D,N;if(!B()||W===c)return;let b=W;W=c,Zr();let y=(()=>{var _e,ot,ze,mt,dt,Pe,ke,Ue,Qe,xt;let j=(ot=(_e=r.launcher)==null?void 0:_e.sidebarMode)!=null?ot:!1,R=(ze=e.ownerDocument.defaultView)!=null?ze:window,Se=(dt=(mt=r.launcher)==null?void 0:mt.mobileFullscreen)!=null?dt:!0,me=(ke=(Pe=r.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?ke:640,Z=R.innerWidth<=me,we=un(r)&&Se&&Z,Ee=F()&&((xt=(Qe=(Ue=r.launcher)==null?void 0:Ue.composerBar)==null?void 0:Qe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return j||Se&&Z&&S||we||Ee})();if(W&&y){if(!Xt){let j=e.getRootNode(),R=j instanceof ShadowRoot?j.host:e.closest(".persona-host");R&&(Xt=qi(R,(N=(D=r.launcher)==null?void 0:D.zIndex)!=null?N:vn))}Qt||(Qt=zi(e.ownerDocument))}else W||(Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null);W&&(Yt(),Gr(!0));let T={open:W,source:g,timestamp:Date.now()};W&&!b?o.emit("widget:opened",T):!W&&b&&o.emit("widget:closed",T),o.emit("widget:state",{open:W,launcherEnabled:S,voiceActive:bt.active,streaming:$.isStreaming()})},Fo=c=>{zt(c?"stop":"send"),q&&(q.disabled=c),fr.buttons.forEach(g=>{g.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},$o=()=>{bt.active||fe&&fe.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>$o(),200)});let xs=()=>{var b,y,T,D,N,j,R,Se,me,Z,we;Hn.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"Hello \u{1F44B}",Yn.textContent=(D=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",fe.placeholder=(j=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?j:"How can I help...";let c=G.querySelector("[data-persona-intro-card]");if(c){let Ee=((R=r.copy)==null?void 0:R.showWelcomeCard)!==!1;c.style.display=Ee?"":"none",Ee?(G.classList.remove("persona-gap-3"),G.classList.add("persona-gap-6")):(G.classList.remove("persona-gap-6"),G.classList.add("persona-gap-3"))}!((me=(Se=r.sendButton)==null?void 0:Se.useIcon)!=null&&me)&&!($!=null&&$.isStreaming())&&(de.textContent=(we=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?we:"Send"),fe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',fe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let Mr=null,ba=()=>{Mr==null&&(Mr=setInterval(()=>{let c=Fe.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Mr),Mr=null;return}let g=Date.now();c.forEach(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=Ea(g-y))})},100))};if($=new Os(r,{onMessagesChanged(c){yo(Fe,c,We),ba(),$&&(c.some(T=>T.role==="user")?fr.render([],$,fe,c):fr.render(r.suggestionChips,$,fe,c,r.suggestionChipsConfig)),Gr(!or),ua(c);let g=[...c].reverse().find(y=>y.role==="user"),b=bt.lastUserMessageId;g&&g.id!==b&&(bt.lastUserMessageId=g.id,o.emit("user:message",g)),bt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Oo(c),Nr()},onStatusChanged(c){var y;let g=(y=r.statusIndicator)!=null?y:{};ye(mn,(T=>{var D,N,j,R;return T==="idle"?(D=g.idleText)!=null?D:xn.idle:T==="connecting"?(N=g.connectingText)!=null?N:xn.connecting:T==="connected"?(j=g.connectedText)!=null?j:xn.connected:T==="error"?(R=g.errorText)!=null?R:xn.error:xn[T]})(c),g,c)},onStreamingChanged(c){or=c,Fo(c),$&&yo(Fe,$.getMessages(),We),c||Gr(!0),Nr()},onVoiceStatusChanged(c){var g,b;if(((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":J(),Y();break;case"speaking":J(),ae();break;default:c==="idle"&&$.isBargeInActive()?(J(),E(),q==null||q.setAttribute("aria-label","End voice session")):(bt.active=!1,J(),ar("system"),In());break}},onArtifactsState(c){Fn=c,jn(),Oo()}}),kt.current=$,((wc=(vc=r.voiceRecognition)==null?void 0:vc.provider)==null?void 0:wc.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&$.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(z||r.onSSEEvent)&&$.setSSEEventCallback((c,g)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,g),ce==null||ce.processEvent(c,g),z==null||z.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,b,y;c&&(c.metadata&&(d=bl(c.metadata),w.syncFromMetadata()),(g=c.messages)!=null&&g.length&&$.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&$.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let vs=()=>{var g,b,y;!F()||W||!((y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||Dt(!0,"auto")},ws=c=>{var T;if(c.preventDefault(),$.isStreaming()){$.cancel(),ce==null||ce.reset(),ie==null||ie.update();return}let g=fe.value.trim(),b=(T=rt==null?void 0:rt.hasAttachments())!=null?T:!1;if(!g&&!b)return;vs();let y;b&&(y=[],y.push(...rt.getContentParts()),g&&y.push(Wa(g))),fe.value="",fe.style.height="auto",xo(),$.sendMessage(g,{contentParts:y}),b&&rt.clearAttachments()},ya=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},_o={...$a},jo=!1,xo=()=>{_o={...$a}},xa=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),va=c=>{if(!fe)return;jo=!0,fe.value=c,fe.dispatchEvent(new Event("input",{bubbles:!0})),jo=!1;let g=fe.value.length;fe.setSelectionRange(g,g)},Cs=()=>{jo||xo()},As=c=>{if(fe){if(ya()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=fe.selectionStart===0&&fe.selectionEnd===0,b=tu({direction:c.key==="ArrowUp"?"up":"down",history:xa(),currentValue:fe.value,atStart:g,state:_o});if(_o=b.state,b.handled){c.preventDefault(),b.value!==void 0&&va(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}xo(),c.preventDefault(),de.click()}}},Ss=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(ge)&&($.cancel(),ce==null||ce.reset(),ie==null||ie.update(),xo(),c.preventDefault(),c.stopImmediatePropagation())},Ts=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!rt)return;let g=Oy(c.clipboardData);g.length!==0&&(c.preventDefault(),await rt.handleFiles(g))},Tn=null,Vn=!1,Or=null,lt=null,Es=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,vo=(c="user")=>{var D,N,j,R,Se,me,Z;if(Vn||$.isStreaming())return;let g=Es();if(!g)return;Tn=new g;let y=(N=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?N:2e3;Tn.continuous=!0,Tn.interimResults=!0,Tn.lang="en-US";let T=fe.value;Tn.onresult=we=>{let Ee="",_e="";for(let ze=0;ze<we.results.length;ze++){let mt=we.results[ze],dt=mt[0].transcript;mt.isFinal?Ee+=dt+" ":_e=dt}let ot=T+Ee+_e;fe.value=ot,Or&&clearTimeout(Or),(Ee||_e)&&(Or=window.setTimeout(()=>{let ze=fe.value.trim();ze&&Tn&&Vn&&(vr(),fe.value="",fe.style.height="auto",$.sendMessage(ze,{viaVoice:!0}))},y))},Tn.onerror=we=>{we.error!=="no-speech"&&vr()},Tn.onend=()=>{if(Vn){let we=fe.value.trim();we&&we!==T.trim()&&(fe.value="",fe.style.height="auto",$.sendMessage(we,{viaVoice:!0})),vr()}};try{if(Tn.start(),Vn=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),ar(c),In(),q){let we=(j=r.voiceRecognition)!=null?j:{};lt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(R=we.iconName)!=null?R:"mic",iconSize:parseFloat((Z=(me=we.iconSize)!=null?me:(Se=r.sendButton)==null?void 0:Se.size)!=null?Z:"40")||24};let Ee=we.recordingBackgroundColor,_e=we.recordingIconColor,ot=we.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Ee!=null?Ee:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=_e!=null?_e:"var(--persona-voice-recording-indicator, #ffffff)",_e){let ze=q.querySelector("svg");ze&&ze.setAttribute("stroke",_e)}ot&&(q.style.borderColor=ot),q.setAttribute("aria-label","Stop voice recognition")}}catch{vr("system")}},vr=(c="user")=>{if(Vn){if(Vn=!1,Or&&(clearTimeout(Or),Or=null),Tn){try{Tn.stop()}catch{}Tn=null}if(bt.active=!1,ar(c),In(),q){if(q.classList.remove("persona-voice-recording"),lt){q.style.backgroundColor=lt.backgroundColor,q.style.color=lt.color,q.style.borderColor=lt.borderColor;let g=q.querySelector("svg");g&&g.setAttribute("stroke",lt.color||"currentColor"),lt=null}q.setAttribute("aria-label","Start voice recognition")}}},Uo=(c,g)=>{var mt,dt,Pe,ke,Ue,Qe,xt,k;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((mt=c==null?void 0:c.provider)==null?void 0:mt.type)==="runtype";if(!(b||y))return null;let D=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",N.setAttribute("aria-label","Start voice recognition");let j=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",R=(Pe=g==null?void 0:g.size)!=null?Pe:"40px",Se=(ke=c==null?void 0:c.iconSize)!=null?ke:R,me=parseFloat(Se)||24,Z=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:g==null?void 0:g.backgroundColor,we=(Qe=c==null?void 0:c.iconColor)!=null?Qe:g==null?void 0:g.textColor;N.style.width=Se,N.style.height=Se,N.style.minWidth=Se,N.style.minHeight=Se,N.style.fontSize="18px",N.style.lineHeight="1",we?N.style.color=we:N.style.color="var(--persona-text, #111827)";let _e=Ce(j,me,we||"currentColor",1.5);_e?N.appendChild(_e):N.textContent="\u{1F3A4}",Z?N.style.backgroundColor=Z:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),D.appendChild(N);let ot=(xt=c==null?void 0:c.tooltipText)!=null?xt:"Start voice recognition";if(((k=c==null?void 0:c.showTooltip)!=null?k:!1)&&ot){let Ne=h("div","persona-send-button-tooltip");Ne.textContent=ot,D.appendChild(Ne)}return{micButton:N,micButtonWrapper:D}},Ke=()=>{var g,b,y,T,D;if(!q||lt)return;let c=(g=r.voiceRecognition)!=null?g:{};lt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((D=(T=c.iconSize)!=null?T:(y=r.sendButton)==null?void 0:y.size)!=null?D:"40")||24}},C=(c,g)=>{var D,N,j,R,Se;if(!q)return;let b=q.querySelector("svg");b&&b.remove();let y=(Se=lt==null?void 0:lt.iconSize)!=null?Se:parseFloat((R=(j=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?j:(N=r.sendButton)==null?void 0:N.size)!=null?R:"40")||24,T=Ce(c,y,g,1.5);T&&q.appendChild(T)},_=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},E=()=>{var T;if(!q)return;Ke();let c=(T=r.voiceRecognition)!=null?T:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,y=c.recordingBorderColor;if(_(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let D=q.querySelector("svg");D&&D.setAttribute("stroke",b)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},Y=()=>{var j,R,Se,me,Z,we,Ee,_e;if(!q)return;Ke();let c=(j=r.voiceRecognition)!=null?j:{},g=$.getVoiceInterruptionMode(),b=(R=c.processingIconName)!=null?R:"loader",y=(me=(Se=c.processingIconColor)!=null?Se:lt==null?void 0:lt.color)!=null?me:"",T=(we=(Z=c.processingBackgroundColor)!=null?Z:lt==null?void 0:lt.backgroundColor)!=null?we:"",D=(_e=(Ee=c.processingBorderColor)!=null?Ee:lt==null?void 0:lt.borderColor)!=null?_e:"";_(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=T,q.style.borderColor=D;let N=y||"currentColor";q.style.color=N,C(b,N),q.setAttribute("aria-label","Processing voice input"),g==="none"&&(q.style.cursor="default")},ae=()=>{var Se,me,Z,we,Ee,_e,ot,ze,mt,dt,Pe,ke;if(!q)return;Ke();let c=(Se=r.voiceRecognition)!=null?Se:{},g=$.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(me=c.speakingIconName)!=null?me:b,T=(_e=c.speakingIconColor)!=null?_e:g==="barge-in"?(we=(Z=c.recordingIconColor)!=null?Z:lt==null?void 0:lt.color)!=null?we:"":(Ee=lt==null?void 0:lt.color)!=null?Ee:"",D=(mt=c.speakingBackgroundColor)!=null?mt:g==="barge-in"?(ot=c.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(ze=lt==null?void 0:lt.backgroundColor)!=null?ze:"",N=(ke=c.speakingBorderColor)!=null?ke:g==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=lt==null?void 0:lt.borderColor)!=null?Pe:"";_(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=D,q.style.borderColor=N;let j=T||"currentColor";q.style.color=j,C(y,j);let R=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",R),g==="none"&&(q.style.cursor="default"),g==="barge-in"&&q.classList.add("persona-voice-recording")},J=()=>{var c,g,b;q&&(_(),lt&&(q.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",q.style.color=(g=lt.color)!=null?g:"",q.style.borderColor=(b=lt.borderColor)!=null?b:"",C(lt.iconName,lt.color||"currentColor"),lt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},Me=()=>{var c,g;if(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let b=$.getVoiceStatus(),y=$.getVoiceInterruptionMode();if(y==="none"&&(b==="processing"||b==="speaking"))return;if(y==="cancel"&&(b==="processing"||b==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,In(),ar("user"),J()});return}$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),bt.manuallyDeactivated=!$.isVoiceActive(),In(),ar("user"),$.isVoiceActive()?E():J()});return}if(Vn){let b=fe.value.trim();bt.manuallyDeactivated=!0,In(),vr("user"),b&&(fe.value="",fe.style.height="auto",$.sendMessage(b))}else bt.manuallyDeactivated=!1,In(),vo("user")};Bn=Me,q&&(q.addEventListener("click",Me),yt.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),J()):vr("system"),q&&q.removeEventListener("click",Me)}));let Oe=o.on("assistant:complete",()=>{ms&&(bt.active||bt.manuallyDeactivated||ms==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!bt.active&&!bt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),ar("auto"),$.isVoiceActive()&&E()}):vo("auto"))},600))});yt.push(Oe);let ct=o.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});yt.push(ct);let Ge=()=>{Dt(!W,"user")},Xe=null,et=null;if(S&&!F()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>Xs(r,Ge).element,onToggle:Ge});g&&(et=g)}et||(Xe=Xs(r,Ge))}Xe?e.appendChild(Xe.element):et&&e.appendChild(et),Zr(),fr.render(r.suggestionChips,$,fe,void 0,r.suggestionChipsConfig),xs(),Fo($.isStreaming()),Gr(!0),la(),M&&(!S||F()?setTimeout(()=>$o(),0):W&&setTimeout(()=>$o(),200));let Yt=()=>{var R,Se,me,Z,we,Ee,_e,ot,ze,mt,dt,Pe,ke,Ue,Qe,xt,k,Ne,ee,tt,Ot,Nt;if(F()){Ct(),Zr();return}let c=un(r),g=(Se=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?Se:!1,b=c||g||((Z=(me=r.launcher)==null?void 0:me.fullHeight)!=null?Z:!1),y=(we=e.ownerDocument.defaultView)!=null?we:window,T=(_e=(Ee=r.launcher)==null?void 0:Ee.mobileFullscreen)!=null?_e:!0,D=(ze=(ot=r.launcher)==null?void 0:ot.mobileBreakpoint)!=null?ze:640,N=y.innerWidth<=D,j=T&&N&&S;try{if(j){gr(),Io(e,r);return}if(P&&(P=!1,gr(),Io(e,r)),!S&&!c){re.style.height="",re.style.width="";return}if(!g&&!c){let qt=(dt=(mt=r==null?void 0:r.launcher)==null?void 0:mt.width)!=null?dt:r==null?void 0:r.launcherWidth,at=qt!=null?qt:pr;re.style.width=at,re.style.maxWidth=at}if(Er(),!b){let qt=y.innerHeight,at=64,ln=(ke=(Pe=r.launcher)==null?void 0:Pe.heightOffset)!=null?ke:0,Kn=Math.max(200,qt-at),Ve=Math.min(640,Kn),wt=Math.max(200,Ve-ln);re.style.height=`${wt}px`}}finally{if(Ct(),Zr(),W&&S){let at=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((xt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?xt:640),ln=(Ne=(k=r.launcher)==null?void 0:k.sidebarMode)!=null?Ne:!1,Kn=(tt=(ee=r.launcher)==null?void 0:ee.mobileFullscreen)!=null?tt:!0,Ve=un(r)&&Kn&&at,wt=ln||Kn&&at&&S||Ve;if(wt&&!Qt){let Jn=e.getRootNode(),on=Jn instanceof ShadowRoot?Jn.host:e.closest(".persona-host");on&&!Xt&&(Xt=qi(on,(Nt=(Ot=r.launcher)==null?void 0:Ot.zIndex)!=null?Nt:vn)),Qt=zi(e.ownerDocument)}else wt||(Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null)}}};Yt();let Lt=(Cc=e.ownerDocument.defaultView)!=null?Cc:window;if(Lt.addEventListener("resize",Yt),yt.push(()=>Lt.removeEventListener("resize",Yt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Ct()});c.observe($e),yt.push(()=>c.disconnect())}yr=G.scrollTop;let Ht=G.scrollHeight,an=()=>{let c=G.scrollTop,g=G.scrollHeight,b=g<Ht;Ht=g;let{action:y,nextLastScrollTop:T}=ja({following:br.isFollowing(),currentScrollTop:c,lastScrollTop:yr,nearBottom:Us(G,us),userScrollThreshold:aa,isAutoScrolling:Hr||ho||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(yr=T,y==="resume"){Jr();return}y==="pause"&&fs()};G.addEventListener("scroll",an,{passive:!0}),yt.push(()=>G.removeEventListener("scroll",an));let hn=c=>{let g=Ua({following:br.isFollowing(),deltaY:c.deltaY,nearBottom:Us(G,us),resumeWhenNearBottom:!0});g==="pause"?fs():g==="resume"&&Jr()};G.addEventListener("wheel",hn,{passive:!0}),yt.push(()=>G.removeEventListener("wheel",hn)),It.addEventListener("click",()=>{G.scrollTop=G.scrollHeight,yr=G.scrollTop,Jr(),Gr(!0)}),yt.push(()=>It.remove()),yt.push(()=>{gs()});let fn=()=>{je&&(qn&&(je.removeEventListener("click",qn),qn=null),B()?(je.style.display="",qn=()=>{Dt(!1,"user")},je.addEventListener("click",qn)):je.style.display="none")};fn(),(()=>{let{clearChatButton:c}=Ie;c&&c.addEventListener("click",()=>{$.clearMessages(),be.clear(),Jr(),Ho(Ie.composerOverlay);try{localStorage.removeItem(cs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cs}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==cs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},w.syncFromMetadata(),z==null||z.clear(),ce==null||ce.reset(),ie==null||ie.update()})})(),jt&&jt.addEventListener("submit",ws),fe==null||fe.addEventListener("keydown",As),fe==null||fe.addEventListener("input",Cs),fe==null||fe.addEventListener("paste",Ts);let ir=(Ac=e.ownerDocument)!=null?Ac:document;ir.addEventListener("keydown",Ss,!0);let Ll="persona-attachment-drop-active",Ms=0,Ti=()=>{Ms=0,ge.classList.remove(Ll)},qo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&rt!==null},Pl=c=>{!fi(c.dataTransfer)||!qo()||(Ms++,Ms===1&&ge.classList.add(Ll))},Il=c=>{!fi(c.dataTransfer)||!qo()||(Ms--,Ms<=0&&Ti())},Wl=c=>{!fi(c.dataTransfer)||!qo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Rl=c=>{var b;if(!fi(c.dataTransfer)||!qo())return;c.preventDefault(),c.stopPropagation(),Ti();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&rt.handleFiles(g)},eo=!0;ge.addEventListener("dragenter",Pl,eo),ge.addEventListener("dragleave",Il,eo),e.addEventListener("dragover",Wl,eo),e.addEventListener("drop",Rl,eo);let wa=e.ownerDocument,Hl=c=>{qo()&&c.preventDefault()},Bl=c=>{qo()&&c.preventDefault()};wa.addEventListener("dragover",Hl),wa.addEventListener("drop",Bl),yt.push(()=>{jt&&jt.removeEventListener("submit",ws),fe==null||fe.removeEventListener("keydown",As),fe==null||fe.removeEventListener("input",Cs),fe==null||fe.removeEventListener("paste",Ts),ir.removeEventListener("keydown",Ss,!0)}),yt.push(()=>{ge.removeEventListener("dragenter",Pl,eo),ge.removeEventListener("dragleave",Il,eo),e.removeEventListener("dragover",Wl,eo),e.removeEventListener("drop",Rl,eo),wa.removeEventListener("dragover",Hl),wa.removeEventListener("drop",Bl),Ti()}),yt.push(()=>{$.cancel()}),Xe?yt.push(()=>{Xe==null||Xe.destroy()}):et&&yt.push(()=>{et==null||et.remove()});let rn={update(c){var en,kr,sn,En,dr,So,To,Ca,ks,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Od,Fd,$d,_d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,xp,vp,wp,Cp,Ap,Sp,Tp;let g=r.toolCall,b=r.messageActions,y=(en=r.layout)==null?void 0:en.messages,T=r.colorScheme,D=r.loadingIndicator,N=r.iterationDisplay,j=(kr=r.features)==null?void 0:kr.showReasoning,R=(sn=r.features)==null?void 0:sn.showToolCalls,Se=(En=r.features)==null?void 0:En.toolCallDisplay,me=(dr=r.features)==null?void 0:dr.reasoningDisplay;r={...r,...c},gr(),Io(e,r),di(e,r),pi(e,r),jn(),r.colorScheme!==T&&Kr();let Z=ui.getForInstance(r.plugins);s.length=0,s.push(...Z),S=(To=(So=r.launcher)==null?void 0:So.enabled)!=null?To:!0,H=(ks=(Ca=r.launcher)==null?void 0:Ca.autoExpand)!=null?ks:!1,Je=(Ic=(Pc=r.features)==null?void 0:Pc.showReasoning)!=null?Ic:!0,ve=(Rc=(Wc=r.features)==null?void 0:Wc.showToolCalls)!=null?Rc:!0,he=(Bc=(Hc=r.features)==null?void 0:Hc.scrollToBottom)!=null?Bc:{},Jt(),Dr();let we=Re;if(Re=(Nc=(Dc=r.features)==null?void 0:Dc.showEventStreamToggle)!=null?Nc:!1,Re&&!we){if(z||(K=new ra(Le),z=new na(pe,K),ce=ce!=null?ce:new oa,K.open().then(()=>z==null?void 0:z.restore()).catch(()=>{}),$.setSSEEventCallback((X,St)=>{var $t;($t=r.onSSEEvent)==null||$t.call(r,X,St),ce==null||ce.processEvent(X,St),z.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(St)})})),!ht&&De){let X=(Fc=(Oc=r.features)==null?void 0:Oc.eventStream)==null?void 0:Fc.classNames,St="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"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");ht=h("button",St),ht.style.width="28px",ht.style.height="28px",ht.style.color=kn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let $t=Ce("activity","18px","currentColor",1.5);$t&&ht.appendChild($t);let pt=Ie.clearChatButtonWrapper,Wt=Ie.closeButtonWrapper,dn=pt||Wt;dn&&dn.parentNode===De?De.insertBefore(ht,dn):De.appendChild(ht),ht.addEventListener("click",()=>{se?Dn():Cn()})}}else!Re&&we&&(Dn(),ht&&(ht.remove(),ht=null),z==null||z.clear(),K==null||K.destroy(),z=null,K=null,ce==null||ce.reset(),ce=null);if((($c=r.launcher)==null?void 0:$c.enabled)===!1&&Xe&&(Xe.destroy(),Xe=null),((_c=r.launcher)==null?void 0:_c.enabled)===!1&&et&&(et.remove(),et=null),((jc=r.launcher)==null?void 0:jc.enabled)!==!1&&!Xe&&!et){let X=s.find(St=>St.renderLauncher);if(X!=null&&X.renderLauncher){let St=X.renderLauncher({config:r,defaultRenderer:()=>Xs(r,Ge).element,onToggle:Ge});St&&(et=St,e.appendChild(et))}et||(Xe=Xs(r,Ge),e.appendChild(Xe.element))}Xe&&Xe.update(r),Te&&((Uc=r.launcher)==null?void 0:Uc.title)!==void 0&&(Te.textContent=r.launcher.title),Be&&((qc=r.launcher)==null?void 0:qc.subtitle)!==void 0&&(Be.textContent=r.launcher.subtitle);let Ee=(zc=r.layout)==null?void 0:zc.header;if((Ee==null?void 0:Ee.layout)!==A&&De){let X=Ee?Qs(r,Ee,{showClose:B(),onClose:()=>Dt(!1,"user")}):io({config:r,showClose:B(),onClose:()=>Dt(!1,"user")});De.replaceWith(X.header),De=X.header,O=X.iconHolder,Te=X.headerTitle,Be=X.headerSubtitle,je=X.closeButton,A=Ee==null?void 0:Ee.layout}else if(Ee&&(O&&(O.style.display=Ee.showIcon===!1?"none":""),Te&&(Te.style.display=Ee.showTitle===!1?"none":""),Be&&(Be.style.display=Ee.showSubtitle===!1?"none":""),je&&(je.style.display=Ee.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let X=Ee.showClearChat;if(X!==void 0){Ie.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:St}=Ie;St&&!St.classList.contains("persona-absolute")&&(X?St.classList.remove("persona-ml-auto"):St.classList.add("persona-ml-auto"))}}let ot=((Vc=r.layout)==null?void 0:Vc.showHeader)!==!1;De&&(De.style.display=ot?"":"none");let ze=((Kc=r.layout)==null?void 0:Kc.showFooter)!==!1;$e&&($e.style.display=ze?"":"none"),Ct(),Dr(),S!==I?S?Dt(H,"auto"):(W=!0,Zr()):H!==L&&Dt(H,"auto"),L=H,I=S,Yt(),fn();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(g),ke=JSON.stringify(r.messageActions)!==JSON.stringify(b),Ue=JSON.stringify((Jc=r.layout)==null?void 0:Jc.messages)!==JSON.stringify(y),Qe=((Gc=r.loadingIndicator)==null?void 0:Gc.render)!==(D==null?void 0:D.render)||((Xc=r.loadingIndicator)==null?void 0:Xc.renderIdle)!==(D==null?void 0:D.renderIdle)||((Qc=r.loadingIndicator)==null?void 0:Qc.showBubble)!==(D==null?void 0:D.showBubble),xt=r.iterationDisplay!==N,k=((Zc=(Yc=r.features)==null?void 0:Yc.showReasoning)!=null?Zc:!0)!==(j!=null?j:!0)||((td=(ed=r.features)==null?void 0:ed.showToolCalls)!=null?td:!0)!==(R!=null?R:!0)||JSON.stringify((nd=r.features)==null?void 0:nd.toolCallDisplay)!==JSON.stringify(Se)||JSON.stringify((rd=r.features)==null?void 0:rd.reasoningDisplay)!==JSON.stringify(me);(Pe||ke||Ue||Qe||xt||k)&&$&&(ps++,yo(Fe,$.getMessages(),We));let ee=(od=r.launcher)!=null?od:{},tt=(sd=ee.headerIconHidden)!=null?sd:!1,Ot=(id=(ad=r.layout)==null?void 0:ad.header)==null?void 0:id.showIcon,Nt=tt||Ot===!1,qt=ee.headerIconName,at=(ld=ee.headerIconSize)!=null?ld:"48px";if(O){let X=ge.querySelector(".persona-border-b-persona-divider"),St=X==null?void 0:X.querySelector(".persona-flex-col");if(Nt)O.style.display="none",X&&St&&!X.contains(St)&&X.insertBefore(St,X.firstChild);else{if(O.style.display="",O.style.height=at,O.style.width=at,X&&St&&(X.contains(O)?O.nextSibling!==St&&(O.remove(),X.insertBefore(O,St)):X.insertBefore(O,St)),qt){let pt=parseFloat(at)||24,Wt=Ce(qt,pt*.6,"#ffffff",2);Wt?O.replaceChildren(Wt):O.textContent=(cd=ee.agentIconText)!=null?cd:"\u{1F4AC}"}else if(ee.iconUrl){let pt=O.querySelector("img");if(pt)pt.src=ee.iconUrl,pt.style.height=at,pt.style.width=at;else{let Wt=document.createElement("img");Wt.src=ee.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=at,Wt.style.width=at,O.replaceChildren(Wt)}}else{let pt=O.querySelector("svg"),Wt=O.querySelector("img");(pt||Wt)&&O.replaceChildren(),O.textContent=(dd=ee.agentIconText)!=null?dd:"\u{1F4AC}"}let $t=O.querySelector("img");$t&&($t.style.height=at,$t.style.width=at)}}let ln=(ud=(pd=r.layout)==null?void 0:pd.header)==null?void 0:ud.showTitle,Kn=(gd=(md=r.layout)==null?void 0:md.header)==null?void 0:gd.showSubtitle;if(Te&&(Te.style.display=ln===!1?"none":""),Be&&(Be.style.display=Kn===!1?"none":""),je){((hd=(fd=r.layout)==null?void 0:fd.header)==null?void 0:hd.showCloseButton)===!1?je.style.display="none":je.style.display="";let St=(bd=ee.closeButtonSize)!=null?bd:"32px",$t=(yd=ee.closeButtonPlacement)!=null?yd:"inline";je.style.height=St,je.style.width=St;let{closeButtonWrapper:pt}=Ie,Wt=$t==="top-right",dn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&Wt!==dn)if(pt.remove(),Wt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(pt);else{let ft=(vd=(xd=ee.clearChat)==null?void 0:xd.placement)!=null?vd:"inline",pn=(Cd=(wd=ee.clearChat)==null?void 0:wd.enabled)!=null?Cd:!0;pt.className=pn&&ft==="inline"?"":"persona-ml-auto";let Rn=ge.querySelector(".persona-border-b-persona-divider");Rn&&Rn.appendChild(pt)}if(je.style.color=ee.closeButtonColor||kn.actionIconColor,ee.closeButtonBackgroundColor?(je.style.backgroundColor=ee.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),ee.closeButtonBorderWidth||ee.closeButtonBorderColor){let ft=ee.closeButtonBorderWidth||"0px",pn=ee.closeButtonBorderColor||"transparent";je.style.border=`${ft} solid ${pn}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");ee.closeButtonBorderRadius?(je.style.borderRadius=ee.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),ee.closeButtonPaddingX?(je.style.paddingLeft=ee.closeButtonPaddingX,je.style.paddingRight=ee.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),ee.closeButtonPaddingY?(je.style.paddingTop=ee.closeButtonPaddingY,je.style.paddingBottom=ee.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom="");let yn=(Ad=ee.closeButtonIconName)!=null?Ad:"x",wr=(Sd=ee.closeButtonIconText)!=null?Sd:"\xD7";je.innerHTML="";let Mn=Ce(yn,"28px","currentColor",1);Mn?je.appendChild(Mn):je.textContent=wr;let Zt=(Td=ee.closeButtonTooltipText)!=null?Td:"Close chat",Xn=(Ed=ee.closeButtonShowTooltip)!=null?Ed:!0;if(je.setAttribute("aria-label",Zt),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),Xn&&Zt)){let ft=null,pn=()=>{if(ft||!je)return;let Eo=je.ownerDocument,Ls=Eo.body;if(!Ls)return;ft=Lr(Eo,"div","persona-clear-chat-tooltip"),ft.textContent=Zt;let Ps=Lr(Eo,"div");Ps.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Ps);let Mo=je.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(oo),ft.style.left=`${Mo.left+Mo.width/2}px`,ft.style.top=`${Mo.top-8}px`,ft.style.transform="translate(-50%, -100%)",Ls.appendChild(ft)},Rn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};pt.addEventListener("mouseenter",pn),pt.addEventListener("mouseleave",Rn),je.addEventListener("focus",pn),je.addEventListener("blur",Rn),pt._cleanupTooltip=()=>{Rn(),pt&&(pt.removeEventListener("mouseenter",pn),pt.removeEventListener("mouseleave",Rn)),je&&(je.removeEventListener("focus",pn),je.removeEventListener("blur",Rn))}}}let{clearChatButton:Ve,clearChatButtonWrapper:wt}=Ie;if(Ve){let X=(Md=ee.clearChat)!=null?Md:{},St=(kd=X.enabled)!=null?kd:!0,$t=(Pd=(Ld=r.layout)==null?void 0:Ld.header)==null?void 0:Pd.showClearChat,pt=$t!==void 0?$t:St,Wt=(Id=X.placement)!=null?Id:"inline";if(wt){wt.style.display=pt?"":"none";let{closeButtonWrapper:dn}=Ie;!F()&&dn&&!dn.classList.contains("persona-absolute")&&(pt?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let yn=Wt==="top-right",wr=wt.classList.contains("persona-absolute");if(!F()&&yn!==wr&&pt){if(wt.remove(),yn)wt.className="persona-absolute persona-top-4 persona-z-50",wt.style.right="48px",ge.style.position="relative",ge.appendChild(wt);else{wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wt.style.right="";let Zt=ge.querySelector(".persona-border-b-persona-divider"),Xn=Ie.closeButtonWrapper;Zt&&Xn&&Xn.parentElement===Zt?Zt.insertBefore(wt,Xn):Zt&&Zt.appendChild(wt)}let Mn=Ie.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(yn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(pt){if(!F()){let ft=(Wd=X.size)!=null?Wd:"32px";Ve.style.height=ft,Ve.style.width=ft}let dn=(Rd=X.iconName)!=null?Rd:"refresh-cw",yn=(Hd=X.iconColor)!=null?Hd:"";Ve.style.color=yn||kn.actionIconColor,Ve.innerHTML="";let wr=F()?"14px":"20px",Mn=Ce(dn,wr,"currentColor",2);if(Mn&&Ve.appendChild(Mn),X.backgroundColor?(Ve.style.backgroundColor=X.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let ft=X.borderWidth||"0px",pn=X.borderColor||"transparent";Ve.style.border=`${ft} solid ${pn}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");X.borderRadius?(Ve.style.borderRadius=X.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),X.paddingX?(Ve.style.paddingLeft=X.paddingX,Ve.style.paddingRight=X.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),X.paddingY?(Ve.style.paddingTop=X.paddingY,Ve.style.paddingBottom=X.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Zt=(Bd=X.tooltipText)!=null?Bd:"Clear chat",Xn=(Dd=X.showTooltip)!=null?Dd:!0;if(Ve.setAttribute("aria-label",Zt),wt&&(wt._cleanupTooltip&&(wt._cleanupTooltip(),delete wt._cleanupTooltip),Xn&&Zt)){let ft=null,pn=()=>{if(ft||!Ve)return;let Eo=Ve.ownerDocument,Ls=Eo.body;if(!Ls)return;ft=Lr(Eo,"div","persona-clear-chat-tooltip"),ft.textContent=Zt;let Ps=Lr(Eo,"div");Ps.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Ps);let Mo=Ve.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(oo),ft.style.left=`${Mo.left+Mo.width/2}px`,ft.style.top=`${Mo.top-8}px`,ft.style.transform="translate(-50%, -100%)",Ls.appendChild(ft)},Rn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};wt.addEventListener("mouseenter",pn),wt.addEventListener("mouseleave",Rn),Ve.addEventListener("focus",pn),Ve.addEventListener("blur",Rn),wt._cleanupTooltip=()=>{Rn(),wt&&(wt.removeEventListener("mouseenter",pn),wt.removeEventListener("mouseleave",Rn)),Ve&&(Ve.removeEventListener("focus",pn),Ve.removeEventListener("blur",Rn))}}}}let Jn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[mi],on=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ls.message,ls.messageAndClick];w=gi({parsers:Jn,handlers:on,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),We=om(r,w,oe),$.updateConfig(r),yo(Fe,$.getMessages(),We),fr.render(r.suggestionChips,$,fe,void 0,r.suggestionChipsConfig),xs(),Fo($.isStreaming());let cr=((Nd=r.voiceRecognition)==null?void 0:Nd.enabled)===!0,Gn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),wo=((Fd=(Od=r.voiceRecognition)==null?void 0:Od.provider)==null?void 0:Fd.type)==="runtype";if(cr&&(Gn||wo))if(!q||!Ut){let X=Uo(r.voiceRecognition,r.sendButton);X&&(q=X.micButton,Ut=X.micButtonWrapper,Pt.insertBefore(Ut,Ln),q.addEventListener("click",Me),q.disabled=$.isStreaming())}else{let X=($d=r.voiceRecognition)!=null?$d:{},St=(_d=r.sendButton)!=null?_d:{},$t=(jd=X.iconName)!=null?jd:"mic",pt=(Ud=St.size)!=null?Ud:"40px",Wt=(qd=X.iconSize)!=null?qd:pt,dn=parseFloat(Wt)||24;q.style.width=Wt,q.style.height=Wt,q.style.minWidth=Wt,q.style.minHeight=Wt;let yn=(Vd=(zd=X.iconColor)!=null?zd:St.textColor)!=null?Vd:"currentColor";q.innerHTML="";let wr=Ce($t,dn,yn,2);wr?q.appendChild(wr):q.textContent="\u{1F3A4}";let Mn=(Kd=X.backgroundColor)!=null?Kd:St.backgroundColor;Mn?q.style.backgroundColor=Mn:q.style.backgroundColor="",yn?q.style.color=yn:q.style.color="var(--persona-text, #111827)",X.borderWidth?(q.style.borderWidth=X.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),X.borderColor?q.style.borderColor=X.borderColor:q.style.borderColor="",X.paddingX?(q.style.paddingLeft=X.paddingX,q.style.paddingRight=X.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),X.paddingY?(q.style.paddingTop=X.paddingY,q.style.paddingBottom=X.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Zt=Ut==null?void 0:Ut.querySelector(".persona-send-button-tooltip"),Xn=(Jd=X.tooltipText)!=null?Jd:"Start voice recognition";if(((Gd=X.showTooltip)!=null?Gd:!1)&&Xn)if(Zt)Zt.textContent=Xn,Zt.style.display="";else{let pn=document.createElement("div");pn.className="persona-send-button-tooltip",pn.textContent=Xn,Ut==null||Ut.insertBefore(pn,q)}else Zt&&(Zt.style.display="none");Ut.style.display="",q.disabled=$.isStreaming()}else q&&Ut&&(Ut.style.display="none",((Qd=(Xd=r.voiceRecognition)==null?void 0:Xd.provider)==null?void 0:Qd.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Vn&&vr());if(((Yd=r.attachments)==null?void 0:Yd.enabled)===!0)if(!Ft||!Ze){let X=(Zd=r.attachments)!=null?Zd:{},$t=(tp=((ep=r.sendButton)!=null?ep:{}).size)!=null?tp:"40px";xe||(xe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),xe.style.display="none",jt.insertBefore(xe,fe)),ne||(ne=document.createElement("input"),ne.type="file",ne.accept=((np=X.allowedTypes)!=null?np:$r).join(","),ne.multiple=((rp=X.maxFiles)!=null?rp:4)>1,ne.style.display="none",ne.setAttribute("aria-label","Attach files"),jt.insertBefore(ne,fe)),Ft=h("div","persona-send-button-wrapper"),Ze=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ze.type="button",Ze.setAttribute("aria-label",(op=X.buttonTooltipText)!=null?op:"Attach file");let pt=(sp=X.buttonIconName)!=null?sp:"paperclip",Wt=$t,dn=parseFloat(Wt)||40,yn=Math.round(dn*.6);Ze.style.width=Wt,Ze.style.height=Wt,Ze.style.minWidth=Wt,Ze.style.minHeight=Wt,Ze.style.fontSize="18px",Ze.style.lineHeight="1",Ze.style.backgroundColor="transparent",Ze.style.color="var(--persona-primary, #111827)",Ze.style.border="none",Ze.style.borderRadius="6px",Ze.style.transition="background-color 0.15s ease",Ze.addEventListener("mouseenter",()=>{Ze.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ze.addEventListener("mouseleave",()=>{Ze.style.backgroundColor="transparent"});let wr=Ce(pt,yn,"currentColor",1.5);wr?Ze.appendChild(wr):Ze.textContent="\u{1F4CE}",Ze.addEventListener("click",Xn=>{Xn.preventDefault(),ne==null||ne.click()}),Ft.appendChild(Ze);let Mn=(ap=X.buttonTooltipText)!=null?ap:"Attach file",Zt=h("div","persona-send-button-tooltip");Zt.textContent=Mn,Ft.appendChild(Zt),st.append(Ft),!rt&&ne&&xe&&(rt=Zo.fromConfig(X),rt.setPreviewsContainer(xe),ne.addEventListener("change",async()=>{rt&&(ne!=null&&ne.files)&&(await rt.handleFileSelect(ne.files),ne.value="")})),ge.querySelector(".persona-attachment-drop-overlay")||ge.appendChild(sm(X.dropOverlay))}else{Ft.style.display="";let X=(ip=r.attachments)!=null?ip:{};ne&&(ne.accept=((lp=X.allowedTypes)!=null?lp:$r).join(","),ne.multiple=((cp=X.maxFiles)!=null?cp:4)>1),rt&&rt.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Ft&&(Ft.style.display="none"),rt&&rt.clearAttachments(),(dp=ge.querySelector(".persona-attachment-drop-overlay"))==null||dp.remove();let Gt=(pp=r.sendButton)!=null?pp:{},Co=(up=Gt.useIcon)!=null?up:!1,to=(mp=Gt.iconText)!=null?mp:"\u2191",no=Gt.iconName,Fr=(gp=Gt.tooltipText)!=null?gp:"Send message",Ao=(fp=Gt.showTooltip)!=null?fp:!1,nt=(hp=Gt.size)!=null?hp:"40px",bn=Gt.backgroundColor,gn=Gt.textColor;if(Co){if(de.style.width=nt,de.style.height=nt,de.style.minWidth=nt,de.style.minHeight=nt,de.style.fontSize="18px",de.style.lineHeight="1",de.innerHTML="",gn?de.style.color=gn:de.style.color="var(--persona-button-primary-fg, #ffffff)",no){let X=parseFloat(nt)||24,St=(gn==null?void 0:gn.trim())||"currentColor",$t=Ce(no,X,St,2);$t?de.appendChild($t):de.textContent=to}else de.textContent=to;de.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",bn?(de.style.backgroundColor=bn,de.classList.remove("persona-bg-persona-primary")):(de.style.backgroundColor="",de.classList.add("persona-bg-persona-primary"))}else de.textContent=(yp=(bp=r.copy)==null?void 0:bp.sendButtonLabel)!=null?yp:"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",bn?(de.style.backgroundColor=bn,de.classList.remove("persona-bg-persona-accent")):de.classList.add("persona-bg-persona-accent"),gn?de.style.color=gn:de.classList.add("persona-text-white");Gt.borderWidth?(de.style.borderWidth=Gt.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),Gt.borderColor?de.style.borderColor=Gt.borderColor:de.style.borderColor="",Gt.paddingX?(de.style.paddingLeft=Gt.paddingX,de.style.paddingRight=Gt.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Gt.paddingY?(de.style.paddingTop=Gt.paddingY,de.style.paddingBottom=Gt.paddingY):(de.style.paddingTop="",de.style.paddingBottom="");let cn=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Ao&&Fr)if(cn)cn.textContent=Fr,cn.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Fr,Ln==null||Ln.insertBefore(X,de)}else cn&&(cn.style.display="none");let gt=(Ap=(xp=r.layout)==null?void 0:xp.contentMaxWidth)!=null?Ap:F()?(Cp=(wp=(vp=r.launcher)==null?void 0:vp.composerBar)==null?void 0:wp.contentMaxWidth)!=null?Cp:"720px":void 0;gt?(Fe.style.maxWidth=gt,Fe.style.marginLeft="auto",Fe.style.marginRight="auto",Fe.style.width="100%",jt&&(jt.style.maxWidth=gt,jt.style.marginLeft="auto",jt.style.marginRight="auto"),Rt&&(Rt.style.maxWidth=gt,Rt.style.marginLeft="auto",Rt.style.marginRight="auto")):(Fe.style.maxWidth="",Fe.style.marginLeft="",Fe.style.marginRight="",Fe.style.width="",jt&&(jt.style.maxWidth="",jt.style.marginLeft="",jt.style.marginRight=""),Rt&&(Rt.style.maxWidth="",Rt.style.marginLeft="",Rt.style.marginRight=""));let it=(Sp=r.statusIndicator)!=null?Sp:{},Et=(Tp=it.visible)!=null?Tp:!0;if(mn.style.display=Et?"":"none",$){let X=$.getStatus();ye(mn,($t=>{var pt,Wt,dn,yn;return $t==="idle"?(pt=it.idleText)!=null?pt:xn.idle:$t==="connecting"?(Wt=it.connectingText)!=null?Wt:xn.connecting:$t==="connected"?(dn=it.connectedText)!=null?dn:xn.connected:$t==="error"?(yn=it.errorText)!=null?yn:xn.error:xn[$t]})(X),it,X)}mn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Wn=it.align==="left"?"persona-text-left":it.align==="center"?"persona-text-center":"persona-text-right";mn.classList.add(Wn)},open(){B()&&Dt(!0,"api")},close(){B()&&Dt(!1,"api")},toggle(){B()&&Dt(!W,"api")},clearChat(){An=!1,$.clearMessages(),be.clear(),Jr();try{localStorage.removeItem(cs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==cs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},w.syncFromMetadata(),z==null||z.clear(),ce==null||ce.reset(),ie==null||ie.update()},setMessage(c){return!fe||$.isStreaming()?!1:(!W&&B()&&Dt(!0,"system"),fe.value=c,fe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let g=(c==null?void 0:c.trim())||fe.value.trim();return g?(!W&&B()&&Dt(!0,"system"),fe.value="",fe.style.height="auto",$.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return $.isStreaming()?!1:((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?($.isVoiceActive()||(!W&&B()&&Dt(!0,"system"),bt.manuallyDeactivated=!1,In(),$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),ar("user"),$.isVoiceActive()&&E()})),!0):Vn?!0:Es()?(!W&&B()&&Dt(!0,"system"),bt.manuallyDeactivated=!1,In(),vo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,In(),ar("user"),J()}),!0):!1:Vn?(bt.manuallyDeactivated=!0,In(),vr("user"),!0):!1},injectMessage(c){return!W&&B()&&Dt(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!W&&B()&&Dt(!0,"system");let g=$.injectAssistantMessage(c);return U&&(U=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),g},injectUserMessage(c){return!W&&B()&&Dt(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!W&&B()&&Dt(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!W&&B()&&Dt(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!W&&B()&&Dt(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!W&&B()&&Dt(!0,"system"),$.injectTestEvent(c)},async connectStream(c,g){return $.connectStream(c,g)},__pushEventStreamEvent(c){z&&(ce==null||ce.processEvent(c.type,c.payload),z.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Re||!z||Cn()},hideEventStream(){se&&Dn()},isEventStreamVisible(){return se},showArtifacts(){mr(r)&&(An=!1,jn(),At==null||At.setMobileOpen(!0))},hideArtifacts(){mr(r)&&(An=!0,jn())},upsertArtifact(c){return mr(r)?(An=!1,$.upsertArtifact(c)):null},selectArtifact(c){mr(r)&&$.selectArtifact(c)},clearArtifacts(){mr(r)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return S&&!W&&!F()||!fe?!1:(fe.focus(),!0)},async resolveApproval(c,g,b){let T=$.getMessages().find(D=>{var N;return D.variant==="approval"&&((N=D.approval)==null?void 0:N.id)===c});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${c}`);if(T.approval.toolType==="webmcp"){$.resolveWebMcpApproval(T.id,g);return}return $.resolveApproval(T.approval,g,b)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return o.on(c,g)},off(c,g){o.off(c,g)},isOpen(){return B()&&W},isVoiceActive(){return bt.active},getState(){return{open:B()&&W,launcherEnabled:S,voiceActive:bt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!W&&B()&&Dt(!0,"system");let g=Fe.querySelector(".persona-feedback-container");g&&g.remove();let b=fl({onSubmit:async(y,T)=>{var D;$.isClientTokenMode()&&await $.submitCSATFeedback(y,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,y,T)},onDismiss:c==null?void 0:c.onDismiss,...c});Fe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!W&&B()&&Dt(!0,"system");let g=Fe.querySelector(".persona-feedback-container");g&&g.remove();let b=hl({onSubmit:async(y,T)=>{var D;$.isClientTokenMode()&&await $.submitNPSFeedback(y,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,y,T)},onDismiss:c==null?void 0:c.onDismiss,...c});Fe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return $.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return $.submitNPSFeedback(c,g)},destroy(){Mr!=null&&(clearInterval(Mr),Mr=null),yt.forEach(c=>c()),ue.remove(),Ye==null||Ye.remove(),Xe==null||Xe.destroy(),et==null||et.remove(),qn&&je.removeEventListener("click",qn)}};if((((Sc=n==null?void 0:n.debugTools)!=null?Sc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:rn,getMessages:rn.getMessages,getStatus:rn.getStatus,getMetadata:rn.getPersistentMetadata,updateMetadata:rn.updatePersistentMetadata,clearHistory:()=>rn.clearChat(),setVoiceActive:b=>b?rn.startVoiceRecognition():rn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,yt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=j=>{let R=j.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&rn.focusInput()};if(window.addEventListener("persona:focusInput",g),yt.push(()=>{window.removeEventListener("persona:focusInput",g)}),Re){let j=Se=>{let me=Se.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&rn.showEventStream()},R=Se=>{let me=Se.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&rn.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",R),yt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",R)})}let b=j=>{let R=j.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&rn.showArtifacts()},y=j=>{let R=j.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&rn.hideArtifacts()},T=j=>{let R=j.detail;R!=null&&R.instanceId&&R.instanceId!==c||R!=null&&R.artifact&&rn.upsertArtifact(R.artifact)},D=j=>{let R=j.detail;R!=null&&R.instanceId&&R.instanceId!==c||typeof(R==null?void 0:R.id)=="string"&&rn.selectArtifact(R.id)},N=j=>{let R=j.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&rn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",N),yt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",N)})}let lr=Fy(r.persistState);if(lr&&B()){let c=$y(lr.storage),g=`${lr.keyPrefix}widget-open`,b=`${lr.keyPrefix}widget-voice`,y=`${lr.keyPrefix}widget-voice-mode`;if(c){let T=((Tc=lr.persist)==null?void 0:Tc.openState)&&c.getItem(g)==="true",D=((Ec=lr.persist)==null?void 0:Ec.voiceState)&&c.getItem(b)==="true",N=((Mc=lr.persist)==null?void 0:Mc.voiceState)&&c.getItem(y)==="true";if(T&&setTimeout(()=>{rn.open(),setTimeout(()=>{var j;if(D||N)rn.startVoiceRecognition();else if((j=lr.persist)!=null&&j.focusInput){let R=e.querySelector("textarea");R&&R.focus()}},100)},0),(kc=lr.persist)!=null&&kc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(Lc=lr.persist)!=null&&Lc.voiceState&&(o.on("voice:state",j=>{c.setItem(b,j.active?"true":"false")}),o.on("user:message",j=>{c.setItem(y,j.viaVoice?"true":"false")})),lr.clearOnChatClear){let j=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(y)},R=()=>j();window.addEventListener("persona:clear-chat",R),yt.push(()=>{window.removeEventListener("persona:clear-chat",R)})}}}return p&&B()&&setTimeout(()=>{rn.open()},0),Nr(),rn};var _y=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},am=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!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"},Cl=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=""},im=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Cl(e)},xl=e=>{e.style.transition=""},vl=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=""},wl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},hi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},jy=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Uy=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},lm=(e,t,n,r,s,o,a)=>{var v,x,w,S,H,M;let i=Ar(o),d=i.reveal==="push";jy(e,t,n,r,d),Uy(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.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",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(S=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileBreakpoint)!=null?S:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),vl(t),xl(r),im(r),wl(n),hi(s,r),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",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((M=(H=o==null?void 0:o.launcher)==null?void 0:H.zIndex)!=null?M:vn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.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.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"),im(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",vl(t),xl(r),wl(n),hi(s,r);let L=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":I;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=L,r.style.transform=A,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",xl(r),Cl(r),hi(s,r);let L=_y(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),A=i.animate?"transform 180ms ease":"none",P=i.side==="right"?a?`translateX(-${L}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${L}px)`;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=`${I+L}px`,t.style.transition=A,t.style.transform=P,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",vl(t),Cl(r),wl(n),hi(s,r);let L=i.reveal==="emerge";L?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",P=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${I}`,r.style.width=I,r.style.maxWidth=I,r.style.minWidth=I,r.style.minHeight="0",r.style.position="relative",r.style.overflow=L||P?"hidden":"visible",r.style.transition=A,L&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},qy=(e,t)=>{let n=e.ownerDocument.createElement("div");return am(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){am(n,r)},destroy(){n.remove()}}},zy=(e,t)=>{var H,M,L,I;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(M=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)==null||M?(I=(L=t==null?void 0:t.launcher)==null?void 0:L.autoExpand)!=null?I:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),Ar(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{lm(a,i,d,l,p,t,u)}),f.observe(a))},x=()=>{lm(a,i,d,l,p,t,u),v()},w=a.ownerDocument.defaultView,S=()=>{x()};return w==null||w.addEventListener("resize",S),Ar(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:p,shell:a,syncWidgetState(A){let P=A.launcherEnabled?A.open:!0;u!==P&&(u=P,x())},updateConfig(A){var P,F;t=A,((F=(P=t==null?void 0:t.launcher)==null?void 0:P.enabled)!=null?F:!0)===!1&&(u=!0),x()},destroy(){w==null||w.removeEventListener("resize",S),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},bi=(e,t)=>un(t)?zy(e,t):qy(e,t);var Al={},cm=!1,Vy=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Ky=()=>{try{if(typeof Al!="undefined"&&Al.url)return new URL("../widget.css",Al.url).href}catch{}return null},dm=(e,t)=>{let n=Ky(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},pm=e=>{let t=Vy(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=bi(t,s),a,i=[],d=(w,S)=>{var I,A;let M=!((A=(I=S==null?void 0:S.launcher)==null?void 0:I.enabled)!=null?A:!0)||un(S),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),M&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),n){let P=w.attachShadow({mode:"open"});P.appendChild(L),dm(P,r)}else w.appendChild(L),dm(w,r);return t.id&&L.setAttribute("data-persona-instance",t.id),L},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(o.host,s);a=yl(w,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(cm||(cm=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let m=w=>{f(),o.destroy(),o=bi(t,w),s=w,u()},v={update(w){var A,P,F,B,W,U;let S={...s,...w,launcher:{...(A=s==null?void 0:s.launcher)!=null?A:{},...(P=w==null?void 0:w.launcher)!=null?P:{},dock:{...(B=(F=s==null?void 0:s.launcher)==null?void 0:F.dock)!=null?B:{},...(U=(W=w==null?void 0:w.launcher)==null?void 0:W.dock)!=null?U:{}}}},H=un(s),M=un(S),L=ao(s),I=ao(S);if(H!==M||L!==I){m(S);return}s=S,o.updateConfig(s),a.update(w),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,S,H){if(S==="host")return o.host;if(S in w)return Reflect.get(w,S,H);let M=a[S];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var hm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Jy=new Set(["button","a","input","select","textarea","details","summary"]),Gy=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Sl=/\b(product|card|item|listing|result)\b/i,El=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Xy=3e3,Qy=100;function bm(e){let t=typeof e.className=="string"?e.className:"";if(Sl.test(t)||e.id&&Sl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Sl.test(r.value))return!0}return!1}function ym(e){var t;return El.test(((t=e.textContent)!=null?t:"").trim())}function xm(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Yy(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function um(e){let t=e.match(El);return t?t[0]:null}function mm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Zy(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var ex="commerce-card",tx="result-card";function gm(e){return!bm(e)||!ym(e)||!xm(e)&&!Yy(e)?0:5200}function fm(e){var r;return!bm(e)||ym(e)||!xm(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var vm=[{id:ex,scoreElement(e){return gm(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||El.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(gm(e)===0)return null;let{title:n,href:r}=mm(e),s=(p=(l=um(((d=e.textContent)!=null?d:"").trim()))!=null?l:um(t.text))!=null?p:"",o=Zy(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
+ `)}},{id:tx,scoreElement(e){return fm(e)},formatSummary(e,t){if(fm(e)===0)return null;let{title:n,href:r}=mm(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
+ `)}}];function nx(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function rx(e){var p,u,f,m,v,x,w,S,H,M,L,I,A;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(v=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(w=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?w:200,o=(H=(S=t.visibleOnly)!=null?S:e.visibleOnly)!=null?H:!0,a=(M=t.root)!=null?M:e.root,i=(L=t.mode)!=null?L:"structured",d=(I=t.maxCandidates)!=null?I:Math.max(500,n*10),l=(A=e.rules)!=null?A:vm;return i==="simple"&&e.rules&&e.rules.length>0?(nx(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function Tl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var ox=["data-testid","data-product","data-action","data-id","data-name","data-type"];function sx(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Jy.has(t)||n&&Gy.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function wm(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function ax(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Cm(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Tl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of ox){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${Tl(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>Tl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function ix(e){return e==="static"?Qy:Xy}function Am(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:Cm(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:sx(e),attributes:ax(e)}}function lx(e,t,n,r){let s=ix(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function cx(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function dx(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(hm.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!wm(l)){i=a.nextNode();continue}let u=Am(l,e.maxTextLength),f=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(w=>w==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:x}=lx(l,u,e.rules,n);s.push({el:l,domIndex:o,enriched:u,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;cx(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var f;let p;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,n);m&&(p=m)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function px(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(hm.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!wm(d)){o=s.nextNode();continue}let p=Am(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!u&&!f){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function ux(e={}){var r;let t=rx(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?px(t,n):dx(t,n):[]}var yi=100;function mx(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
110
110
  ${a.map(i=>`- ${i.split(`
111
111
  `).join(`
112
112
  `)}`).join(`
113
- `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,fi)}" (clickable)`);r.push(`Interactive elements:
113
+ `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,yi)}" (clickable)`);r.push(`Interactive elements:
114
114
  ${a.join(`
115
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,fi)}" (navigable)`);r.push(`Navigation links:
115
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,yi)}" (navigable)`);r.push(`Navigation links:
116
116
  ${a.join(`
117
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,fi)}" (input)`);r.push(`Form inputs:
117
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,yi)}" (input)`);r.push(`Form inputs:
118
118
  ${a.join(`
119
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,fi)}"`);r.push(`Content:
119
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,yi)}"`);r.push(`Content:
120
120
  ${a.join(`
121
121
  `)}`)}return r.join(`
122
122
 
123
- `)}var mm={name:"@runtypelabs/persona",version:"3.29.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./codegen":{types:"./dist/codegen.d.ts",import:"./dist/codegen.js",require:"./dist/codegen.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:launcher && pnpm run build:theme-ref && pnpm run build:codegen && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:codegen":"tsup src/codegen.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var os=mm.version;function rx(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function ox(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function sx(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Tr(e.colors.primary,.95),100:Tr(e.colors.primary,.9),200:Tr(e.colors.primary,.8),300:Tr(e.colors.primary,.7),400:Tr(e.colors.primary,.6),500:e.colors.primary,600:Tr(e.colors.primary,.8),700:Tr(e.colors.primary,.7),800:Tr(e.colors.primary,.6),900:Tr(e.colors.primary,.5),950:Tr(e.colors.primary,.45)}}),{...t,palette:n}}}}function ax(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function ix(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Tr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function lx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var cx={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},gm={components:{panel:{borderRadius:"0",shadow:"none"}}},fm={id:"shop",label:"Shopping Assistant",config:{theme:cx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:sr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},hm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:gm}},ym={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:gm}},bm={shop:fm,minimal:hm,fullscreen:ym};function dx(e){return bm[e]}var px=em;function Fr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function ux(e){if(e)return{getHeaders:Fr(e.getHeaders),onFeedback:Fr(e.onFeedback),onCopy:Fr(e.onCopy),requestMiddleware:Fr(e.requestMiddleware),actionHandlers:Fr(e.actionHandlers),actionParsers:Fr(e.actionParsers),postprocessMessage:Fr(e.postprocessMessage),contextProviders:Fr(e.contextProviders),streamParser:Fr(e.streamParser)}}var xm=`({ text, message }: any) => {
123
+ `)}var Sm={name:"@runtypelabs/persona",version:"3.30.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./codegen":{types:"./dist/codegen.d.ts",import:"./dist/codegen.js",require:"./dist/codegen.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./plugin-kit":{types:"./dist/plugin-kit.d.ts",import:"./dist/plugin-kit.js",require:"./dist/plugin-kit.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:launcher && pnpm run build:theme-ref && pnpm run build:codegen && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:plugin-kit && pnpm run build:animations","build:plugin-kit":"tsup src/plugin-kit.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:codegen":"tsup src/codegen.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var ds=Sm.version;function fx(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function hx(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function bx(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Pr(e.colors.primary,.95),100:Pr(e.colors.primary,.9),200:Pr(e.colors.primary,.8),300:Pr(e.colors.primary,.7),400:Pr(e.colors.primary,.6),500:e.colors.primary,600:Pr(e.colors.primary,.8),700:Pr(e.colors.primary,.7),800:Pr(e.colors.primary,.6),900:Pr(e.colors.primary,.5),950:Pr(e.colors.primary,.45)}}),{...t,palette:n}}}}function yx(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function xx(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Pr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function vx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var wx={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Tm={components:{panel:{borderRadius:"0",shadow:"none"}}},Em={id:"shop",label:"Shopping Assistant",config:{theme:wx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:pr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Mm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Tm}},km={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Tm}},Lm={shop:Em,minimal:Mm,fullscreen:km};function Cx(e){return Lm[e]}var Ax=pm;function _r(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function Sx(e){if(e)return{getHeaders:_r(e.getHeaders),onFeedback:_r(e.onFeedback),onCopy:_r(e.onCopy),requestMiddleware:_r(e.requestMiddleware),actionHandlers:_r(e.actionHandlers),actionParsers:_r(e.actionParsers),postprocessMessage:_r(e.postprocessMessage),contextProviders:_r(e.contextProviders),streamParser:_r(e.streamParser)}}var Pm=`({ text, message }: any) => {
124
124
  const jsonSource = (message as any).rawContent || text || message.content;
125
125
  if (!jsonSource || typeof jsonSource !== 'string') return null;
126
126
  let cleanJson = jsonSource
@@ -133,7 +133,7 @@ ${a.join(`
133
133
  if (parsed.action) return { type: parsed.action, payload: parsed };
134
134
  } catch (e) { return null; }
135
135
  return null;
136
- }`,vm=`function(ctx) {
136
+ }`,Im=`function(ctx) {
137
137
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
138
138
  if (!jsonSource || typeof jsonSource !== 'string') return null;
139
139
  var cleanJson = jsonSource
@@ -146,7 +146,7 @@ ${a.join(`
146
146
  if (parsed.action) return { type: parsed.action, payload: parsed };
147
147
  } catch (e) { return null; }
148
148
  return null;
149
- }`,wm=`(action: any, context: any) => {
149
+ }`,Wm=`(action: any, context: any) => {
150
150
  if (action.type !== 'nav_then_click') return;
151
151
  const payload = action.payload || action.raw || {};
152
152
  const url = payload?.page;
@@ -163,7 +163,7 @@ ${a.join(`
163
163
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
164
164
  window.location.href = targetUrl;
165
165
  return { handled: true, displayText: text };
166
- }`,Cm=`function(action, context) {
166
+ }`,Rm=`function(action, context) {
167
167
  if (action.type !== 'nav_then_click') return;
168
168
  var payload = action.payload || action.raw || {};
169
169
  var url = payload.page;
@@ -180,26 +180,26 @@ ${a.join(`
180
180
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
181
181
  window.location.href = targetUrl;
182
182
  return { handled: true, displayText: text };
183
- }`,mx=`(parsed: any) => {
183
+ }`,Tx=`(parsed: any) => {
184
184
  if (!parsed || typeof parsed !== 'object') return null;
185
185
  if (parsed.action === 'nav_then_click') return 'Navigating...';
186
186
  if (parsed.action === 'message') return parsed.text || '';
187
187
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
188
188
  return parsed.text || null;
189
- }`,gx=`function(parsed) {
189
+ }`,Ex=`function(parsed) {
190
190
  if (!parsed || typeof parsed !== 'object') return null;
191
191
  if (parsed.action === 'nav_then_click') return 'Navigating...';
192
192
  if (parsed.action === 'message') return parsed.text || '';
193
193
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
194
194
  return parsed.text || null;
195
- }`;function fx(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function hi(e){var t,n;return(n=(t=e.parserType)!=null?t:fx(e.streamParser))!=null?n:"plain"}function yi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function bi(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function xi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function vi(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Cl(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Am(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),Am(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function co(e,t,n,r){n&&(e.push(`${r}${t}: {`),Am(e,n,`${r} `),e.push(`${r}},`))}function Ys(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function hx(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:ux(n.hooks)}:void 0;return t==="esm"?yx(r,s):t==="script-installer"?vx(r,s):t==="script-advanced"?Cx(r,s):t==="react-component"?bx(r,s):t==="react-advanced"?xx(r,s):wx(r,s)}function yx(e,t){let n=t==null?void 0:t.hooks,r=hi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ys(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(o,"theme",e.theme," "),e.launcher&&co(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...yi(e," ")),o.push(...bi(e," ",n)),o.push(...xi(e," ")),o.push(...vi(e," ")),o.push(...Cl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
196
- `)}function bx(e,t){let n=t==null?void 0:t.hooks,r=hi(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Ys(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(o,"theme",e.theme," "),e.launcher&&co(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...yi(e," ")),o.push(...bi(e," ",n)),o.push(...xi(e," ")),o.push(...vi(e," ")),o.push(...Cl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
197
- `)}function xx(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ys(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(r,"theme",e.theme," "),e.launcher&&co(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...yi(e," ")),r.push(...bi(e," ",n)),r.push(...xi(e," ")),r.push(...vi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${mx}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${xm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${xm}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${wm}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${wm}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
198
- `)}function Sm(e){var s;let t=hi(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([p,m])=>{p!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(l[p]=m)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function vx(e,t){let n=Sm(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/install.global.js" data-config='${o}'></script>`}function wx(e,t){let n=t==null?void 0:t.hooks,r=hi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ys(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(o,"theme",e.theme," "),e.launcher&&co(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...yi(e," ")),o.push(...bi(e," ",n)),o.push(...xi(e," ")),o.push(...vi(e," ")),o.push(...Cl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
199
- `)}function Cx(e,t){let n=t==null?void 0:t.hooks,r=Sm(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
195
+ }`;function Mx(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function xi(e){var t,n;return(n=(t=e.parserType)!=null?t:Mx(e.streamParser))!=null?n:"plain"}function vi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function wi(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Ci(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Ai(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Ml(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Hm(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),Hm(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function go(e,t,n,r){n&&(e.push(`${r}${t}: {`),Hm(e,n,`${r} `),e.push(`${r}},`))}function sa(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function kx(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:Sx(n.hooks)}:void 0;return t==="esm"?Lx(r,s):t==="script-installer"?Wx(r,s):t==="script-advanced"?Hx(r,s):t==="react-component"?Px(r,s):t==="react-advanced"?Ix(r,s):Rx(r,s)}function Lx(e,t){let n=t==null?void 0:t.hooks,r=xi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${sa(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&go(o,"theme",e.theme," "),e.launcher&&go(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...vi(e," ")),o.push(...wi(e," ",n)),o.push(...Ci(e," ")),o.push(...Ai(e," ")),o.push(...Ml(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
196
+ `)}function Px(e,t){let n=t==null?void 0:t.hooks,r=xi(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${sa(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&go(o,"theme",e.theme," "),e.launcher&&go(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...vi(e," ")),o.push(...wi(e," ",n)),o.push(...Ci(e," ")),o.push(...Ai(e," ")),o.push(...Ml(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
197
+ `)}function Ix(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${sa(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&go(r,"theme",e.theme," "),e.launcher&&go(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...vi(e," ")),r.push(...wi(e," ",n)),r.push(...Ci(e," ")),r.push(...Ai(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Tx}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Pm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Pm}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Wm}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Wm}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
198
+ `)}function Bm(e){var s;let t=xi(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(l[p]=u)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function Wx(e,t){let n=Bm(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ds}/dist/install.global.js" data-config='${o}'></script>`}function Rx(e,t){let n=t==null?void 0:t.hooks,r=xi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ds}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ds}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${sa(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&go(o,"theme",e.theme," "),e.launcher&&go(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...vi(e," ")),o.push(...wi(e," ",n)),o.push(...Ci(e," ")),o.push(...Ai(e," ")),o.push(...Ml(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
199
+ `)}function Hx(e,t){let n=t==null?void 0:t.hooks,r=Bm(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
200
200
  `).map((a,i)=>i===0?a:" "+a).join(`
201
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${gx});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${vm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${vm}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Cm}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Cm}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Ys(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
202
- `)}var Tm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Em=.1,Mm=.15,km=1.5,Al=24,Lm=40,Ax=`
201
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ds}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${Ex});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Im}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Im}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Rm}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Rm}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${sa(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
202
+ `)}var Dm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Nm=.1,Om=.15,Fm=1.5,kl=24,$m=40,Bx=`
203
203
  /* \u2500\u2500 Root \u2500\u2500 */
204
204
  .persona-dc-root {
205
205
  display: flex;
@@ -350,7 +350,7 @@ ${a.join(`
350
350
  .persona-dc-stage {
351
351
  height: 550px;
352
352
  min-height: 400px;
353
- padding: ${Al}px;
353
+ padding: ${kl}px;
354
354
  overflow: auto;
355
355
  background: #f0f1f3;
356
356
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -440,5 +440,5 @@ ${a.join(`
440
440
  min-height: 300px;
441
441
  }
442
442
  }
443
- `;function Sx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Ax,document.head.appendChild(e)}function Tx(e,t){let n=e.clientWidth-Al*2-Lm,r=e.clientHeight-Al*2-Lm;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Ex(e,t,n,r,s){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function Mx(e,t){let{items:n,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Sx();let p=Math.max(0,Math.min(r,n.length-1)),m=s,g=o,u=null,v=1,x=!1,C=h("div","persona-dc-root"),T=h("div","persona-dc-toolbar"),H=h("div","persona-dc-toolbar-lead"),L=h("div","persona-dc-toolbar-trail"),P=qt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>we(-1)}),W=h("div");W.style.position="relative";let w=h("button","persona-dc-title-btn");w.type="button",w.setAttribute("aria-expanded","false"),w.setAttribute("aria-haspopup","listbox");let I=h("span","persona-dc-title-text"),O=h("span","persona-dc-title-chevron"),$=be("chevron-down",12,"currentColor",2);$&&O.appendChild($),w.append(I,O);let B=h("div","persona-dc-dropdown");B.setAttribute("role","listbox"),B.style.display="none";let j=!1;function z(){B.innerHTML="";for(let ue=0;ue<n.length;ue++){let ie=n[ue],re=h("button","persona-dc-dropdown-item");re.type="button",re.setAttribute("role","option"),re.setAttribute("aria-current",ue===p?"true":"false");let Qe=h("span");if(Qe.textContent=ie.title,re.appendChild(Qe),ie.description){let Ie=h("span","persona-dc-dropdown-desc");Ie.textContent=ie.description,re.appendChild(Ie)}re.addEventListener("click",()=>{We(),ze(ue)}),B.appendChild(re)}}function oe(){j=!j,B.style.display=j?"":"none",w.setAttribute("aria-expanded",j?"true":"false"),j&&z()}function We(){j&&(j=!1,B.style.display="none",w.setAttribute("aria-expanded","false"))}w.addEventListener("click",ue=>{ue.stopPropagation(),oe()});let je=()=>We();document.addEventListener("click",je),W.append(w,B);let Ne=qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>we(1)}),ge=h("span","persona-dc-counter");H.append(P,W,Ne,ge);let ye=null;i&&(ye=Xa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:ue=>{m=ue,V.dataset.device=m,u=null,Q()}}),L.appendChild(ye.element));let Le=null;if(a){let ue=h("div","persona-dc-zoom-controls"),ie=qt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ie=u!=null?u:v;u=Math.max(Mm,Ie-Em),Q()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{u=1,Q()});let re=qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ie=u!=null?u:v;u=Math.min(km,Ie+Em),Q()}}),Qe=qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{u=null,Q()}});ue.append(ie,Le,re,Qe),L.appendChild(ue)}if(d){let ue=h("div","persona-dc-separator");L.appendChild(ue);let ie=Xa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:re=>{g=re,V.dataset.colorScheme=g,ve()}});L.appendChild(ie.element)}let He=h("div","persona-dc-separator");L.appendChild(He);let ee=qt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});L.appendChild(ee),T.append(H,L);let Pe=h("div","persona-dc-stage"),V=h("div","persona-dc-iframe-wrapper");V.dataset.device=m,V.dataset.colorScheme=g;let le=h("iframe","persona-dc-iframe");le.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),le.setAttribute("loading","lazy"),le.title=n[p].title,V.appendChild(le),Pe.appendChild(V),C.append(T,Pe),e.appendChild(C);function ve(){var ue;try{let ie=(ue=le.contentDocument)==null?void 0:ue.body;if(!ie)return;g==="dark"?ie.classList.add("theme-dark"):ie.classList.remove("theme-dark")}catch{}}le.addEventListener("load",()=>ve());function fe(){let ue=n[p];I.textContent=ue.title,ge.textContent=`${p+1} / ${n.length}`,le.title=ue.title}function we(ue){let ie=((p+ue)%n.length+n.length)%n.length;ze(ie)}function ze(ue){ue<0||ue>=n.length||(p=ue,le.src=n[p].url,fe(),l==null||l(p,n[p]))}function Q(){var re;if(x)return;let ue=(re=Tm[m])!=null?re:Tm.desktop;v=Tx(Pe,ue);let ie=Math.max(Mm,Math.min(km,u!=null?u:v));Ex(V,le,ue,ie,m),Le&&(Le.textContent=`${Math.round(ie*100)}%`)}let te=new ResizeObserver(()=>Q());te.observe(Pe),fe(),le.src=n[p].url,requestAnimationFrame(()=>Q());function se(){x||(x=!0,te.disconnect(),document.removeEventListener("click",je),C.remove())}return{element:C,goTo:ze,next:()=>we(1),prev:()=>we(-1),getIndex:()=>p,setDevice(ue){m=ue,V.dataset.device=ue,ye==null||ye.setSelected(ue),u=null,Q()},setColorScheme(ue){g=ue,V.dataset.colorScheme=ue},setZoom(ue){u=ue,Q()},destroy:se}}export{yu as ASK_USER_QUESTION_TOOL_NAME,qo as AgentWidgetClient,Is as AgentWidgetSession,Ko as AttachmentManager,Up as DEFAULT_COMPONENTS,Pi as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,_p as DEFAULT_PALETTE,jp as DEFAULT_SEMANTIC,Ft as DEFAULT_WIDGET_CONFIG,bm as PRESETS,ym as PRESET_FULLSCREEN,hm as PRESET_MINIMAL,fm as PRESET_SHOP,Ch as THEME_ZONES,os as VERSION,Ca as WEBMCP_TOOL_PREFIX,Es as WebMcpBridge,rx as accessibilityPlugin,ox as animationsPlugin,Eo as applyThemeVariables,Go as attachHeaderToContainer,sx as brandPlugin,zs as buildComposer,ru as buildDefaultHeader,ro as buildHeader,qs as buildHeaderWithLayout,ou as buildMinimalHeader,ex as collectEnrichedPageContext,lo as componentRegistry,pi as createActionManager,ml as createAgentExperience,By as createAskUserQuestionBubble,Li as createBestAvailableVoiceProvider,oy as createBubbleWithLayout,dl as createCSATFeedback,$i as createComboButton,Cb as createComponentMiddleware,al as createComponentStreamParser,Sp as createDefaultSanitizer,Mx as createDemoCarousel,Rm as createDirectivePostprocessor,Mo as createDropdownMenu,Gm as createFlexibleJsonStreamParser,qt as createIconButton,sg as createImagePart,Ei as createJsonStreamParser,Ga as createLabelButton,sl as createLocalStorageAdapter,va as createMarkdownProcessor,_o as createMarkdownProcessorFromConfig,mu as createMessageActions,pl as createNPSFeedback,Si as createPlainTextParser,lx as createPlugin,Ti as createRegexJsonParser,Vs as createStandardBubble,Ia as createTextPart,Rs as createTheme,Hi as createThemeObserver,Xa as createToggleGroup,Xo as createTypingIndicator,Vo as createVoiceProvider,gi as createWidgetHostLayout,Mi as createXmlParser,px as default,ns as defaultActionHandlers,di as defaultJsonActionParser,cm as defaultParseRules,Na as detectColorScheme,Hm as directivePostprocessor,Js as ensureAskUserQuestionSheet,jo as escapeHtml,cl as extractComponentDirectiveFromMessage,ag as fileToImagePart,tx as formatEnrichedContext,zo as generateAssistantMessageId,hx as generateCodeSnippet,eg as generateMessageId,pm as generateStableSelector,Ls as generateUserMessageId,Hs as getActiveTheme,Kp as getColorScheme,ng as getDisplayText,su as getHeaderLayout,og as getImageParts,dx as getPreset,ll as hasComponentDirective,rg as hasImages,_i as headerLayouts,ix as highContrastPlugin,em as initAgentWidget,oo as isAskUserQuestionMessage,wb as isComponentDirectiveType,an as isDockedMountMode,Ba as isVoiceSupported,Aa as isWebMcpToolName,Wh as listRegisteredStreamAnimations,wp as markdownPostprocessor,Ii as mergeWithDefaults,tg as normalizeContent,so as parseAskUserQuestionPayload,ci as pluginRegistry,ax as reducedMotionPlugin,Ph as registerStreamAnimationPlugin,Lo as removeAskUserQuestionSheet,il as renderComponentDirective,uu as renderLoadingIndicatorWithFallback,be as renderLucideIcon,yr as resolveDockConfig,Ts as resolveSanitizer,Wi as resolveTokens,Mp as stripWebMcpPrefix,Ri as themeToCssVariables,Ih as unregisterStreamAnimationPlugin,ig as validateImageFile,qp as validateTheme};
443
+ `;function Dx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Bx,document.head.appendChild(e)}function Nx(e,t){let n=e.clientWidth-kl*2-$m,r=e.clientHeight-kl*2-$m;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Ox(e,t,n,r,s){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function Fx(e,t){let{items:n,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Dx();let p=Math.max(0,Math.min(r,n.length-1)),u=s,f=o,m=null,v=1,x=!1,w=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),H=h("div","persona-dc-toolbar-lead"),M=h("div","persona-dc-toolbar-trail"),L=Kt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ae(-1)}),I=h("div");I.style.position="relative";let A=h("button","persona-dc-title-btn");A.type="button",A.setAttribute("aria-expanded","false"),A.setAttribute("aria-haspopup","listbox");let P=h("span","persona-dc-title-text"),F=h("span","persona-dc-title-chevron"),B=Ce("chevron-down",12,"currentColor",2);B&&F.appendChild(B),A.append(P,F);let W=h("div","persona-dc-dropdown");W.setAttribute("role","listbox"),W.style.display="none";let U=!1;function V(){W.innerHTML="";for(let ye=0;ye<n.length;ye++){let ue=n[ye],re=h("button","persona-dc-dropdown-item");re.type="button",re.setAttribute("role","option"),re.setAttribute("aria-current",ye===p?"true":"false");let Ye=h("span");if(Ye.textContent=ue.title,re.appendChild(Ye),ue.description){let Ie=h("span","persona-dc-dropdown-desc");Ie.textContent=ue.description,re.appendChild(Ie)}re.addEventListener("click",()=>{We(),qe(ye)}),W.appendChild(re)}}function oe(){U=!U,W.style.display=U?"":"none",A.setAttribute("aria-expanded",U?"true":"false"),U&&V()}function We(){U&&(U=!1,W.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",ye=>{ye.stopPropagation(),oe()});let Je=()=>We();document.addEventListener("click",Je),I.append(A,W);let ve=Kt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ae(1)}),Re=h("span","persona-dc-counter");H.append(L,I,ve,Re);let he=null;i&&(he=Qa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ye=>{u=ye,z.dataset.device=u,m=null,Q()}}),M.appendChild(he.element));let He=null;if(a){let ye=h("div","persona-dc-zoom-controls"),ue=Kt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ie=m!=null?m:v;m=Math.max(Om,Ie-Nm),Q()}});He=h("span","persona-dc-zoom-level"),He.title="Reset to 100%",He.style.cursor="pointer",He.addEventListener("click",()=>{m=1,Q()});let re=Kt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ie=m!=null?m:v;m=Math.min(Fm,Ie+Nm),Q()}}),Ye=Kt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,Q()}});ye.append(ue,He,re,Ye),M.appendChild(ye)}if(d){let ye=h("div","persona-dc-separator");M.appendChild(ye);let ue=Qa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:re=>{f=re,z.dataset.colorScheme=f,ie()}});M.appendChild(ue.element)}let Le=h("div","persona-dc-separator");M.appendChild(Le);let K=Kt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});M.appendChild(K),S.append(H,M);let pe=h("div","persona-dc-stage"),z=h("div","persona-dc-iframe-wrapper");z.dataset.device=u,z.dataset.colorScheme=f;let ce=h("iframe","persona-dc-iframe");ce.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ce.setAttribute("loading","lazy"),ce.title=n[p].title,z.appendChild(ce),pe.appendChild(z),w.append(S,pe),e.appendChild(w);function ie(){var ye;try{let ue=(ye=ce.contentDocument)==null?void 0:ye.body;if(!ue)return;f==="dark"?ue.classList.add("theme-dark"):ue.classList.remove("theme-dark")}catch{}}ce.addEventListener("load",()=>ie());function se(){let ye=n[p];P.textContent=ye.title,Re.textContent=`${p+1} / ${n.length}`,ce.title=ye.title}function Ae(ye){let ue=((p+ye)%n.length+n.length)%n.length;qe(ue)}function qe(ye){ye<0||ye>=n.length||(p=ye,ce.src=n[p].url,se(),l==null||l(p,n[p]))}function Q(){var re;if(x)return;let ye=(re=Dm[u])!=null?re:Dm.desktop;v=Nx(pe,ye);let ue=Math.max(Om,Math.min(Fm,m!=null?m:v));Ox(z,ce,ye,ue,u),He&&(He.textContent=`${Math.round(ue*100)}%`)}let te=new ResizeObserver(()=>Q());te.observe(pe),se(),ce.src=n[p].url,requestAnimationFrame(()=>Q());function le(){x||(x=!0,te.disconnect(),document.removeEventListener("click",Je),w.remove())}return{element:w,goTo:qe,next:()=>Ae(1),prev:()=>Ae(-1),getIndex:()=>p,setDevice(ye){u=ye,z.dataset.device=ye,he==null||he.setSelected(ye),m=null,Q()},setColorScheme(ye){f=ye,z.dataset.colorScheme=ye},setZoom(ye){m=ye,Q()},destroy:le}}export{Su as ASK_USER_QUESTION_TOOL_NAME,Xo as AgentWidgetClient,Os as AgentWidgetSession,Zo as AttachmentManager,Xp as DEFAULT_COMPONENTS,Di as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,pr as DEFAULT_FLOATING_LAUNCHER_WIDTH,Jp as DEFAULT_PALETTE,Gp as DEFAULT_SEMANTIC,_t as DEFAULT_WIDGET_CONFIG,Lm as PRESETS,km as PRESET_FULLSCREEN,Mm as PRESET_MINIMAL,Em as PRESET_SHOP,Rh as THEME_ZONES,ds as VERSION,ro as WEBMCP_TOOL_PREFIX,Ws as WebMcpBridge,fx as accessibilityPlugin,hx as animationsPlugin,Io as applyThemeVariables,ts as attachHeaderToContainer,bx as brandPlugin,Ys as buildComposer,du as buildDefaultHeader,io as buildHeader,Qs as buildHeaderWithLayout,pu as buildMinimalHeader,ux as collectEnrichedPageContext,mo as componentRegistry,gi as createActionManager,yl as createAgentExperience,Vb as createAskUserQuestionBubble,Bi as createBestAvailableVoiceProvider,fb as createBubbleWithLayout,fl as createCSATFeedback,Vi as createComboButton,Hy as createComponentMiddleware,pl as createComponentStreamParser,Pp as createDefaultSanitizer,Fx as createDemoCarousel,qm as createDirectivePostprocessor,Wo as createDropdownMenu,ag as createFlexibleJsonStreamParser,Kt as createIconButton,hg as createImagePart,Wi as createJsonStreamParser,Xa as createLabelButton,dl as createLocalStorageAdapter,Aa as createMarkdownProcessor,Ko as createMarkdownProcessorFromConfig,vu as createMessageActions,hl as createNPSFeedback,Pi as createPlainTextParser,vx as createPlugin,Ii as createRegexJsonParser,Zs as createStandardBubble,Wa as createTextPart,$s as createTheme,$i as createThemeObserver,Qa as createToggleGroup,ns as createTypingIndicator,Yo as createVoiceProvider,bi as createWidgetHostLayout,Ri as createXmlParser,Ax as default,ls as defaultActionHandlers,mi as defaultJsonActionParser,vm as defaultParseRules,Oa as detectColorScheme,zm as directivePostprocessor,ta as ensureAskUserQuestionSheet,Jo as escapeHtml,gl as extractComponentDirectiveFromMessage,bg as fileToImagePart,mx as formatEnrichedContext,Qo as generateAssistantMessageId,kx as generateCodeSnippet,pg as generateMessageId,Cm as generateStableSelector,Bs as generateUserMessageId,_s as getActiveTheme,eu as getColorScheme,mg as getDisplayText,uu as getHeaderLayout,fg as getImageParts,Cx as getPreset,ml as hasComponentDirective,gg as hasImages,Ki as headerLayouts,xx as highContrastPlugin,pm as initAgentWidget,lo as isAskUserQuestionMessage,Ry as isComponentDirectiveType,un as isDockedMountMode,Da as isVoiceSupported,ko as isWebMcpToolName,Uh as listRegisteredStreamAnimations,Mp as markdownPostprocessor,Ni as mergeWithDefaults,ug as normalizeContent,co as parseAskUserQuestionPayload,ui as pluginRegistry,yx as reducedMotionPlugin,_h as registerStreamAnimationPlugin,Ho as removeAskUserQuestionSheet,ul as renderComponentDirective,xu as renderLoadingIndicatorWithFallback,Ce as renderLucideIcon,Ar as resolveDockConfig,Is as resolveSanitizer,Oi as resolveTokens,ki as stripWebMcpPrefix,Fi as themeToCssVariables,jh as unregisterStreamAnimationPlugin,yg as validateImageFile,Qp as validateTheme};
444
444
  //# sourceMappingURL=index.js.map