@runtypelabs/persona 3.29.1 → 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 (53) hide show
  1. package/README.md +55 -0
  2. package/dist/codegen.cjs +6 -6
  3. package/dist/codegen.js +4 -4
  4. package/dist/index.cjs +47 -47
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +112 -7
  7. package/dist/index.d.ts +112 -7
  8. package/dist/index.global.js +59 -59
  9. package/dist/index.global.js.map +1 -1
  10. package/dist/index.js +47 -47
  11. package/dist/index.js.map +1 -1
  12. package/dist/launcher.global.js +2 -2
  13. package/dist/launcher.global.js.map +1 -1
  14. package/dist/plugin-kit.cjs +1 -0
  15. package/dist/plugin-kit.d.cts +98 -0
  16. package/dist/plugin-kit.d.ts +98 -0
  17. package/dist/plugin-kit.js +1 -0
  18. package/dist/smart-dom-reader.d.cts +107 -4
  19. package/dist/smart-dom-reader.d.ts +107 -4
  20. package/dist/theme-editor.cjs +38 -38
  21. package/dist/theme-editor.d.cts +111 -6
  22. package/dist/theme-editor.d.ts +111 -6
  23. package/dist/theme-editor.js +38 -38
  24. package/dist/theme-reference.cjs +1 -1
  25. package/dist/theme-reference.d.cts +2 -0
  26. package/dist/theme-reference.d.ts +2 -0
  27. package/dist/theme-reference.js +1 -1
  28. package/package.json +8 -2
  29. package/src/components/approval-bubble.test.ts +268 -0
  30. package/src/components/approval-bubble.ts +170 -20
  31. package/src/components/launcher.ts +6 -3
  32. package/src/components/tool-bubble.test.ts +39 -0
  33. package/src/components/tool-bubble.ts +4 -0
  34. package/src/index-core.ts +1 -0
  35. package/src/plugin-kit.test.ts +230 -0
  36. package/src/plugin-kit.ts +294 -0
  37. package/src/plugins/types.ts +49 -2
  38. package/src/session.test.ts +99 -0
  39. package/src/session.ts +14 -3
  40. package/src/theme-editor/preview-utils.test.ts +10 -0
  41. package/src/theme-editor/preview-utils.ts +29 -1
  42. package/src/theme-editor/sections.test.ts +17 -0
  43. package/src/theme-editor/sections.ts +31 -0
  44. package/src/theme-reference.ts +1 -1
  45. package/src/types/theme.ts +2 -0
  46. package/src/types.ts +59 -2
  47. package/src/ui.approval-plugin.test.ts +204 -0
  48. package/src/ui.ts +149 -16
  49. package/src/utils/theme.test.ts +6 -2
  50. package/src/utils/theme.ts +0 -8
  51. package/src/utils/tokens.ts +6 -1
  52. package/src/webmcp-bridge.test.ts +66 -0
  53. package/src/webmcp-bridge.ts +49 -0
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
- import{Marked as Wm}from"marked";var Rm=e=>{if(e)return e},wa=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new Wm({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=Rm(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},jo=e=>e?wa({markedOptions:e.options,renderer:e.renderer}):wa(),Hm=wa(),wp=e=>Hm(e),Uo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ap=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Cp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Sp=(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=Cp(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=Cp(t.length);return t.push({token:o,type:s}),o}),n},Bm=e=>{let t=jo(e);return n=>{let r=[],s=Sp(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="${Ap(i)}"></div>`;o=o.replace(d,p)}),o}},Dm=e=>{let t=[],n=Sp(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="${Ap(o)}"></div>`;r=r.replace(a,d)}),r};import Nm from"dompurify";var Fm={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"]},Om=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Tp=()=>{let e=Nm(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:")&&!Om.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Fm)},Es=e=>e===!1?null:typeof e=="function"?e:Tp();var Sa="webmcp:",Aa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Mp(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}:${$m(t.join(""))}`}function Ep(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 $m(e){let t=Ep(e,0).toString(36),n=Ep(e,2654435761).toString(36);return`${t}.${n}`}var Ms=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 Aa.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=jm(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=kp(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,Vm(n),{signal:l.signal});return Um(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){Aa.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,Aa.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:qm;try{return await n(t)}catch(s){return Aa.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=>_m(t,r))}},kp=e=>e.startsWith(Sa)?e.slice(Sa.length):e,So=e=>e.startsWith(Sa),_m=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},jm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Um=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:Km(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),qm=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=zm(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)},zm=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)}},Vm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Km=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Lp,STR as Pp,OBJ as Ip}from"partial-json";var Ta=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),qo=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)}},Jm=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`},Wp=e=>e.status==="complete"?Jm(e):e.status==="pending"?"Waiting":"",Gm=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 Rp=e=>e.status==="complete"?Gm(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`},Ls=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)},Si=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Ls(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&&ks(r,n.slice(o,a.index),[]),a[1]!==void 0?ks(r,a[1],["bold"]):a[2]!==void 0?ks(r,a[2],["italic"]):a[3]!==void 0&&ks(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&ks(r,n.slice(o),[]),r},ks=(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})},Xm=()=>{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()=>{}}},To=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ti=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ei=()=>{var t;let e=Xm();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)}},Mi=()=>{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=Lp(n,Pp|Ip);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:()=>{}}},Qm=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=Lp(o,Pp|Ip),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},ki=()=>{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 Ym="https://api.runtype.com/v1/dispatch",Pa="https://api.runtype.com";function Zm(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 Li=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 eg(e){switch(e){case"json":return Mi;case"regex-json":return Ei;case"xml":return ki;default:return Ti}}var Hp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function tg(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=Hp(n);if(!Hp(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=To(e);return To(t)!==null&&a===null?t:e}var zo=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:Ym,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:eg(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 Ms(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 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(Li).map(P=>{var W,A,I;return{id:P.id,role:P.role,content:(I=(A=(W=P.contentParts)!=null?W:P.llmContent)!=null?A: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?Mp(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,C=u&&x&&this.lastSentClientToolsFingerprint===v,T=!1,H=null,k;for(let P=0;;P++){let A={...m,...u&&(T||!C)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),signal:r.signal}),k.status===409&&P===0&&u){let I=await k.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(!k.ok){let P=H!=null?H:await k.json().catch(()=>({error:"Chat request failed"}));if(k.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(k.status===429){let A=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:A}),A}let W=new Error(P.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!k.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(k.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(Li).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(Li).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,qe;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=F=>{let Ae=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,De=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ne=F.tools?F.tools.map(je=>({...je,chunks:je.chunks?[...je.chunks]:void 0})):void 0;return{...F,reasoning:Ae,toolCall:De,tools:Ne}},m=F=>{if(F.role!=="assistant"||F.variant)return!0;let Ae=Array.isArray(F.contentParts)&&F.contentParts.length>0,De=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||Ae||De||!!F.stopReason},g=F=>{m(F)&&n({type:"message",message:p(F)})},u=null,v=null,x={current:null},C={current:null},T=!1,H=new Map,k=new Map,P=new Map,W=new Map,A={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},O=(F,Ae,De="")=>`${F}::${Ae}::${De}`,D=(F,Ae)=>`${F}::${Ae}::`,R=(F,Ae,De,Ne)=>{let je=O(F,Ae,De),dt=P.get(je);if(dt)return dt;let rt=De?`-${De}`:"",At={id:`nested-${F}-${Ae}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ne,parentToolId:F,parentStepId:Ae}};return P.set(je,At),g(At),At},_=F=>{if(F==null)return null;try{return String(F)}catch{return null}},z=F=>{var Ae,De,Ne,je,dt;return _((dt=(je=(Ne=(De=(Ae=F.stepId)!=null?Ae:F.step_id)!=null?De:F.step)!=null?Ne:F.parentId)!=null?je:F.flowStepId)!=null?dt:F.flow_step_id)},oe=F=>{var Ae,De,Ne,je,dt,rt,At;return _((At=(rt=(dt=(je=(Ne=(De=(Ae=F.callId)!=null?Ae:F.call_id)!=null?De:F.requestId)!=null?Ne:F.request_id)!=null?je:F.toolCallId)!=null?dt:F.tool_call_id)!=null?rt:F.stepId)!=null?At:F.step_id)},Re=r,Ue=!1,Fe=()=>{if(u)return u;let F;return!Ue&&Re?(F=Re,Ue=!0):Re&&C.current?F=`${Re}_${C.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(u),u},ge=(F,Ae)=>{A.lastId=Ae,F&&A.byStep.set(F,Ae)},ye=(F,Ae)=>{var dt;let De=(dt=F.reasoningId)!=null?dt:F.id,Ne=z(F);if(De){let rt=String(De);return ge(Ne,rt),rt}if(Ne){let rt=A.byStep.get(Ne);if(rt)return A.lastId=rt,rt}if(A.lastId&&!Ae)return A.lastId;if(!Ae)return null;let je=`reason-${l()}`;return ge(Ne,je),je},Le=F=>{let Ae=H.get(F);if(Ae)return Ae;let De={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return H.set(F,De),g(De),De},Be=(F,Ae)=>{I.lastId=Ae,F&&I.byCall.set(F,Ae)},ee=new Set,Pe=new Map,V=new Set,le=new Map,ve=F=>{if(!F)return!1;let Ae=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ae==="emit_artifact_markdown"||Ae==="emit_artifact_component"},fe=(F,Ae)=>{var dt;let De=(dt=F.toolId)!=null?dt:F.id,Ne=oe(F);if(De){let rt=String(De);return Be(Ne,rt),rt}if(Ne){let rt=I.byCall.get(Ne);if(rt)return I.lastId=rt,rt}if(I.lastId&&!Ae)return I.lastId;if(!Ae)return null;let je=`tool-${l()}`;return Be(Ne,je),je},Ce=F=>{let Ae=k.get(F);if(Ae)return Ae;let De={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return k.set(F,De),g(De),De},Ve=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let Ae=Number(F);if(!Number.isNaN(Ae)&&Number.isFinite(Ae))return Ae;let De=Date.parse(F);if(!Number.isNaN(De))return De}return Date.now()},X=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},te=new Map,se=new Map,ue=new Map,ie=new Map,re=null,Qe=(F,Ae,De)=>{var At;let Ne=ue.get(F);Ne||(Ne=[],ue.set(F,Ne));let je=0,dt=Ne.length;for(;je<dt;){let _t=je+dt>>>1;Ne[_t].seq<Ae?je=_t+1:dt=_t}((At=Ne[je])==null?void 0:At.seq)===Ae?Ne[je]={seq:Ae,text:De}:Ne.splice(je,0,{seq:Ae,text:De});let rt="";for(let _t=0;_t<Ne.length;_t++)rt+=Ne[_t].text;return rt},Ie=(F,Ae)=>{let De=X(Ae),Ne=se.get(F.id),je=tg(Ne,De);F.rawContent=je;let dt=te.get(F.id),rt=Ye=>{var ne;let Dt=(ne=F.content)!=null?ne:"";Ye.trim()!==""&&(Dt.trim().length===0||Ye.startsWith(Dt)||Ye.trimStart().startsWith(Dt.trim()))&&(F.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(F.id),se.delete(F.id),F.streaming=!1,g(F)};if(!dt){rt(De),At();return}let _t=To(je);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:De},$t;try{$t=dt.processChunk(je)}catch{rt(De),At();return}if($t instanceof Promise){$t.then(Ye=>{rt(q(Ye)),At()}).catch(()=>{rt(De),At()});return}rt(q($t)),At()},ce=[],J=!1,_e,Et=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,_e()}))},de=new La((F,Ae)=>{ce.push({payloadType:F,payload:Ae}),Et()}),ae=null,Mn=new Map,Ot=(ln=this.config.iterationDisplay)!=null?ln:"separate";for(_e=()=>{var F,Ae,De,Ne,je,dt,rt,At,_t,q,$t,Ye,Dt,ne,me,vt,jt,Zt,hn,St,Ct,ft,yt,zt,tt,Bn,Qn,yn,Dn,ut,xr,Nn,po,kn,Wo,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,Cr,as,pr,ur,mr,Pr,uo,ta,is,na,Ro,mt,ls,nr,Ln,ra,oa,Ho,Ir,sa,mo,cs,Wr,ds,zr,Vr,aa,ia,wi,go,Kr,la,ps,Jr,ca,us,Gr,ms,da,Rr,pa,Xr,Rt,Bo,Do,gs,wr,ua,fs,hs,ma,No,Fo,fo,ga,fa,ys,bs,xs,vs,vn,Vn,Hr,ot,Cs,ho,gr,ha;for(let Qr=0;Qr<ce.length;Qr++){let Ke=ce[Qr].payloadType,w=ce[Qr].payload;if(Ke==="reason_start"){let j=(F=ye(w,!0))!=null?F:`reason-${l()}`,L=Le(j);L.reasoning=(Ae=L.reasoning)!=null?Ae:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(Ne=L.reasoning.startedAt)!=null?Ne:Ve((De=w.startedAt)!=null?De:w.timestamp),L.reasoning.completedAt=void 0,L.reasoning.durationMs=void 0,L.streaming=!0,L.reasoning.status="streaming",g(L)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let j=(dt=(je=ye(w,!1))!=null?je:ye(w,!0))!=null?dt:`reason-${l()}`,L=Le(j);L.reasoning=(rt=L.reasoning)!=null?rt:{id:j,status:"streaming",chunks:[]},L.reasoning.startedAt=(_t=L.reasoning.startedAt)!=null?_t:Ve((At=w.startedAt)!=null?At:w.timestamp);let Q=(Ye=($t=(q=w.reasoningText)!=null?q:w.text)!=null?$t:w.delta)!=null?Ye:"";if(Q&&w.hidden!==!0){let Z=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Z!==void 0){let K=Qe(j,Z,String(Q));L.reasoning.chunks=[K]}else L.reasoning.chunks.push(String(Q))}if(L.reasoning.status=w.done?"complete":"streaming",w.done){L.reasoning.completedAt=Ve((Dt=w.completedAt)!=null?Dt:w.timestamp);let Z=(ne=L.reasoning.startedAt)!=null?ne:Date.now();L.reasoning.durationMs=Math.max(0,((me=L.reasoning.completedAt)!=null?me:Date.now())-Z)}L.streaming=L.reasoning.status!=="complete",g(L)}else if(Ke==="reason_complete"){let j=(jt=(vt=ye(w,!1))!=null?vt:ye(w,!0))!=null?jt:`reason-${l()}`,L=H.get(j);if(L!=null&&L.reasoning){L.reasoning.status="complete",L.reasoning.completedAt=Ve((Zt=w.completedAt)!=null?Zt:w.timestamp);let Z=(hn=L.reasoning.startedAt)!=null?hn:Date.now();L.reasoning.durationMs=Math.max(0,((St=L.reasoning.completedAt)!=null?St:Date.now())-Z),L.streaming=!1,g(L)}let Q=z(w);Q&&A.byStep.delete(Q)}else if(Ke==="tool_start"){let j=(Ct=fe(w,!0))!=null?Ct:`tool-${l()}`,L=(ft=w.toolName)!=null?ft:w.name;if(ve(L)){ee.add(j);continue}let Q=Ce(j),Z=(yt=Q.toolCall)!=null?yt:{id:j,status:"pending"};Z.name=L!=null?L:Z.name,Z.status="running",w.args!==void 0?Z.args=w.args:w.parameters!==void 0&&(Z.args=w.parameters),Z.startedAt=(tt=Z.startedAt)!=null?tt:Ve((zt=w.startedAt)!=null?zt:w.timestamp),Z.completedAt=void 0,Z.durationMs=void 0,Q.toolCall=Z,Q.streaming=!0;let K=w.agentContext;(K||w.executionId)&&(Q.agentMetadata={executionId:(Bn=K==null?void 0:K.executionId)!=null?Bn:w.executionId,iteration:(Qn=K==null?void 0:K.iteration)!=null?Qn:w.iteration}),g(Q)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let j=(Dn=(yn=fe(w,!1))!=null?yn:fe(w,!0))!=null?Dn:`tool-${l()}`;if(ee.has(j))continue;let L=Ce(j),Q=(ut=L.toolCall)!=null?ut:{id:j,status:"running"};Q.startedAt=(Nn=Q.startedAt)!=null?Nn:Ve((xr=w.startedAt)!=null?xr:w.timestamp);let Z=(Wo=(kn=(po=w.text)!=null?po:w.delta)!=null?kn:w.message)!=null?Wo:"";Z&&(Q.chunks=(Or=Q.chunks)!=null?Or:[],Q.chunks.push(String(Z))),Q.status="running",L.toolCall=Q,L.streaming=!0;let K=w.agentContext;(K||w.executionId)&&(L.agentMetadata=(Fn=L.agentMetadata)!=null?Fn:{executionId:(Er=K==null?void 0:K.executionId)!=null?Er:w.executionId,iteration:(bt=K==null?void 0:K.iteration)!=null?bt:w.iteration}),g(L)}else if(Ke==="tool_complete"){let j=(bn=(On=fe(w,!1))!=null?On:fe(w,!0))!=null?bn:`tool-${l()}`;if(ee.has(j)){ee.delete(j);continue}let L=Ce(j),Q=(Lt=L.toolCall)!=null?Lt:{id:j,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=Ve((Yn=w.completedAt)!=null?Yn:w.timestamp);let Z=(Zn=w.duration)!=null?Zn:w.executionTime;if(typeof Z=="number")Q.durationMs=Z;else{let $e=($n=Q.startedAt)!=null?$n:Date.now();Q.durationMs=Math.max(0,(($r=Q.completedAt)!=null?$r:Date.now())-$e)}L.toolCall=Q,L.streaming=!1;let K=w.agentContext;(K||w.executionId)&&(L.agentMetadata=(_n=L.agentMetadata)!=null?_n:{executionId:(Mr=K==null?void 0:K.executionId)!=null?Mr:w.executionId,iteration:(_r=K==null?void 0:K.iteration)!=null?_r:w.iteration}),g(L);let We=oe(w);We&&I.byCall.delete(We)}else if(Ke==="step_await"&&w.awaitReason==="local_tool_required"&&w.toolName){let j=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,L=(Wt=j!=null?j:w.toolId)!=null?Wt:`local-${l()}`,Q=Ce(L),Z=w.toolName,K=So(Z),We=(xn=Q.toolCall)!=null?xn:{id:L,status:"pending"};We.name=Z,We.args=w.parameters,We.status=K?"running":"complete",We.chunks=(er=We.chunks)!=null?er:[],We.startedAt=(kr=We.startedAt)!=null?kr:Ve((jr=w.startedAt)!=null?jr:w.timestamp),K?(We.completedAt=void 0,We.duration=void 0,We.durationMs=void 0):We.completedAt=(Ur=We.completedAt)!=null?Ur:We.startedAt,Q.toolCall=We,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(jn=w.executionId)!=null?jn:(vr=Q.agentMetadata)==null?void 0:vr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Q)}else if(Ke==="text_start"){if((lr=w.toolContext)!=null&&lr.toolId)continue;let j=w.partId;if(j!==void 0&&C.current!==null&&j!==C.current){let L=u;L&&(L.streaming=!1,g(L),re=L,u=null,T=!0)}j!==void 0&&(C.current=j)}else if(Ke==="text_end"){if((gt=w.toolContext)!=null&&gt.toolId)continue;let j=u;j&&(j.streaming=!1,g(j),re=j,u=null,T=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let j=w.stepType,L=w.executionType;if(j==="tool"||L==="context")continue;let Q=w.toolContext;if(Q!=null&&Q.toolId){let $e=String((Gt=(Jt=w.id)!=null?Jt:Q.stepId)!=null?Gt:`step-${l()}`),et=w.partId!==void 0&&w.partId!==null?String(w.partId):"",Ee=`${Q.toolId}::${$e}`,Ge=W.get(Ee);if(et!==""&&Ge!==void 0&&Ge!==""&&Ge!==et){let wt=P.get(O(Q.toolId,$e,Ge));wt&&wt.streaming!==!1&&(wt.streaming=!1,g(wt))}et!==""&&W.set(Ee,et);let Pt=R(Q.toolId,$e,et,Q.executionId),nn=(cr=(tr=(qr=(Un=w.text)!=null?Un:w.delta)!=null?qr:w.content)!=null?tr:w.chunk)!=null?cr:"";nn&&(Pt.content+=String(nn),Pt.streaming=!0,g(Pt)),w.isComplete&&(Pt.streaming=!1,g(Pt));continue}let Z=w.partId;if(Z!==void 0&&C.current!==null&&Z!==C.current){let $e=u;$e&&($e.streaming=!1,g($e),re=$e,u=null,T=!0)}Z!==void 0&&(C.current=Z);let K=Z!==void 0&&(qn=ie.get(Z))!=null?qn:Fe();Z!==void 0&&(K.partId||(K.partId=Z),ie.set(Z,K));let We=(Lr=(dr=(zn=(S=w.text)!=null?S:w.delta)!=null?zn:w.content)!=null?dr:w.chunk)!=null?Lr:"";if(We){let $e=typeof w.seq=="number"?w.seq:void 0,et=Z!=null?Z:K.id,Ee=$e!==void 0?Qe(et,$e,String(We)):((Cr=se.get(K.id))!=null?Cr:"")+We;K.rawContent=Ee,te.has(K.id)||te.set(K.id,this.createStreamParser());let Ge=te.get(K.id),Pt=Ee.trim().startsWith("{")||Ee.trim().startsWith("[");if(Pt&&se.set(K.id,Ee),Ge.__isPlainTextParser===!0){K.content=$e!==void 0?Ee:K.content+We,se.delete(K.id),te.delete(K.id),K.rawContent=void 0,g(K);continue}let wt=Ge.processChunk(Ee);if(wt instanceof Promise)wt.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()!=="")K.content=rn,g(K);else if(!Pt&&!Ee.trim().startsWith("<")){let Cn=u,Xt=Cn&&Cn.id===K.id?Cn:K;Xt.id===K.id&&(Xt.content=$e!==void 0?Ee:Xt.content+We,se.delete(Xt.id),te.delete(Xt.id),Xt.rawContent=void 0,g(Xt))}}).catch(()=>{K.content=$e!==void 0?Ee:K.content+We,se.delete(K.id),te.delete(K.id),K.rawContent=void 0,g(K)});else{let Mt=typeof wt=="string"?wt:(as=wt==null?void 0:wt.text)!=null?as:null;Mt!==null&&Mt.trim()!==""?(K.content=Mt,g(K)):!Pt&&!Ee.trim().startsWith("<")&&(K.content=$e!==void 0?Ee:K.content+We,se.delete(K.id),te.delete(K.id),K.rawContent=void 0,g(K))}}if(w.isComplete){let $e=(ur=(pr=w.result)==null?void 0:pr.response)!=null?ur:K.content;if($e){let et=se.get(K.id),Ee=et!=null?et:X($e);K.rawContent=Ee;let Ge=te.get(K.id),Pt=null,nn=!1;if(Ge&&(Pt=Ge.getExtractedText(),Pt===null&&(Pt=To(Ee)),Pt===null)){let wt=Ge.processChunk(Ee);wt instanceof Promise?(nn=!0,wt.then(Mt=>{var pn;let rn=typeof Mt=="string"?Mt:(pn=Mt==null?void 0:Mt.text)!=null?pn:null;if(rn!==null){let Cn=u;Cn&&Cn.id===K.id&&(Cn.content=rn,Cn.streaming=!1,te.delete(Cn.id),se.delete(Cn.id),g(Cn))}})):Pt=typeof wt=="string"?wt:(mr=wt==null?void 0:wt.text)!=null?mr:null}if(!nn){Pt!==null&&Pt.trim()!==""?K.content=Pt:se.has(K.id)||(K.content=X($e));let wt=te.get(K.id);if(wt){let Mt=(Pr=wt.close)==null?void 0:Pr.call(wt);Mt instanceof Promise&&Mt.catch(()=>{}),te.delete(K.id)}se.delete(K.id),K.streaming=!1,g(K)}}}}else if(Ke==="step_complete"){let j=w.stepType,L=w.executionType;if(j==="tool"||L==="context")continue;let Q=w.toolContext;if(Q!=null&&Q.toolId){let $e=String((ta=(uo=w.id)!=null?uo:Q.stepId)!=null?ta:"");if($e){let et=D(Q.toolId,$e);for(let[Ee,Ge]of P)Ee.startsWith(et)&&Ge.streaming!==!1&&(Ge.streaming=!1,g(Ge));W.delete(`${Q.toolId}::${$e}`)}continue}let Z=w.stopReason;if(T){if(u!==null){let Ee=u;Z&&(Ee.stopReason=Z),te.delete(Ee.id),se.delete(Ee.id),Ee.streaming!==!1&&(Ee.streaming=!1,g(Ee))}let $e=(is=w.result)==null?void 0:is.response,et=re;et&&(Z&&(et.stopReason=Z),$e!=null?Ie(et,$e):(te.delete(et.id),se.delete(et.id))),re=null;continue}let K=(na=w.result)==null?void 0:na.response,We=Fe();if(Z&&(We.stopReason=Z),K!=null){let $e=te.get(We.id),et=!1,Ee=!1;if($e){let Ge=$e.getExtractedText(),Pt=se.get(We.id),nn=Pt!=null?Pt:X(K);if(We.rawContent=nn,Ge!==null&&Ge.trim()!=="")We.content=Ge,et=!0;else{let wt=To(nn);if(wt!==null)We.content=wt,et=!0;else{let Mt=$e.processChunk(nn);if(Mt instanceof Promise)Ee=!0,Mt.then(rn=>{var Cn;let pn=typeof rn=="string"?rn:(Cn=rn==null?void 0:rn.text)!=null?Cn:null;if(pn!==null&&pn.trim()!==""){let Xt=u;Xt&&Xt.id===We.id&&(Xt.content=pn,Xt.streaming=!1,te.delete(Xt.id),se.delete(Xt.id),g(Xt))}else{let Xt=$e.getExtractedText(),rr=u;rr&&rr.id===We.id&&(Xt!==null&&Xt.trim()!==""?rr.content=Xt:se.has(rr.id)||(rr.content=X(K)),rr.streaming=!1,te.delete(rr.id),se.delete(rr.id),g(rr))}});else{let rn=typeof Mt=="string"?Mt:(Ro=Mt==null?void 0:Mt.text)!=null?Ro:null;if(rn!==null&&rn.trim()!=="")We.content=rn,et=!0;else{let pn=$e.getExtractedText();pn!==null&&pn.trim()!==""&&(We.content=pn,et=!0)}}}}}if(!Ee){if(!We.rawContent){let Ge=se.get(We.id);We.rawContent=Ge!=null?Ge:X(K)}if(!et&&!se.has(We.id)&&(We.content=X(K)),$e){let Ge=(mt=$e.close)==null?void 0:mt.call($e);Ge instanceof Promise&&Ge.catch(()=>{})}te.delete(We.id),se.delete(We.id),We.streaming=!1,g(We)}}else te.delete(We.id),se.delete(We.id),We.streaming=!1,g(We)}else if(Ke==="flow_complete"){let j=(ls=w.result)==null?void 0:ls.response;if(T){if(u!==null){let L=u;te.delete(L.id),se.delete(L.id),L.streaming!==!1&&(L.streaming=!1,g(L))}}else if(j!=null){let L=Fe(),Q=se.get(L.id),Z=Q!=null?Q:X(j);L.rawContent=Z;let K=X(j),We=te.get(L.id);if(We){let Ee=To(Z);if(Ee!==null)K=Ee;else{let Ge=We.processChunk(Z);Ge instanceof Promise&&Ge.then(nn=>{var Mt;let wt=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;wt!==null&&(L.content=wt,L.streaming=!1,g(L))});let Pt=We.getExtractedText();Pt!==null&&(K=Pt)}}te.delete(L.id),se.delete(L.id);let $e=K!==L.content,et=L.streaming!==!1;$e&&(L.content=K),L.streaming=!1,($e||et)&&g(L)}else if(u!==null){let L=u;te.delete(L.id),se.delete(L.id),L.streaming!==!1&&(L.streaming=!1,g(L))}n({type:"status",status:"idle"})}else if(Ke==="agent_start")ae={executionId:w.executionId,agentId:(nr=w.agentId)!=null?nr:"virtual",agentName:(Ln=w.agentName)!=null?Ln:"",status:"running",currentIteration:0,maxTurns:(ra=w.maxTurns)!=null?ra:1,startedAt:Ve(w.startedAt)};else if(Ke==="agent_iteration_start"){if(ae&&(ae.currentIteration=w.iteration),Ot==="separate"&&w.iteration>1){let j=u;j&&(j.streaming=!1,g(j),Mn.set(w.iteration-1,j),u=null)}}else if(Ke==="agent_turn_start")v=null;else if(Ke==="agent_turn_delta"){if(w.contentType==="text"){let j=Fe();j.content+=(oa=w.delta)!=null?oa:"",j.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId,agentName:ae==null?void 0:ae.agentName},v=j,g(j)}else if(w.contentType==="thinking"){let j=(Ho=w.turnId)!=null?Ho:`agent-think-${w.iteration}`,L=Le(j);L.reasoning=(Ir=L.reasoning)!=null?Ir:{id:j,status:"streaming",chunks:[]},L.reasoning.chunks.push((sa=w.delta)!=null?sa:""),L.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId},g(L)}else if(w.contentType==="tool_input"){let j=(mo=w.toolCallId)!=null?mo:I.lastId;if(j){let L=k.get(j);L!=null&&L.toolCall&&(L.toolCall.chunks=(cs=L.toolCall.chunks)!=null?cs:[],L.toolCall.chunks.push((Wr=w.delta)!=null?Wr:""),g(L))}}}else if(Ke==="agent_turn_complete"){let j=w.turnId;if(j){let Z=H.get(j);if(Z!=null&&Z.reasoning){Z.reasoning.status="complete",Z.reasoning.completedAt=Ve(w.completedAt);let K=(ds=Z.reasoning.startedAt)!=null?ds:Date.now();Z.reasoning.durationMs=Math.max(0,((zr=Z.reasoning.completedAt)!=null?zr:Date.now())-K),Z.streaming=!1,g(Z)}}let L=w.stopReason,Q=u!=null?u:v;if(L&&Q!==null){let Z=w.turnId;(!Z||((Vr=Q.agentMetadata)==null?void 0:Vr.turnId)===Z)&&(Q.stopReason=L,g(Q))}}else if(Ke==="agent_tool_start"){u&&(u.streaming=!1,g(u),u=null);let j=(aa=w.toolCallId)!=null?aa:`agent-tool-${l()}`;Be(oe(w),j);let L=Ce(j),Q=(ia=L.toolCall)!=null?ia:{id:j,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};Q.name=(go=(wi=w.toolName)!=null?wi:w.name)!=null?go:Q.name,Q.status="running",w.parameters!==void 0&&(Q.args=w.parameters),Q.startedAt=Ve((Kr=w.startedAt)!=null?Kr:w.timestamp),L.toolCall=Q,L.streaming=!0,L.agentMetadata={executionId:w.executionId,iteration:w.iteration},g(L)}else if(Ke==="agent_tool_delta"){let j=(la=w.toolCallId)!=null?la:I.lastId;if(j){let L=(ps=k.get(j))!=null?ps:Ce(j);L.toolCall&&(L.toolCall.chunks=(Jr=L.toolCall.chunks)!=null?Jr:[],L.toolCall.chunks.push((ca=w.delta)!=null?ca:""),L.toolCall.status="running",L.streaming=!0,g(L))}}else if(Ke==="agent_tool_complete"){let j=(us=w.toolCallId)!=null?us:I.lastId;if(j){let L=(Gr=k.get(j))!=null?Gr:Ce(j);if(L.toolCall){L.toolCall.status="complete",w.result!==void 0&&(L.toolCall.result=w.result),typeof w.executionTime=="number"&&(L.toolCall.durationMs=w.executionTime),L.toolCall.completedAt=Ve((ms=w.completedAt)!=null?ms:w.timestamp),L.streaming=!1,g(L);let Q=oe(w);Q&&I.byCall.delete(Q)}}}else if(Ke==="agent_media"){let j=Array.isArray(w.media)?w.media:[],L=[];for(let Q of j){if(!Q||typeof Q!="object")continue;let Z=Q,K=typeof Z.type=="string"?Z.type:void 0,We=typeof Z.mediaType=="string"?Z.mediaType.toLowerCase():"",$e=null,et="";if(K==="media"){let Ee=typeof Z.data=="string"?Z.data:void 0;if(!Ee)continue;et=We.length>0?We:"application/octet-stream",$e=`data:${et};base64,${Ee}`}else if(K==="image-url"){let Ee=typeof Z.url=="string"?Z.url:void 0;if(!Ee)continue;et=We,$e=Ee}else if(K==="file-url"){let Ee=typeof Z.url=="string"?Z.url:void 0;if(!Ee)continue;et=We,$e=Ee}else continue;if($e)if(K==="image-url"||et.startsWith("image/"))L.push({type:"image",image:$e,...et?{mimeType:et}:{}});else if(et.startsWith("audio/"))L.push({type:"audio",audio:$e,mimeType:et});else if(et.startsWith("video/"))L.push({type:"video",video:$e,mimeType:et});else{let Ee=et||"application/octet-stream";L.push({type:"file",data:$e,mimeType:Ee,filename:Zm(Ee)})}}if(L.length>0){let Q=l(),Z=w.toolCallId,We={id:`agent-media-${typeof Z=="string"&&Z.length>0?`${Z}-${Q}`:String(Q)}`,role:"assistant",content:"",contentParts:L,createdAt:new Date().toISOString(),streaming:!1,sequence:Q,agentMetadata:{executionId:w.executionId,iteration:w.iteration}};g(We);let $e=u;$e&&($e.streaming=!1,g($e)),u=null,x.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let j=`agent-reflection-${w.executionId}-${w.iteration}`,L={id:j,role:"assistant",content:(da=w.reflection)!=null?da:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Rr=w.reflection)!=null?Rr:""]},agentMetadata:{executionId:w.executionId,iteration:w.iteration}};g(L)}else if(Ke==="agent_complete"){ae&&(ae.status=w.success?"complete":"error",ae.completedAt=Ve(w.completedAt),ae.stopReason=w.stopReason);let j=u;j&&(j.streaming=!1,g(j)),n({type:"status",status:"idle"})}else if(Ke==="agent_error"){let j=typeof w.error=="string"?w.error:(Xr=(pa=w.error)==null?void 0:pa.message)!=null?Xr:"Agent execution error";w.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):n({type:"error",error:new Error(j)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let j=(Rt=w.approvalId)!=null?Rt:`approval-${l()}`,L={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Bo=ae==null?void 0:ae.agentId)!=null?Bo:"virtual",executionId:(gs=(Do=w.executionId)!=null?Do:ae==null?void 0:ae.executionId)!=null?gs:"",toolName:(wr=w.toolName)!=null?wr:"",toolType:w.toolType,description:(fs=w.description)!=null?fs:`Execute ${(ua=w.toolName)!=null?ua:"tool"}`,parameters:w.parameters}};g(L)}else if(Ke==="step_await"&&w.awaitReason==="approval_required"){let j=(hs=w.approvalId)!=null?hs:`approval-${l()}`,L={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(ma=ae==null?void 0:ae.agentId)!=null?ma:"virtual",executionId:(Fo=(No=w.executionId)!=null?No:ae==null?void 0:ae.executionId)!=null?Fo:"",toolName:(fo=w.toolName)!=null?fo:"",toolType:w.toolType,description:(fa=w.description)!=null?fa:`Execute ${(ga=w.toolName)!=null?ga:"tool"}`,parameters:w.parameters}};g(L)}else if(Ke==="agent_approval_complete"){let j=w.approvalId;if(j){let Q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(ys=w.decision)!=null?ys:"approved",agentId:(bs=ae==null?void 0:ae.agentId)!=null?bs:"virtual",executionId:(vs=(xs=w.executionId)!=null?xs:ae==null?void 0:ae.executionId)!=null?vs:"",toolName:(vn=w.toolName)!=null?vn:"",description:(Vn=w.description)!=null?Vn:"",resolvedAt:Date.now()}};g(Q)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let j=w.artifactType,L=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:L,artifactType:j,title:Q,component:typeof w.component=="string"?w.component:void 0}),le.set(L,{markdown:"",title:Q}),!V.has(L)){V.add(L);let Z={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:L,title:Q,artifactType:j,status:"streaming"}})};Pe.set(L,Z),g(Z)}}else if(Ke==="artifact_delta"){let j=String(w.id),L=typeof w.delta=="string"?w.delta:String((Hr=w.delta)!=null?Hr:"");n({type:"artifact_delta",id:j,artDelta:L});let Q=le.get(j);Q&&(Q.markdown+=L)}else if(Ke==="artifact_update"){let j=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:j,component:typeof w.component=="string"?w.component:void 0})}else if(Ke==="artifact_complete"){let j=String(w.id);n({type:"artifact_complete",id:j});let L=Pe.get(j);if(L){L.streaming=!1;try{let Q=JSON.parse((ot=L.rawContent)!=null?ot:"{}");if(Q.props){Q.props.status="complete";let Z=le.get(j);Z!=null&&Z.markdown&&(Q.props.markdown=Z.markdown)}L.rawContent=JSON.stringify(Q)}catch{}le.delete(j),g(L),Pe.delete(j)}}}else if(Ke==="transcript_insert"){let j=w.message;if(!j||typeof j!="object")continue;let L=String((Cs=j.id)!=null?Cs:`msg-${l()}`),Q=j.role,K={id:L,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(g(K),K.rawContent)try{let We=JSON.parse(K.rawContent),$e=(ho=We==null?void 0:We.props)==null?void 0:ho.artifactId;typeof $e=="string"&&V.add($e)}catch{}u=null,x.current=null,te.delete(L),se.delete(L)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let j=null;if(w.error instanceof Error)j=w.error;else if(Ke==="dispatch_error"){let L=(gr=w.message)!=null?gr:w.error;L!=null&&L!==""&&(j=new Error(String(L)))}else if(Ke==="step_error"||Ke==="flow_error"){let L=w.error;typeof L=="string"&&L!==""?j=new Error(L):L!=null&&typeof L=="object"&&"message"in L&&(j=new Error(String((ha=L.message)!=null?ha:L)))}else Ke==="error"&&w.error!=null&&w.error!==""&&(j=new Error(String(w.error)));if(j){n({type:"error",error:j});let L=u;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:F,value:Ae}=await s.read();if(F)break;a+=o.decode(Ae,{stream:!0});let De=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=De.pop())!=null?Hn:"";for(let Ne of De){let je=Ne.split(`
12
- `),dt="message",rt="";for(let q of je)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((qe=this.onSSEEvent)==null||qe.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 ng(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ps(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Vo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ia="[Image]";function rg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function og(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function sg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ag(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Wa(e){return{type:"text",text:e}}function ig(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 lg(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 cg(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 Bp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],dg=["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=[...Bp,...dg];function pg(e){return Bp.includes(e)||e.startsWith("image/")}function Ra(e){return pg(e.type)}async function Dp(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 Np(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 ug(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Fp(e,t){let n=ug(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 Is=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=...`,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 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(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 Eo=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 Ko(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Is(e.runtype);case"browser":if(!Eo.isSupported())throw new Error("Browser speech recognition not supported");return new Eo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Pi(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ko({type:"runtype",runtype:e.runtype});if(Eo.isSupported())return Ko({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 Pi(e),!0}catch{return!1}}function Op(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 Ws=e=>({isError:!0,content:[{type:"text",text:e}]}),$p=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Rs=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)&&So(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 zo(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=Ko(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 zo(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"?Ps():n==="assistant"?Vo():`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"?Ps():s==="assistant"?Vo():`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=Ps(),o=Vo(),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 C=Op(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=Vo();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=Op(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,k,P,W;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=(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 A=(x=t.toolCall)==null?void 0:x.args,I=Array.isArray(A==null?void 0:A.questions)?A.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 A=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:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};l.forEach((I,O)=>{let D=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!D)return;let R=A[D],_=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${O}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${O}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(s,{[o]:n});if(!A.ok){let I=await A.json().catch(()=>null);throw new Error((k=I==null?void 0:I.error)!=null?k:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let I=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(W=(P=this.callbacks).onError)==null||W.call(P,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 m=>{var P,W,A,I,O,D,R;let g=(P=m.toolCall)==null?void 0:P.name,u=(W=m.toolCall)==null?void 0:W.id;if(!g||!u)return null;let v=`${t}:${u}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return null;this.webMcpInflightKeys.add(v),r.push(v);let x=this.markWebMcpToolRunning(m),C=new AbortController;this.webMcpResolveControllers.add(C),s.push(C);let T=(I=(A=m.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?I:g,H=this.client.executeWebMcpToolCall(g,(O=m.toolCall)==null?void 0:O.args,C.signal),k;if(!H)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await H}catch(_){let z=_ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"));return z||(R=(D=this.callbacks).onError)==null||R.call(D,_ instanceof Error?_:new Error(String(_))),this.markWebMcpToolComplete(m,Ws(z?"Aborted by cancel()":$p(_)),x),this.webMcpInflightKeys.delete(v),null}return C.signal.aborted?(this.markWebMcpToolComplete(m,Ws("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:k,toolMessage:m,startedAt:x,completedAt:Date.now()}})),i=[];try{if(i=a.filter(u=>u!==null),i.length===0)return;let m={};for(let u of i)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((d=u==null?void 0:u.error)!=null?d:`Resume failed: ${g.status}`)}for(let u of i)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(m){if(!(m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,m instanceof Error?m:new Error(String(m)));else for(let u of i)this.markWebMcpToolComplete(u.toolMessage,Ws("Aborted by cancel()"),u.startedAt)}finally{for(let m of r)this.webMcpInflightKeys.delete(m);for(let m of s)this.webMcpResolveControllers.delete(m);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,v,x,C,T,H,k,P,W,A,I,O;let n=(u=t.agentMetadata)==null?void 0:u.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(x=t.toolCall)==null?void 0:x.id;if(!n){(T=(C=this.callbacks).onError)==null||T.call(C,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let D=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(D)||this.webMcpResolvedKeys.has(D))return;this.webMcpInflightKeys.add(D);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(D)}catch(R){(k=(H=this.callbacks).onError)==null||k.call(H,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(D)}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=(P=t.toolCall)==null?void 0:P.args,p=this.client.executeWebMcpToolCall(r,l,d),m="execute",g=a;try{let D;if(p?D=await p:D={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ws("Aborted by cancel()"),a);return}let R=(A=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?A:r;m="resume",await this.resumeWithToolOutput(n,R,D,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,D,a,g)},signal:d})}catch(D){let R=D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")||D.message.includes("abort"));(m==="execute"||R||d.aborted)&&this.markWebMcpToolComplete(t,Ws(R||d.aborted?"Aborted by cancel()":$p(D)),a),R||(O=(I=this.callbacks).onError)==null||O.call(I,D instanceof Error?D:new Error(String(D)))}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,m,g,u,v,x,C,T,H,k;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&&So(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let P=`${d}:${l}`,W=this.webMcpInflightKeys.has(P),A=this.webMcpResolvedKeys.has(P),I=(x=s.toolCall)==null?void 0:x.name,O=((C=s.agentMetadata)==null?void 0:C.executionId)===d&&((T=s.toolCall)==null?void 0:T.id)===l&&I!==void 0&&So(I)&&((H=s.toolCall)==null?void 0:H.status)==="complete";(W||A||O)&&(a.agentMetadata={...(k=a.agentMetadata)!=null?k:{},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},Sr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import{Activity as mg,ArrowDown as gg,ArrowUp as fg,ArrowUpRight as hg,Bot as yg,ChevronDown as bg,ChevronUp as xg,ChevronRight as vg,ChevronLeft as Cg,Check as wg,Clipboard as Ag,ClipboardCopy as Sg,Copy as Tg,File as Eg,FileCode as Mg,FileSpreadsheet as kg,FileText as Lg,ImagePlus as Pg,Loader as Ig,LoaderCircle as Wg,Mic as Rg,Paperclip as Hg,RefreshCw as Bg,Search as Dg,Send as Ng,ShieldAlert as Fg,ShieldCheck as Og,ShieldX as $g,Square as _g,ThumbsDown as jg,ThumbsUp as Ug,Upload as qg,Volume2 as zg,X as Vg,User as Kg,Mail as Jg,Phone as Gg,Calendar as Xg,Clock as Qg,Building as Yg,MapPin as Zg,Lock as ef,Key as tf,CreditCard as nf,AtSign as rf,Hash as of,Globe as sf,Link as af,CircleCheck as lf,CircleX as cf,TriangleAlert as df,Info as pf,Ban as uf,Shield as mf,ArrowLeft as gf,ArrowRight as ff,ExternalLink as hf,Ellipsis as yf,EllipsisVertical as bf,Menu as xf,House as vf,Plus as Cf,Minus as wf,Pencil as Af,Trash as Sf,Trash2 as Tf,Save as Ef,Download as Mf,Share as kf,Funnel as Lf,Settings as Pf,RotateCw as If,Maximize as Wf,Minimize as Rf,ShoppingCart as Hf,ShoppingBag as Bf,Package as Df,Truck as Nf,Tag as Ff,Gift as Of,Receipt as $f,Wallet as _f,Store as jf,DollarSign as Uf,Percent as qf,Play as zf,Pause as Vf,VolumeX as Kf,Camera as Jf,Image as Gf,Film as Xf,Headphones as Qf,MessageCircle as Yf,MessageSquare as Zf,Bell as eh,Heart as th,Star as nh,Eye as rh,EyeOff as oh,Bookmark as sh,CalendarDays as ah,History as ih,Timer as lh,Folder as ch,FolderOpen as dh,Files as ph,Sparkles as uh,Zap as mh,Sun as gh,Moon as fh,Flag as hh,Monitor as yh,Smartphone as bh}from"lucide";var xh={activity:mg,"arrow-down":gg,"arrow-up":fg,"arrow-up-right":hg,bot:yg,"chevron-down":bg,"chevron-up":xg,"chevron-right":vg,"chevron-left":Cg,check:wg,clipboard:Ag,"clipboard-copy":Sg,copy:Tg,file:Eg,"file-code":Mg,"file-spreadsheet":kg,"file-text":Lg,"image-plus":Pg,loader:Ig,"loader-circle":Wg,mic:Rg,paperclip:Hg,"refresh-cw":Bg,search:Dg,send:Ng,"shield-alert":Fg,"shield-check":Og,"shield-x":$g,square:_g,"thumbs-down":jg,"thumbs-up":Ug,upload:qg,"volume-2":zg,x:Vg,user:Kg,mail:Jg,phone:Gg,calendar:Xg,clock:Qg,building:Yg,"map-pin":Zg,lock:ef,key:tf,"credit-card":nf,"at-sign":rf,hash:of,globe:sf,link:af,"circle-check":lf,"circle-x":cf,"triangle-alert":df,info:pf,ban:uf,shield:mf,"arrow-left":gf,"arrow-right":ff,"external-link":hf,ellipsis:yf,"ellipsis-vertical":bf,menu:xf,house:vf,plus:Cf,minus:wf,pencil:Af,trash:Sf,"trash-2":Tf,save:Ef,download:Mf,share:kf,funnel:Lf,settings:Pf,"rotate-cw":If,maximize:Wf,minimize:Rf,"shopping-cart":Hf,"shopping-bag":Bf,package:Df,truck:Nf,tag:Ff,gift:Of,receipt:$f,wallet:_f,store:jf,"dollar-sign":Uf,percent:qf,play:zf,pause:Vf,"volume-x":Kf,camera:Jf,image:Gf,film:Xf,headphones:Qf,"message-circle":Yf,"message-square":Zf,bell:eh,heart:th,star:nh,eye:rh,"eye-off":oh,bookmark:sh,"calendar-days":ah,history:ih,timer:lh,folder:ch,"folder-open":dh,files:ph,sparkles:uh,zap:mh,sun:gh,moon:fh,flag:hh,monitor:yh,smartphone:bh},be=(e,t=24,n="currentColor",r=2)=>{let s=xh[e];return s?vh(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 vh(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:Nr,maxFileSize:10*1024*1024,maxFiles:4};function Ch(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function wh(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 Jo=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=Np(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 Dp(l),g=Ra(l)?URL.createObjectURL(l):null,u={id:Ch(),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=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=wh(t.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Fp(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 _p=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Hs(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];_p(o)&&_p(s)?n[r]=Hs(o,s):n[r]=s}return n}var sr="min(440px, calc(100vw - 24px))",Ii="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 jp(e,t){if(!(!e&&!t))return e?t?Hs(e,t):e:t}function Wi(e){var t,n,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,k,P,W;return e?{...Ft,...e,theme:jp(Ft.theme,e.theme),darkTheme:jp(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,Be,ee,Pe,V,le,ve;let A=(ye=Ft.features)==null?void 0:ye.artifacts,I=(Le=e.features)==null?void 0:Le.artifacts,O=(Be=Ft.features)==null?void 0:Be.scrollToBottom,D=(ee=e.features)==null?void 0:ee.scrollToBottom,R=(Pe=Ft.features)==null?void 0:Pe.streamAnimation,_=(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,Re=A===void 0&&I===void 0?void 0:{...A,...I,layout:{...A==null?void 0:A.layout,...I==null?void 0:I.layout}},Ue=O===void 0&&D===void 0?void 0:{...O,...D},Fe=R===void 0&&_===void 0?void 0:{...R,..._},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,...Ue!==void 0?{scrollToBottom:Ue}:{},...Re!==void 0?{artifacts:Re}:{},...Fe!==void 0?{streamAnimation:Fe}:{},...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,...(k=e.layout)==null?void 0:k.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 Up={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"}},qp={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"}},zp={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:Ii,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 Go(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."))?Go(e,r):r}function Ri(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=Go(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 Vp(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 Kp(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]=Kp(o,s):n[r]=s}return n}function Ah(e,t){return t?Kp(e,t):e}function Bs(e,t={}){var s,o,a,i,d,l,p,m,g,u,v,x,C;let n={palette:Up,semantic:qp,components:zp},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:Ah(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=Vp(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 Hi(e){var x,C,T,H,k,P,W,A,I,O,D,R,_,z,oe,Re,Ue,Fe,ge,ye,Le,Be,ee,Pe,V,le,ve,fe,Ce,Ve,X,te,se,ue,ie,re,Qe,Ie,ce,J,_e,Et,de,ae,Mn,Ot,ln,Hn,Xn,qe,F,Ae,De,Ne,je,dt,rt,At,_t,q,$t,Ye,Dt,ne,me,vt,jt,Zt,hn,St,Ct,ft,yt,zt,tt,Bn,Qn,yn,Dn,ut,xr,Nn,po,kn,Wo,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=Ri(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"]=(k=n["--persona-semantic-colors-background"])!=null?k: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"]=(A=n["--persona-semantic-colors-text-muted"])!=null?A: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"]=(D=n["--persona-semantic-colors-divider"])!=null?D:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(_=n["--persona-components-voice-recording-background"])!=null?_: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"]=(Re=n["--persona-components-approval-requested-background"])!=null?Re:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ue=n["--persona-components-approval-requested-border"])!=null?Ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Fe=n["--persona-components-approval-requested-text"])!=null?Fe: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"]=(Be=n["--persona-components-attachment-image-border"])!=null?Be: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"]=(Ce=n["--persona-palette-radius-lg"])!=null?Ce:"0.5rem",n["--persona-radius-xl"]=(Ve=n["--persona-palette-radius-xl"])!=null?Ve:"0.75rem",n["--persona-radius-full"]=(X=n["--persona-palette-radius-full"])!=null?X:"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"]=(J=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?J:"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"]=(F=(qe=n["--persona-components-message-assistant-borderRadius"])!=null?qe:n["--persona-radius-lg"])!=null?F:"0.5rem",n["--persona-header-bg"]=(Ae=n["--persona-components-header-background"])!=null?Ae:n["--persona-surface"],n["--persona-header-border"]=(De=n["--persona-components-header-border"])!=null?De:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ne=n["--persona-components-header-iconBackground"])!=null?Ne:n["--persona-primary"],n["--persona-header-icon-fg"]=(je=n["--persona-components-header-iconForeground"])!=null?je: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"]=(Ct=n["--persona-components-message-assistant-background"])!=null?Ct: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"]=(Wo=(kn=n["--persona-components-scrollToBottom-shadow"])!=null?kn:n["--persona-palette-shadows-sm"])!=null?Wo:"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=Go(e,S.toolbarBackground))!=null?qn:S.toolbarBackground;n["--persona-artifact-toolbar-bg"]=zn}}return n}var Sh={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 Th={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"}}},Jp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Fa=()=>{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"},Eh=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Fa()},Gp=e=>Eh(e),Mh=e=>Bs(e),kh=e=>{var n;let t=Bs(void 0,{validate:!1});return Bs({...e,palette:{...t.palette,colors:{...Th.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ds=e=>{let t=Gp(e),n=Jp(e==null?void 0:e.theme),r=Jp(e==null?void 0:e.darkTheme);return t==="dark"?kh(Hs(n!=null?n:{},r!=null?r:{})):Mh(n)},Lh=e=>Hi(e),Mo=(e,t)=>{var o;let n=Ds(t),r=Lh(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)},Bi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Fa())});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(Fa());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 Ph}from"idiomorph";var Oa=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Ph.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 Xp(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 Qp(e,t){var n,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,k,P,W,A,I,O,D,R,_,z,oe,Re,Ue,Fe,ge,ye,Le,Be,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:"",(k=(H=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:H.length)!=null?k:0,(I=(A=(W=(P=e.toolCall)==null?void 0:P.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?I:"",typeof((O=e.toolCall)==null?void 0:O.args)=="string"?e.toolCall.args.length:(D=e.toolCall)!=null&&D.args?JSON.stringify(e.toolCall.args).length:0,(z=(_=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:_.length)!=null?z:0,(Fe=(Ue=(Re=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:Re[e.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?Fe:0,(Be=(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?Be:"",(Pe=(ee=e.contentParts)==null?void 0:ee.length)!=null?Pe:0,(V=e.stopReason)!=null?V:"",t].join("\0")}function Yp(){return new Map}function Zp(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function eu(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function tu(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 Ns(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Fs(e,t){return Ns(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 gn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},fn=1e5,eo=fn+1;var Os={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ih=["pre","code","a","script","style"],qa=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Os.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Os.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Os.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Os.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Os.buffer}},ru=[{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"}],$s=new Map;for(let e of ru)$s.set(e.name,e);var Wh=e=>{$s.set(e.name,e)},Rh=e=>{ru.some(t=>t.name===e)||$s.delete(e)},Hh=()=>Array.from($s.keys()),_s=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=$s.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},Bh=(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},Dh=(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},Di=/\s/,Nh=(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},Fh=(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(Di.test(o[i])){let l=i;for(;l<o.length&&Di.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&&!Di.test(o[p]);)l.appendChild(Bh(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},Oh=(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(Dh(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},js=(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:Ih).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Nh(d,o)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Fh:Oh;for(let u of i)p(u,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},Us=(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},nu=new WeakMap,$h=(e,t)=>{var o;if(!e.styles)return;let n=nu.get(t);if(n||(n=new Set,nu.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)},Ni=new WeakMap,_h=(e,t)=>{if(!e.onAttach)return;let n=Ni.get(t);if(n||(n=new Map,Ni.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},ou=e=>{let t=Ni.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Fi=(e,t)=>{$h(e,t),_h(e,t)};function Oi(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 qs=0,to=null;function $i(e=document){var n;if(qs++,qs===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,qs=Math.max(0,qs-1),qs===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 Ka={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: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 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 zs=(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 Ws=e=>({isError:!0,content:[{type:"text",text:e}]
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 k,P,W,A,I,O,D,R,_,z,oe,Re,Ue,Fe;let a=(k=o.launcher)!=null?k:{},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=(A=a.agentIconSize)!=null?A:"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=(D=a.agentIconSize)!=null?D:"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=(R=a.callToActionIconSize)!=null?R:"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,Be=Math.max(Le-ye,8),ee=be(a.callToActionIconName,Be,"currentColor",2);ee?u.appendChild(ee):u.textContent=(_=a.callToActionIconText)!=null?_:"\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=(Re=a.border)!=null?Re:T,n.style.boxShadow=(Ue=a.shadow)!=null?Ue: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=(Fe=a.collapsedMaxWidth)!=null?Fe:"",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 jh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ja=(e,t={})=>{var x,C,T,H,k,P;let{showClose:n=!0,wrapperClassName:r=jh,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=(k=a.closeButtonIconName)!=null?k:"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",A=a.closeButtonBorderColor||"transparent";l.style.border=`${W} 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),m&&p){let W=null,A=()=>{if(W)return;let O=l.ownerDocument,D=O.body;if(!D)return;W=Sr(O,"div","persona-clear-chat-tooltip"),W.textContent=p;let R=Sr(O,"div");R.className="persona-clear-chat-tooltip-arrow",W.appendChild(R);let _=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(eo),W.style.left=`${_.left+_.width/2}px`,W.style.top=`${_.top-8}px`,W.style.transform="translate(-50%, -100%)",D.appendChild(W)},I=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",A),d.addEventListener("mouseleave",I),l.addEventListener("focus",A),l.addEventListener("blur",I),d._cleanupTooltip=()=>{I(),d.removeEventListener("mouseenter",A),d.removeEventListener("mouseleave",I),l.removeEventListener("focus",A),l.removeEventListener("blur",I)}}return{button:l,wrapper:d}},Uh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ga=(e,t={})=>{var W,A,I,O,D,R,_,z,oe,Re,Ue,Fe,ge;let{wrapperClassName:n=Uh,buttonSize:r,iconSize:s="20px"}=t,a=(A=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?A:{},i=(I=r!=null?r:a.size)!=null?I:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",l=(D=a.iconColor)!=null?D:"",p=(R=a.backgroundColor)!=null?R:"",m=(_=a.borderWidth)!=null?_:"",g=(z=a.borderColor)!=null?z:"",u=(oe=a.borderRadius)!=null?oe:"",v=(Re=a.paddingX)!=null?Re:"",x=(Ue=a.paddingY)!=null?Ue:"",C=(Fe=a.tooltipText)!=null?Fe:"Clear chat",T=(ge=a.showTooltip)!=null?ge:!0,H=h("div",n),k=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");k.style.height=i,k.style.width=i,k.type="button",k.setAttribute("aria-label",C),k.style.color=l||En.actionIconColor;let P=be(d,s,"currentColor",1);if(P&&(P.style.display="block",k.appendChild(P)),p&&(k.style.backgroundColor=p,k.classList.remove("hover:persona-bg-gray-100")),m||g){let ye=m||"0px",Le=g||"transparent";k.style.border=`${ye} solid ${Le}`,k.classList.remove("persona-border-none")}if(u&&(k.style.borderRadius=u,k.classList.remove("persona-rounded-full")),v&&(k.style.paddingLeft=v,k.style.paddingRight=v),x&&(k.style.paddingTop=x,k.style.paddingBottom=x),H.appendChild(k),T&&C){let ye=null,Le=()=>{if(ye)return;let ee=k.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=k.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)},Be=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};H.addEventListener("mouseenter",Le),H.addEventListener("mouseleave",Be),k.addEventListener("focus",Le),k.addEventListener("blur",Be),H._cleanupTooltip=()=>{Be(),H.removeEventListener("mouseenter",Le),H.removeEventListener("mouseleave",Be),k.removeEventListener("focus",Le),k.removeEventListener("blur",Be)}}return{button:k,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,A,I,O,D,R,_,z,oe,Re,Ue,Fe,ge,ye,Le,Be;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=(A=s.headerIconSize)!=null?A:"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=(R=(D=t==null?void 0:t.launcher)==null?void 0:D.agentIconText)!=null?R:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.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=(Ue=(Re=t==null?void 0:t.launcher)==null?void 0:Re.title)!=null?Ue:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=En.subtitleColor,g.textContent=(ge=(Fe=t==null?void 0:t.launcher)==null?void 0:Fe.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=(Be=u.placement)!=null?Be:"inline",C=null,T=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"});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:k,wrapper:P}=Ja(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&r.appendChild(P),{header:r,iconHolder:l,headerTitle:m,headerSubtitle:g,closeButton:k,closeButtonWrapper:P,clearChatButton:C,clearChatButtonWrapper:T}},Xo=(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 ko(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 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 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 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 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=ko({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 su=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 qh(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=ko({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 au=e=>{var H,k,P,W,A,I,O,D,R;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:(k=a.title)!=null?k:"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),qh(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 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 _=s==null?void 0:s.titleRowHover;_&&(l.style.borderRadius=(I=_.borderRadius)!=null?I:"10px",l.style.padding=(O=_.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=_.background)!=null?z:"",l.style.borderColor=(oe=_.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(D=a.closeButtonSize)!=null?D:"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=(R=a.closeButtonIconName)!=null?R:"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}},ji={default:su,minimal:au},iu=e=>{var t;return(t=ji[e])!=null?t:ji.default},Vs=(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=iu(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 W,A,I,O,D,R,_,z,oe,Re,Ue,Fe;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(A=t.useIcon)!=null?A:!1,r=(I=t.iconText)!=null?I:"\u2191",s=t.iconName,o=(O=t.stopIconName)!=null?O:"square",a=(D=t.tooltipText)!=null?D:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(z=(_=e==null?void 0:e.copy)==null?void 0:_.sendButtonLabel)!=null?z:"Send",l=(Re=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?Re:"Stop",p=(Ue=t.showTooltip)!=null?Ue:!1,m=(Fe=t.size)!=null?Fe:"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 k="send";return{button:x,wrapper:v,setMode:ge=>{if(ge===k)return;k=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}}},ei=e=>{var H,k,P,W,A,I,O,D,R,_,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=((k=t.provider)==null?void 0:k.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=(A=t.iconName)!=null?A:"mic",p=(I=t.iconSize)!=null?I:a,m=parseFloat(p)||24,g=(D=t.backgroundColor)!=null?D:(O=e==null?void 0:e.sendButton)==null?void 0:O.backgroundColor,u=(_=t.iconColor)!=null?_:(R=e==null?void 0:e.sendButton)==null?void 0:R.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 Re=h("div","persona-send-button-tooltip");Re.textContent=C,i.appendChild(Re)}return{button:d,wrapper:i}},ti=e=>{var v,x,C,T,H,k,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",(k=t.buttonTooltipText)!=null?k:"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",A=>{A.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}},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 Ks=e=>{var v,x,C,T,H,k;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 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:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var lu=()=>{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}},cu=e=>{var v,x,C,T,H,k;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 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:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var du=e=>{var p,m,g,u,v,x,C,T,H,k,P,W,A,I,O,D,R;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 _=(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=_.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 Re=h("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(T=_.expandedSize)!=null?T:"anchored",Re.style.zIndex=String((k=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?k:fn),{wrapper:z,panel:oe,pillRoot:Re}}if(n){let _=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 _.appendChild(z),{wrapper:_,panel:z}}if(!t){let _=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 _.style.width=oe,z.style.width="100%",_.appendChild(z),{wrapper:_,panel:z}}let s=(A=e==null?void 0:e.launcher)!=null?A:{},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=(R=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?R: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}},zh=(e,t)=>{var P,W,A,I,O,D,R,_,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}=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=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.clearChat)==null?void 0:W.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 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=(R=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",p.append(m,g);let u=h("div","persona-flex persona-flex-col persona-gap-3"),v=(_=e==null?void 0:e.layout)==null?void 0:_.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=cu({config:e}),{root:H,textNode:k}=lu();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:k}},pu=(e,t=!0)=>{var C,T,H,k,P,W,A,I,O;if(no(e))return zh(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?Vs(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=(k=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?k:"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=(A=e==null?void 0:e.layout)==null?void 0:A.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=Ks({config:e}),v=((O=e==null?void 0:e.layout)==null?void 0:O.showFooter)!==!1;s?Xo(n,o,e):(o.header.style.display="none",Xo(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 Vh=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}},Kh=(e,t)=>{if(!e)return null;let n=Vh(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Jh=(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},Gh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Ui=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(":"))},qi=320,mu=320,Xh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Qh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Yh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Zh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),ey=(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=`${qi}px`,l.style.maxHeight=`${mu}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}),Gh(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}},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","audio");let n=0;return e.forEach(r=>{if(!Ui(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=`${qi}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ny=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(!Ui(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=`${qi}px`,s.style.maxHeight=`${mu}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}},ry=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(!Ui(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}},Qo=()=>{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},gu=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Qo};if(t){let s=t(r);if(s!==null)return s}return Qo()},oy=(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},uu=(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},sy=(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},fu=(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 k=h("div");return k.style.display="none",k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id),k}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=(k,P,W)=>{let A=qt({icon:k,label:P,size:14,className:"persona-message-action-btn"});return A.setAttribute("data-action",W),A};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},Js=(e,t,n,r,s,o)=>{var ee,Pe,V,le,ve,fe,Ce,Ve,X,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=sy(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=Xh(e),T=(Ce=(fe=e.content)==null?void 0:fe.trim())!=null?Ce:"",k=C.length>0&&T===Ia,P=qa((X=(Ve=o==null?void 0:o.widgetConfig)==null?void 0:Ve.features)==null?void 0:X.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,A=e.role==="assistant"&&P.type!=="none"?_s(P.type,W):null,I=e.role==="assistant"&&((ie=A==null?void 0:A.isAnimating)==null?void 0:ie.call(A,e))===!0,O=e.role==="assistant"&&A!==null&&(!!e.streaming||I);O&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),O&&A&&(A.containerClass&&D.classList.add(A.containerClass),D.style.setProperty("--persona-stream-step",`${P.speed}ms`),D.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let R=O?za((re=e.content)!=null?re:"",P.buffer,A,e,!!e.streaming):(Qe=e.content)!=null?Qe:"",_=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=_;O&&(A==null?void 0:A.wrap)==="char"?z=js(_,"char",e.id,{skipTags:A.skipTags}):O&&(A==null?void 0:A.wrap)==="word"&&(z=js(_,"word",e.id,{skipTags:A.skipTags}));let oe=null;if(k?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",D.appendChild(oe)):D.innerHTML=z,O&&(A!=null&&A.useCaret)&&!k&&T){let J=Va(),_e=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=_e[_e.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(J,Et.nextSibling);else{let de=D.lastElementChild;de?de.appendChild(J):D.appendChild(J)}}if(m&&u==="inline"&&e.createdAt){let J=uu(e,l);J.classList.add("persona-ml-2","persona-inline"),D.appendChild(J)}if(C.length>0){let J=ey(C,!k&&!!T,()=>{k&&oe&&(oe.style.display="")});J?x.appendChild(J):k&&oe&&(oe.style.display="")}let Re=Qh(e);if(Re.length>0){let J=ty(Re);J&&x.appendChild(J)}let Ue=Yh(e);if(Ue.length>0){let J=ny(Ue);J&&x.appendChild(J)}let Fe=Zh(e);if(Fe.length>0){let J=ry(Fe);J&&x.appendChild(J)}if(x.appendChild(D),m&&u==="below"&&e.createdAt){let J=uu(e,l);J.classList.add("persona-mt-1"),x.appendChild(J)}let ge=e.role==="assistant"?Kh(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 J=!!(R&&R.trim()),_e=P.placeholder==="skeleton",Et=_e&&P.buffer==="line"&&J;if(J)Et&&x.appendChild(Us());else if(_e)x.appendChild(Us());else{let de=gu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);de&&x.appendChild(de)}}if(ge&&e.stopReason&&!e.streaming&&(T||(D.style.display="none"),x.appendChild(Jh(e.stopReason,ge))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=fu(e,r,s);x.appendChild(J)}if(!p||e.role==="system")return x;let Le=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Be=oy(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Le.append(x,Be):Le.append(Be,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},ay=(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}):Js(e,t,n,r,s,o)};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 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
- `):""},hu=(e,t)=>{let n=Yo.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")},zi=(e,t)=>{var Ue,Fe,ge,ye,Le,Be,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=(Fe=(Ue=t==null?void 0:t.features)==null?void 0:Ue.reasoningDisplay)!=null?Fe:{},o=s.expandable!==!1,a=o&&Yo.has(e.id),i=n.status!=="complete",d=ly(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=Ma(n),fe},C=(Be=u.renderCollapsedSummary)==null?void 0:Be.call(u,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ma(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=Wp(n),p.appendChild(T);let H=(ee=s.loadingAnimation)!=null?ee:"none",k=u.activeTextTemplate,P=u.completeTextTemplate,W=i?k:P,A=C instanceof HTMLElement,I=(fe,Ce,Ve)=>{let X=Ve;for(let te of Ce){let se=h("span","persona-tool-char");se.style.setProperty("--char-index",String(X)),se.textContent=te===" "?"\xA0":te,fe.appendChild(se),X++}return X},O=(fe,Ce)=>{m.textContent="";let Ve=ka(fe,""),X=0;for(let te of Ve){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?Ma(n):te.text;Ce?X=I(se,ue,X):se.appendChild(document.createTextNode(ue))}}};if(!A&&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(!A&&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 Ce=m.textContent||g;m.textContent="",I(m,Ce,0)}n.status==="complete"&&(m.style.display="none")}else A||(n.status==="complete"?m.style.display="none":m.style.display="");let D=null;if(o){D=h("div","persona-flex persona-items-center");let Ce=be(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?D.appendChild(Ce):D.textContent=a?"Hide":"Show";let Ve=h("div","persona-flex persona-items-center persona-ml-auto");Ve.append(D),l.append(p,Ve)}else l.append(p);let R=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.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:{}});iy(R,fe)||(R.textContent=d),R.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,R),r;let _=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.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"),_.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),D){D.innerHTML="";let Ce=be(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?D.appendChild(Ce):D.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(l,R,_),r};var Zo=new Set,cy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),dy=(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=qo(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},py=(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=dy(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?Rp(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=Si(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Si(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},yu=(e,t,n)=>{var p;let r=Zo.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")},Vi=(e,t)=>{var z,oe,Re,Ue,Fe,ge,ye,Le,Be;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=(Re=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?Re:{},a=o.expandable!==!1,i=a&&Zo.has(e.id),{summary:d,previewText:l,isActive:p}=py(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((Ue=n.startedAt)!=null?Ue:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",v),ee.textContent=Ls(n),ee},C=(ge=r.renderCollapsedSummary)==null?void 0:ge.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Fe=o.collapsedMode)!=null?Fe:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Ls(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,k=r.completeTextTemplate,P=p?H:k,W=C instanceof HTMLElement,A=(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=ka(ee,V),ve=0;for(let Ce of le){let Ve=Ce.styles.length>0?(()=>{let X=h("span",Ce.styles.map(te=>`persona-tool-text-${te}`).join(" "));return u.appendChild(X),X})():u;if(Ce.isDuration&&p)Ve.appendChild(x());else{let X=Ce.isDuration?Ls(n):Ce.text;Pe?ve=A(Ve,X,ve):Ve.appendChild(document.createTextNode(X))}}};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="",A(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 D=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let ee=(Be=r.renderCollapsedPreview)==null?void 0:Be.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});cy(D,ee)||(D.textContent=l),D.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,D),s;let R=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.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,R.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=qo(n.args),ee.append(Pe,V),R.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),R.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=qo(n.result),ee.append(Pe,V),R.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`,R.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"}R.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),s.append(m,D,R),s};import{parse as uy,ARR as my,OBJ as gy,STR as fy}from"partial-json";var xu="ask_user_question",Ki=8,es="data-persona-ask-sheet-for",hy="Other",yy="Other\u2026",vu="Type your own answer here",Cu="Send",by="Next",xy="Back",vy="Submit all",Cy="Skip",wy=3,Ji="data-ask-current-index",Gi="data-ask-question-count",wu="data-ask-answers",Xi="data-ask-grouped",Au="data-ask-layout",Ay=e=>e.layout==="pills"?"pills":"rows",Sy=e=>e.getAttribute(Au)==="pills"?"pills":"rows",bu=!1,Su=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===xu,oi=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=uy(s,fy|gy|my);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},Gs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Ki&&!bu&&(bu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ki}.`)),t.slice(0,Ki)},Ty=e=>{var t;return(t=Gs(e)[0])!=null?t:null},Ey=(e,t)=>{var n;return(n=Gs(e)[t])!=null?n:null},Tu=(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))},Eu=(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},My=(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=Eu(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},ky=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},Ly=(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<wy;u++)o.appendChild(ky(r));return o}if(d.forEach((u,v)=>{o.appendChild(My(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?hy:yy;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:vu,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=Eu(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},Mu=(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:vu,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:Cu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Py=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:Cu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Iy=(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:xy,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:Cy,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:vy:(g=n.nextLabel)!=null?g:by,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Lo=e=>{let t=e.getAttribute(wu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},ku=(e,t)=>{e.setAttribute(wu,JSON.stringify(t))},ar=e=>{var n;let t=Number((n=e.getAttribute(Ji))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Wy=(e,t)=>{e.setAttribute(Ji,String(Math.max(0,Math.floor(t))))},ts=e=>{var n;let t=Number((n=e.getAttribute(Gi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ao=e=>e.getAttribute(Xi)==="true",Ry=(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},Hy=(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}=so(t),r=Gs(n),s=Lo(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},Lu=e=>{let t=Lo(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=""},Pu=e=>{if(!ao(e))return;let t=Lo(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}},Qi=(e,t,n)=>{let r=oi(n),s=Sy(e),{payload:o,complete:a}=so(t),i=ao(e),d=ar(e),l=ts(e),p=i?Ey(o,d):Ty(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=Ly(p,r,a,s);x.replaceWith(H)}if(s!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(Mu(r,s))}let C=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!C?e.appendChild(Py(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=Iy(d,l,r);T?T.replaceWith(H):e.appendChild(H)}else T&&T.remove();Lu(e),Pu(e)},By=(e,t,n)=>{let r=oi(t),s=Ay(r),o=e.toolCall.id,a=Gs(n),i=Math.max(1,a.length),d=i>1,l=Ry(e,a),p=d?Hy(e,i):0,m=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(es,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(Gi,String(i)),m.setAttribute(Ji,String(p)),m.setAttribute(Xi,d?"true":"false"),m.setAttribute(Au,s),ku(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`),Tu(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(Mu(r,s)),Qi(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Dy=(e,t,n)=>{let{payload:r}=so(t),s=Math.max(1,Gs(r).length);s>ts(e)&&(e.setAttribute(Gi,String(s)),s>1&&!ao(e)&&e.setAttribute(Xi,"true")),Qi(e,t,n)},Ny=(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);Tu(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},Xs=(e,t,n)=>{if(!n||!oo(e)||oi(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${es}]`).forEach(l=>{l.getAttribute(es)!==s&&l.remove()});let a=n.querySelector(`[${es}="${Su(s)}"]`);if(a){Dy(a,e,t);return}let{payload:i}=so(e),d=By(e,t,i);n.appendChild(d)},Po=(e,t)=>{if(!e)return;let n=t?`[${es}="${Su(t)}"]`:`[${es}]`;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)})},Yi=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=Lo(e),r=ar(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,ku(e,n),Lu(e),Pu(e)},ai=(e,t,n,r)=>{let s=ts(e),o=Math.max(0,Math.min(s-1,r));Wy(e,o),Qi(e,t,n)};var Zi=(e,t)=>{var x,C,T,H,k,P,W,A,I,O,D,R;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 _=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");_.setAttribute("data-approval-status",n.status),n.status==="approved"?(_.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",_.style.color="var(--persona-palette-colors-success-700, #15803d)",_.textContent="Approved"):n.status==="denied"?(_.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",_.style.color="var(--persona-palette-colors-error-700, #b91c1c)",_.textContent="Denied"):n.status==="timeout"&&(_.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",_.style.color="var(--persona-palette-colors-warning-700, #b45309)",_.textContent="Timeout"),g.appendChild(_)}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 _=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&&(_.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(_.style.color=r.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=qo(n.parameters),m.appendChild(_)}if(s){let _=h("div","persona-flex persona-gap-2 persona-mt-2");_.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=(k=r==null?void 0:r.approveButtonColor)!=null?k:"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 Re=document.createTextNode((A=r==null?void 0:r.approveLabel)!=null?A:"Approve");z.appendChild(Re);let Ue=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");Ue.type="button",Ue.style.backgroundColor=(I=r==null?void 0:r.denyButtonColor)!=null?I:"transparent",Ue.style.color=(O=r==null?void 0:r.denyButtonTextColor)!=null?O:"var(--persona-feedback-error, #dc2626)",Ue.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ue.setAttribute("data-approval-action","deny");let Fe=be("shield-x",14,(D=r==null?void 0:r.denyButtonTextColor)!=null?D:"var(--persona-feedback-error, #dc2626)",2);Fe&&(Fe.style.marginRight="4px",Ue.appendChild(Fe));let ge=document.createTextNode((R=r==null?void 0:r.denyLabel)!=null?R:"Deny");Ue.appendChild(ge),_.append(z,Ue),m.appendChild(_)}return a.append(i,m),o.appendChild(a),o};var Iu=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 Qs=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 Ys=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 Fy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Oy=new Set(["step_start","execution_start"]),$y=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),_y=new Set(["step_complete","agent_turn_complete"]),jy=new Set(["flow_complete","agent_complete"]),Wu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Hu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Io=(e,t)=>{let n=e[t];return Hu(n)?n:void 0};function el(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ii(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Uy(e,t){return typeof t.type=="string"?t.type:e}function qy(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 zy(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 Ru(e){var r,s,o,a,i;let t=Io(e,"result"),n=[Io(e,"tokens"),Io(e,"totalTokens"),t?Io(t,"tokens"):void 0,Io(e,"usage"),t?Io(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 Vy(e){var n,r,s,o,a;let t=Io(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 Ky(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(t=Ky){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:ii(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(!Hu(n)){Wu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Uy(t,n),s=this.now();if(Fy.has(r)){this.startRun(s);return}if(Oy.has(r)){this.run||this.startRun(s);return}if($y.has(r)){if(!zy(r,n))return;let a=qy(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+el(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ii(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(_y.has(r)){if(!this.run)return;let a=this.run,i=Ru(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+el(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:ii(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(jy.has(r)){if(!this.run)return;let a=this.run,i=Ru(n),d=i!=null?i:a.exactOutputTokens+el(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:ii(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Wu.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=Vy(n);return o!=null?o:r-t.startedAt}};function ns(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Jy={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)"}},Gy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Xy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Qy=100;function Yy(e,t){let n={...Jy,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Gy}function Zy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function eb(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 tb(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 nb(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 rb(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 ob(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function sb(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 ab(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 tl(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");ns(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"?Zy(e.timestamp,n):eb(e.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let P=Yy(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 A=(oe=r.descriptionFields)!=null?oe:Xy,I=tb(e.payload,A),O=null;I&&(O=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),O.textContent=I);let D=h("div","persona-flex-1 persona-min-w-0"),R=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"),_=be("clipboard","12px","currentColor",1.5);return _&&R.appendChild(_),R.addEventListener("click",async Re=>{Re.stopPropagation(),await nb(rb(e)),R.innerHTML="";let Ue=be("check","12px","currentColor",1.5);Ue&&R.appendChild(Ue),setTimeout(()=>{R.innerHTML="";let Fe=be("clipboard","12px","currentColor",1.5);Fe&&R.appendChild(Fe)},1500)}),v.appendChild(x),v.appendChild(T),k&&v.appendChild(k),v.appendChild(W),O&&v.appendChild(O),v.appendChild(D),v.appendChild(R),u.appendChild(v),d&&u.appendChild(ab(e,a,i)),u}}function Bu(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(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let k=g.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>u().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return u();function u(){let k=m.classNames,P=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ns(P,k==null?void 0:k.panel);let W=[],A="",I="",O=null,D=[],R={},_=0,z=_a(),oe=0,Re=0,Ue=!1,Fe=null,ge=!1,ye=0,Le=new Set,Be=new Map,ee="",Pe="",V=null,le,ve,fe,Ce,Ve,X=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");ns(me,k==null?void 0:k.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",X=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"),X.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(X)}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 Ct=h("span","persona-text-xs");Ct.textContent="Copy All",fe.appendChild(Ct),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");ns(ft,k==null?void 0:k.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),Ce=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"),ns(Ce,k==null?void 0:k.searchInput),Ce.type="text",Ce.placeholder="Search event payloads...",Ve=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"),Ve.type="button",Ve.style.display="none";let tt=be("x","12px","currentColor",2);return tt&&Ve.appendChild(tt),ft.appendChild(zt),ft.appendChild(Ce),ft.appendChild(Ve),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=>{A=me,Hn(),F()},onSearchChange:me=>{I=me,Hn(),F()}});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||!X||!te)return;let ne=a();X.textContent=ob(ne);let me=sb(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"),J=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.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");ns(_e,k==null?void 0:k.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(J),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 Ct of ne)me[Ct.type]=(me[Ct.type]||0)+1;let vt=Object.keys(me).sort(),jt=vt.length!==D.length||!vt.every((Ct,ft)=>Ct===D[ft]),Zt=!jt&&vt.some(Ct=>me[Ct]!==R[Ct]),hn=ne.length!==Object.values(R).reduce((Ct,ft)=>Ct+ft,0);if(!jt&&!Zt&&!hn||(D=vt,R=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 Ct of vt){let ft=h("option","");ft.value=Ct,ft.textContent=`${Ct} (${me[Ct]||0})`,ve.appendChild(ft)}St&&vt.includes(St)?ve.value=St:St&&(ve.value="",A="")}else for(let Ct=1;Ct<ve.options.length;Ct++){let ft=ve.options[Ct];ft.textContent=`${ft.value} (${me[ft.value]||0})`}}function Ot(){let ne=t.getAll();if(A&&(ne=ne.filter(me=>me.type===A)),I){let me=I.toLowerCase();ne=ne.filter(vt=>vt.type.toLowerCase().includes(me)||vt.payload.toLowerCase().includes(me))}return ne}function ln(){return A!==""||I!==""}function Hn(){_=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=J.scrollTop,vt=z.isFollowing();ge=!0,z.pause(),F(),J.scrollTop=me,vt&&z.resume(),ge=!1}function qe(){return Fs(J,50)}function F(){Re=Date.now(),Ue=!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="",J.style.display="none"):(ae.style.display="none",J.style.display=""),fe&&(fe.title=ln()?`Copy Filtered (${me})`:"Copy All"),d&&!z.isFollowing()&&me>_&&(oe+=me-_,de.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",_e.style.display=""),_=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=A!==ee||I!==Pe,Ct=Be.size===0&&W.length>0;if(St||Ct||W.length===0){J.innerHTML="",Be.clear();let ft=document.createDocumentFragment();for(let yt=0;yt<W.length;yt++){let zt=tl(W[yt],yt,Zt,m,Le,Xn,o,s);Be.set(W[yt].id,zt),ft.appendChild(zt)}J.appendChild(ft),ee=A,Pe=I,V=null}else{if(V!==null){let yt=Be.get(V);if(yt&&yt.parentNode===J){let zt=W.findIndex(tt=>tt.id===V);if(zt>=0){let tt=tl(W[zt],zt,Zt,m,Le,Xn,o,s);J.insertBefore(tt,yt),yt.remove(),Be.set(V,tt)}}V=null}let ft=new Set(W.map(yt=>yt.id));for(let[yt,zt]of Be)ft.has(yt)||(zt.remove(),Be.delete(yt));for(let yt=0;yt<W.length;yt++){let zt=W[yt];if(!Be.has(zt.id)){let tt=tl(zt,yt,Zt,m,Le,Xn,o,s);Be.set(zt.id,tt),J.appendChild(tt)}}}z.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Ae(){if(Date.now()-Re>=Qy){Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),F();return}Ue||(Ue=!0,Fe=requestAnimationFrame(()=>{Fe=null,F()}))}let De=(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)},Ne=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)),De("check",1500)}catch{De("x",1500)}}},je=()=>{ve&&(A=ve.value,Hn(),F())},dt=()=>{!Ce||!Ve||(Ve.style.display=Ce.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{I=Ce.value,Hn(),F()},150))},rt=()=>{!Ce||!Ve||(Ce.value="",I="",Ve.style.display="none",O&&clearTimeout(O),Hn(),F())},At=()=>{if(ge)return;let ne=J.scrollTop,{action:me,nextLastScrollTop:vt}=ja({following:z.isFollowing(),currentScrollTop:ne,lastScrollTop:ye,nearBottom:qe(),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=Ua({following:z.isFollowing(),deltaY:ne.deltaY,nearBottom:qe(),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&&(J.scrollTop=J.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(),Ce==null||Ce.focus(),Ce==null||Ce.select();return}ne.key==="Escape"&&(Ce&&document.activeElement===Ce?(rt(),Ce.blur(),P.focus()):r&&r())};fe&&fe.addEventListener("click",Ne),ve&&ve.addEventListener("change",je),Ce&&Ce.addEventListener("input",dt),Ve&&Ve.addEventListener("click",rt),J.addEventListener("scroll",At),J.addEventListener("wheel",_t,{passive:!0}),J.addEventListener("click",$t),_e.addEventListener("click",q),P.addEventListener("keydown",Ye);function Dt(){O&&clearTimeout(O),Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),Ue=!1,Be.clear(),fe&&fe.removeEventListener("click",Ne),ve&&ve.removeEventListener("change",je),Ce&&Ce.removeEventListener("input",dt),Ve&&Ve.removeEventListener("click",rt),J.removeEventListener("scroll",At),J.removeEventListener("wheel",_t),J.removeEventListener("click",$t),_e.removeEventListener("click",q),P.removeEventListener("keydown",Ye)}return{element:P,update:Ae,destroy:Dt}}}function Du(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 Nu=(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:()=>Du(e,t)});if(p)return p}return Du(e,t)};var nl=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 nl;lo.register("PersonaArtifactCard",Nu);function ib(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 Fu(e,t){var ve,fe,Ce,Ve;let n=(fe=(ve=e.features)==null?void 0:ve.artifacts)==null?void 0:fe.layout,s=((Ce=n==null?void 0:n.toolbarPreset)!=null?Ce:"default")==="document",o=(Ve=n==null?void 0:n.panePadding)==null?void 0:Ve.trim(),a=e.markdown?jo(e.markdown):null,i=Es(e.sanitize),d=X=>{let te=a?a(X):Uo(X);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"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.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 X;p(),(X=t.onDismiss)==null||X.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"}),k=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,A=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(W&&A&&A.length>0),O=null,D,R=null,_=null;if(s&&(P||W)&&!I){if(D=P?Xa({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 X=be("chevron-down",14,"currentColor",2);X&&D.appendChild(X)}}else s&&I?(O=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=P?Xa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=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(D,R)):s?D=qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=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"}),Re=()=>{var ie,re,Qe;let X=(ie=Be.find(Ie=>Ie.id===ee))!=null?ie:Be[Be.length-1],te=(re=X==null?void 0:X.id)!=null?re:null,se=(X==null?void 0:X.artifactType)==="markdown"&&(Qe=X.markdown)!=null?Qe:"",ue=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:se,jsonPayload:ue,id:te}},Ue=async()=>{var ie;let{markdown:X,jsonPayload:te}=Re(),se=(ie=Be.find(re=>re.id===ee))!=null?ie:Be[Be.length-1],ue=(se==null?void 0:se.artifactType)==="markdown"?X:se?te:"";try{await navigator.clipboard.writeText(ue)}catch{}};if(D.addEventListener("click",async()=>{let X=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(X&&I){let{markdown:te,jsonPayload:se,id:ue}=Re();try{await X({actionId:"primary",artifactId:ue,markdown:te,jsonPayload:se})}catch{}return}await Ue()}),R&&(A!=null&&A.length)){let X=()=>{var se;return(se=m.closest("[data-persona-root]"))!=null?se:document.body},te=()=>{_=ko({items:A.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:ue,jsonPayload:ie,id:re}=Re(),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:R,position:"bottom-right",portal:X()})};m.isConnected?te():requestAnimationFrame(te),R.addEventListener("click",se=>{se.stopPropagation(),_==null||_.toggle()})}z.addEventListener("click",async()=>{var X;try{await((X=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:X.call(n))}catch{}V()}),oe.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let Fe=()=>{s&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),H.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Fe(),V()}),H.addEventListener("click",()=>{x="source",Fe(),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?k.append(O,z,oe):k.append(D,z,oe),g.append(C,ge,k),Fe()):(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 Be=[],ee=null,Pe=!1,V=()=>{var ue,ie,re,Qe;let X=s&&Be.length<=1;ye.classList.toggle("persona-hidden",X),ye.replaceChildren();for(let Ie of Be){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&&Be.find(Ie=>Ie.id===ee)||Be[Be.length-1];if(!te)return;if(s){let Ie=te.artifactType==="markdown"?"MD":(ue=te.component)!=null?ue:"Component",J=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${J} \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 J=se((Qe=te.props)!=null?Qe:{},ce);if(J){Le.appendChild(J);return}}catch{}}Le.appendChild(ib(te))},le=()=>{var te;let X=Be.length>0;if(m.classList.toggle("persona-hidden",!X),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;X&&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(X){var te,se,ue;Be=X.artifacts,ee=(ue=(se=X.selectedId)!=null?se:(te=X.artifacts[X.artifacts.length-1])==null?void 0:te.id)!=null?ue:null,Be.length>0&&(Pe=!0),V(),le()},setMobileOpen(X){Pe=X,!X&&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 Ou(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 lb(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 li(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"),lb(e),Ou(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"),Ou(e,t)}var $u=["panel","seamless"];function ci(e,t){var i,d,l,p,m,g;for(let u of $u)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=$u.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 _u(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 cb(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 db(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 pb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ub(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function ju(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 Uu(e,t,n,r,s,o){let a=cb(s,200),i=ub(t,n,r,200);i=Math.max(a,i);let d=db(o);return d!==null&&(i=Math.min(i,d)),pb(e,a,i)}var qu={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},rl=(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=qu[a])!=null?x:qu.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 A,I;let H=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");H.htmlFor=`${t.id}-${a}-${T.name}`;let k=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,H.appendChild(k);let P=(A=T.type)!=null?A:"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,A;T.preventDefault();let H=(W=n.formEndpoint)!=null?W:"/form",k=new FormData(p),P={};k.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=(A=O.message)!=null?A:"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 ol=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()}},di=new ol;var zu=()=>{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 mb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},gb=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},pi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=mb(e),n=gb(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}},sl=e=>typeof e=="string"?e:e==null?"":String(e),rs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:sl(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=sl(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:sl(n.text)}}},Vu=e=>Array.isArray(e)?e.map(t=>String(t)):[],ui=e=>{let t=new Set(Vu(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Vu(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 fb=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}},hb=e=>e.map(t=>({...t,streaming:!1})),yb=e=>e.map(t=>({...t,status:"complete"})),al=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?fb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?hb(n.messages):void 0,artifacts:n.artifacts?yb(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 bb,STR as xb,OBJ as vb}from"partial-json";function Cb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function wb(e,t){if(!Cb(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 il(){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=bb(n,xb|vb),o=wb(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ab(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ll(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 Sb(){let e=il();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ku(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 cl(e){let t=Ku(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 dl(e){let t=Ku(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 Tb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function pl(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=Tb}=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 A=1;A<=5;A++){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",`${A} star${A>1?"s":""}: ${l[A-1]}`),I.title=l[A-1],I.dataset.rating=String(A),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=A,T.forEach((O,D)=>{let R=D<A;O.classList.toggle("selected",R),O.setAttribute("aria-checked",D===A-1?"true":"false")})}),T.push(I),C.appendChild(I)}g.appendChild(C);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),g.appendChild(A)}let k=document.createElement("div");k.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 A=(H==null?void 0:H.value.trim())||void 0;await t(m,A),p.remove()}catch(A){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),k.appendChild(P),k.appendChild(W),g.appendChild(k),p.appendChild(g),p}function ul(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 k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=p,H.appendChild(k),H.appendChild(P);let W=document.createElement("div");W.className="persona-feedback-numbers";let A=[];for(let _=0;_<=10;_++){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 ${_} out of 10`),z.textContent=String(_),z.dataset.rating=String(_),_<=6?z.classList.add("persona-feedback-detractor"):_<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{g=_,A.forEach((oe,Re)=>{oe.classList.toggle("selected",Re===_),oe.setAttribute("aria-checked",Re===_?"true":"false")})}),A.push(z),W.appendChild(z)}T.appendChild(H),T.appendChild(W),u.appendChild(T);let I=null;if(d){let _=document.createElement("div");_.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"),_.appendChild(I),u.appendChild(_)}let O=document.createElement("div");O.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),m.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(g===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let _=(I==null?void 0:I.value.trim())||void 0;await t(g,_),m.remove()}catch(_){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),O.appendChild(D),O.appendChild(R),u.appendChild(O),m.appendChild(u),m}var os="persona-chat-history",Eb=30*1e3,Mb={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function kb(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=Mb[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 mi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Lb(e){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 Pb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var ml=e=>!e||typeof e!="object"?{}:{...e},Ju=e=>e.map(t=>({...t,streaming:!1})),Gu=(e,t,n)=>{let r=e!=null&&e.markdown?jo(e.markdown):null,s=Es(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=Uo(a),s?s(d):d}};function Xu(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 gl=(e,t,n)=>{var 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,Cc,wc,Ac,Sc;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=Wi(t),s=di.getForInstance(r.plugins);r.components&&lo.registerAll(r.components);let o=zu(),i=r.persistState===!1?null:(Il=r.storageAdapter)!=null?Il:al(),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=ml(y.metadata)),(Wl=y.messages)!=null&&Wl.length&&(r={...r,initialMessages:y.messages}),(Rl=y.artifacts)!=null&&Rl.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Hl=y.selectedArtifactId)!=null?Hl: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:{}});(Bl=c.messages)!=null&&Bl.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:{},Ho()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[pi],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[rs.message,rs.messageAndClick],C=ui({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let T=(Nl=(Dl=r.launcher)==null?void 0:Dl.enabled)!=null?Nl:!0,H=(Ol=(Fl=r.launcher)==null?void 0:Fl.autoExpand)!=null?Ol:!1,k=($l=r.autoFocusInput)!=null?$l:!1,P=H,W=T,A=(jl=(_l=r.layout)==null?void 0:_l.header)==null?void 0:jl.layout,I=!1,O=()=>no(r),D=()=>T||O(),R=O()?!1:T?H:!0,_=!1,z=null,oe=()=>{_=!0,z&&clearTimeout(z),z=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},Re=Gu(r,C,oe),Ue=(ql=(Ul=r.features)==null?void 0:Ul.showReasoning)!=null?ql:!0,Fe=(Vl=(zl=r.features)==null?void 0:zl.showToolCalls)!=null?Vl:!0,ge=(Jl=(Kl=r.features)==null?void 0:Kl.showEventStreamToggle)!=null?Jl:!1,ye=(Xl=(Gl=r.features)==null?void 0:Gl.scrollToBottom)!=null?Xl:{},Be=`${(Yl=typeof r.persistState=="object"?(Ql=r.persistState)==null?void 0:Ql.keyPrefix:void 0)!=null?Yl:"persona-"}event-stream`,ee=ge?new Ys(Be):null,Pe=(tc=(ec=(Zl=r.features)==null?void 0:Zl.eventStream)==null?void 0:ec.maxEvents)!=null?tc:2e3,V=ge?new Qs(Pe,ee):null,le=ge?new Zs:null,ve=null,fe=!1,Ce=null,Ve=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 X={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=(nc=r.statusIndicator)!=null?nc:{},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}=du(r),Ie=pu(r,D()),{container:ce,body:J,messagesWrapper:_e,suggestions:Et,textarea:de,sendButton:ae,sendButtonWrapper:Mn,composerForm:Ot,statusText:ln,introTitle:Hn,introSubtitle:Xn,closeButton:qe,iconHolder:F,headerTitle:Ae,headerSubtitle:De,header:Ne,footer:je,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"),J.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 Ct=h("span","persona-flex persona-items-center"),ft=h("span","");St.append(Ct,ft),ce.appendChild(St);let yt=()=>{let f=je.style.display==="none"?0:je.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"),Ct.innerHTML="";let f=be(Zt(),"14px","currentColor",2);f?(Ct.appendChild(f),Ct.style.display=""):Ct.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:D()});return Xo(ce,f,r),f.header},onClose:()=>Rt(!1,"user")});if(c){let f=ce.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Ne=c)}}let yn=()=>{var f,y,b,M;if(!V)return;if(fe=!0,!ve&&V&&(ve=Bu({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>Dn(),config:r,plugins:s,getThroughput:()=>{var N;return(N=le==null?void 0:le.getMetric())!=null?N:{status:"idle"}}})),ve&&(J.style.display="none",(f=je.parentNode)==null||f.insertBefore(ve.element,je),ve.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${En.actionIconColor}`;let N=(M=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:M.toggleButtonActive;N&&N.split(/\s+/).forEach($=>$&&ut.classList.add($))}let c=()=>{if(!fe)return;let N=Date.now();N-Ve>=200&&(ve==null||ve.update(),Ve=N),Ce=requestAnimationFrame(c)};Ve=0,Ce=requestAnimationFrame(c),Wr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Dn=()=>{var c,f,y;if(fe){if(fe=!1,ve&&ve.element.remove(),J.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))}Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Wr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ge){let c=(oc=(rc=r.features)==null?void 0:rc.eventStream)==null?void 0:oc.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,N=b||M;N&&N.parentNode===Ne?Ne.insertBefore(ut,N):Ne.appendChild(ut),ut.addEventListener("click",()=>{fe?Dn():yn()})}let xr=c=>{var b,M,N;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 $=c.querySelector("[data-persona-composer-form]");$!=null&&$.parentNode?$.parentNode.insertBefore(y,$):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let $=h("input");$.type="file",$.accept=((b=f.allowedTypes)!=null?b:Nr).join(","),$.multiple=((M=f.maxFiles)!=null?M:4)>1,$.style.display="none",$.setAttribute("aria-label",(N=f.buttonTooltipText)!=null?N:"Attach files"),c.appendChild($)}},Nn=s.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=r.composer,f=Nn.renderComposer({config:r,defaultRenderer:()=>Ks({config:r}).footer,onSubmit:y=>{var $;if(!S||S.isStreaming())return;let b=y.trim(),M=($=tt==null?void 0:tt.hasAttachments())!=null?$:!1;if(!b&&!M)return;fs();let N;M&&(N=[],N.push(...tt.getContentParts()),b&&N.push(Wa(b))),S.sendMessage(b,{contentParts:N}),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:((sc=r.voiceRecognition)==null?void 0:sc.enabled)===!0?()=>{Bn==null||Bn()}:void 0});f&&(je.replaceWith(f),je=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]"),N=c.querySelector("[data-persona-composer-status]");f&&(Ot=f),y&&(de=y),b&&(ae=b),M&&(q=M,$t=M.parentElement),N&&(ln=N);let $=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(Et=$);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 B=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(dt=B)};xr(je),po(je);let kn=(dc=(ac=r.layout)==null?void 0:ac.contentMaxWidth)!=null?dc:O()?(cc=(lc=(ic=r.launcher)==null?void 0:ic.composerBar)==null?void 0:lc.contentMaxWidth)!=null?cc:"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"),(pc=r.attachments)!=null&&pc.enabled&&ne&&me){tt=Jo.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=Xu(c);ce.appendChild(f)}(()=>{var b,M;let c=(M=(b=r.layout)==null?void 0:b.slots)!=null?M:{},f=N=>{switch(N){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=(N,$)=>{var U;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Ne.insertBefore($,Ne.firstChild);else if(N==="header-right")Ne.appendChild($);else{let B=Ne.querySelector(".persona-flex-col");B?(U=B.parentNode)==null||U.insertBefore($,B.nextSibling):Ne.appendChild($)}break;case"body-top":{let B=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith($):J.insertBefore($,J.firstChild);break}case"body-bottom":J.appendChild($);break;case"footer-top":Et.replaceWith($);break;case"footer-bottom":ln.replaceWith($);break;default:break}};for(let[N,$]of Object.entries(c))if($)try{let U=$({config:r,defaultContent:()=>f(N)});U&&y(N,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,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 N=y.getAttribute("data-bubble-type");N==="reasoning"?(Yo.has(M)?Yo.delete(M):Yo.add(M),hu(M,b)):N==="tool"&&(Zo.has(M)?Zo.delete(M):Zo.add(M),yu(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 $;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 N=y.getAttribute("data-action");if(N==="copy"){let B=S.getMessages().find(we=>we.id===M);if(B&&X.onCopy){let we=B.content||"";navigator.clipboard.writeText(we).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 Y=be("copy",14,"currentColor",2);Y&&(y.innerHTML="",y.appendChild(Y))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),X.onCopy(B)}}else if(N==="upvote"||N==="downvote"){let B=(($=Er.get(M))!=null?$:null)===N,we=N==="upvote"?"thumbs-up":"thumbs-down";if(B){Er.delete(M),y.classList.remove("persona-message-action-active");let pe=be(we,14,"currentColor",2);pe&&(y.innerHTML="",y.appendChild(pe))}else{let pe=N==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${pe}"]`);if(Y){Y.classList.remove("persona-message-action-active");let Xe=be(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(Y.innerHTML="",Y.appendChild(Xe))}Er.set(M,N),y.classList.add("persona-message-action-active");let he=be(we,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 Oe=S.getMessages().find(nt=>nt.id===M);Oe&&X.onFeedback&&X.onFeedback({type:N,messageId:Oe.id,message:Oe})}}}),_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 N=y.getAttribute("data-approval-action");if(!N)return;let $=N==="approve"?"approved":"denied",B=S.getMessages().find(pe=>pe.id===M);if(!(B!=null&&B.approval))return;let we=b.querySelector("[data-approval-buttons]");we&&we.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?S.resolveWebMcpApproval(M,$):S.resolveApproval(B.approval,$)});let bt=null,Fn=null,On={artifacts:[],selectedId:null},bn=!1,Lt={current:null};_e.addEventListener("click",c=>{var Y,he,Se,Oe,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=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Se.call(he,{type:"download",artifactId:b}))===!0)return;let N=S.getArtifactById(b),$=N==null?void 0:N.markdown,U=(N==null?void 0:N.title)||"artifact";if(!$){let Xe=y.closest("[data-open-artifact]"),at=Xe==null?void 0:Xe.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Me=S.getMessages().find(ze=>ze.id===it);if(Me!=null&&Me.rawContent)try{let ze=JSON.parse(Me.rawContent);$=(Oe=ze==null?void 0:ze.props)==null?void 0:Oe.markdown,U=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||U}catch{}}}if(!$)return;let B=new Blob([$],{type:"text/markdown"}),we=URL.createObjectURL(B),pe=document.createElement("a");pe.href=we,pe.download=`${U}.md`,pe.click(),URL.revokeObjectURL(we)}),_e.addEventListener("click",c=>{var N,$,U;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((U=($=(N=r.features)==null?void 0:N.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:U.call($,{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,B,we,pe;let b=f.trim();if(!b||!Lt.current)return;let M=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",N=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:b,answers:y.structured,values:(B=y.values)!=null?B:y.source==="multi"?b.split(", "):[b],isFreeText:N,source:y.source},bubbles:!0,composed:!0})),Po(Yn,M);let $=Lt.current.getMessages().find(Y=>{var he;return((he=Y.toolCall)==null?void 0:he.id)===M});(we=$==null?void 0:$.agentMetadata)!=null&&we.awaitingLocalTool?Lt.current.resolveAskUserQuestion($,(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(N=>{var $;return(($=N.toolCall)==null?void 0:$.id)===y});b&&f.persistAskUserQuestionProgress(b,{answers:si(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,N,$;if(((N=(M=r.features)==null?void 0:M.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let f=ar(c),y=ts(c);if(f>=y-1)return;let b=($=Lt.current)==null?void 0:$.getMessages().find(U=>{var B;return((B=U.toolCall)==null?void 0:B.id)===c.getAttribute("data-tool-call-id")});b&&(ai(c,b,r,f+1),$n(c))};Yn.addEventListener("click",c=>{var N,$,U,B,we,pe,Y,he,Se,Oe,nt,Xe,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=(N=b.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ke},bubbles:!0,composed:!0})),Po(Yn,ke);let Me=($=Lt.current)==null?void 0:$.getMessages().find(ze=>{var E;return((E=ze.toolCall)==null?void 0:E.id)===ke});(U=Me==null?void 0:Me.agentMetadata)!=null&&U.awaitingLocalTool&&((B=Lt.current)==null||B.markAskUserQuestionResolved(Me),(we=Lt.current)==null||we.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",ze=ao(b);if(ze&&Me){let E=Lo(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(ze){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=Yi(b).length===0);return}Zn(b,ke,{source:"pick",values:[ke]});return}if(M==="submit-multi"){let ke=Yi(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=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",Me=Lt.current.getMessages().find(Je=>{var xe;return((xe=Je.toolCall)==null?void 0:xe.id)===ke});if(!Me)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),E=(Se=(he=ze==null?void 0:ze.value)==null?void 0:he.trim())!=null?Se:"";if(E){let Je=Lo(b)[ar(b)];(typeof Je!="string"||Je!==E)&&io(b,E)}let Te=M==="next"?1:-1,He=ar(b)+Te;ai(b,Me,r,He),$n(b);return}if(M==="submit-all"){if(!Lt.current)return;let ke=(Oe=b.getAttribute("data-tool-call-id"))!=null?Oe:"",Me=Lt.current.getMessages().find(Je=>{var xe;return((xe=Je.toolCall)==null?void 0:xe.id)===ke});if(!Me)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),E=(Xe=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?Xe:"";E&&io(b,E);let Te=si(b,Me);Lt.current.persistAskUserQuestionProgress(Me,{answers:Te,currentIndex:ar(b)});let He=$r(Te);Zn(b,He||"(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 ze=ao(b),E=ar(b),Te=ts(b),He=E>=Te-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ke},bubbles:!0,composed:!0})),Po(Yn,ke),(it=Me.agentMetadata)!=null&&it.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Me),Lt.current.resolveAskUserQuestion(Me,"(dismissed)"));return}io(b,"");let Je=b.querySelector('[data-ask-free-text-input="true"]');if(Je&&(Je.value=""),He){let xe=si(b,Me),kt=$r(xe);Zn(b,kt||"(skipped)",{source:"submit-all",structured:xe});return}ai(b,Me,r,E+1),$n(b);return}}),Yn.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let y=c.target;if(!((N=y.matches)!=null&&N.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),N=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];N&&(c.preventDefault(),N.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 $;if(!_n||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=(($=e.ownerDocument.defaultView)!=null?$: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 N=b.offsetWidth-M/2;Wt.style.left=`${Math.max(0,N)}px`},vr=()=>{},jn=()=>{var y,b,M,N,$;if(!bt||!ir(r))return;li(e,r),ci(e,r),vr();let c=(N=(M=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:M.narrowHostMaxWidth)!=null?N: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"),($=bt.backdrop)==null||$.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=Fu(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,N,$;if(!_n||!bt)return;if(!(((N=(M=(b=r.features)==null?void 0:b.artifacts)==null?void 0:M.layout)==null?void 0:N.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 B=e.ownerDocument,we=($=B.defaultView)!=null?$:window,pe=Y=>{var at,it;if(!bt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||we.innerWidth<=640)return;Y.preventDefault(),kr();let he=Y.clientX,Se=bt.element.getBoundingClientRect().width,Oe=(it=(at=r.features)==null?void 0:at.artifacts)==null?void 0:it.layout,nt=ke=>{let Me=_n.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),E=ze?0:ju(_n,we),Te=ze?0:U.getBoundingClientRect().width||6,He=Se-(ke.clientX-he),Je=Uu(He,Me,E,Te,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);bt.element.style.width=`${Je}px`,bt.element.style.maxWidth="none",Ur()},Xe=()=>{B.removeEventListener("pointermove",nt),B.removeEventListener("pointerup",Xe),B.removeEventListener("pointercancel",Xe),er=null;try{U.releasePointerCapture(Y.pointerId)}catch{}};er=Xe,B.addEventListener("pointermove",nt),B.addEventListener("pointerup",Xe),B.addEventListener("pointercancel",Xe);try{U.setPointerCapture(Y.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 we,pe,Y,he,Se,Oe,nt,Xe,at,it,ke,Me,ze,E;if(!T||!bt||((pe=(we=r.launcher)==null?void 0:we.sidebarMode)!=null?pe:!1)||an(r)&&yr(r).reveal==="emerge")return;let b=(Y=e.ownerDocument.defaultView)!=null?Y:window,M=(Se=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?Se:!0,N=(nt=(Oe=r.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?nt:640;if(M&&b.innerWidth<=N||!_u(r,T))return;let $=(it=(at=(Xe=r.launcher)==null?void 0:Xe.width)!=null?at:r.launcherWidth)!=null?it:sr,U=(E=(ze=(Me=(ke=r.features)==null?void 0:ke.artifacts)==null?void 0:Me.layout)==null?void 0:ze.expandedPanelWidth)!=null?E:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!bn?(re.style.width=U,re.style.maxWidth=U):(re.style.width=$,re.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{jn()}),Fn.observe(re))}else re.appendChild(ce),O()&&Qe&&(Ie.peekBanner&&Qe.appendChild(Ie.peekBanner),Qe.appendChild(je));e.appendChild(ie),Qe&&e.appendChild(Qe);let lr=()=>{var Je,xe,kt,st,Qt,cn,It,wn,dn,Ze,lt,An,un,yo,bo,xo,$o,_o,Vt,vo,Zr,ht,Pn,Br,Sn,In,Ht,Ut;if(O()){re.style.width="100%",re.style.maxWidth="100%";let Bt=(xe=(Je=r.launcher)==null?void 0:Je.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=Ds(r),Dr=(Co,Ca)=>{var As;return Co==null||Co===""?Ca:(As=Go(Ar,Co))!=null?As:Co},ba="1px solid var(--persona-border)",xa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",va="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,ba),ce.style.borderRadius=Dr(tn==null?void 0:tn.borderRadius,va),ce.style.boxShadow=Dr(tn==null?void 0:tn.shadow,xa),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=(wn=r.launcher)==null?void 0:wn.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,N=Ds(r),$=(Bt,Kt)=>{var Wn;return Bt==null||Bt===""?Kt:(Wn=Go(N,Bt))!=null?Wn:Bt},U=(un=e.ownerDocument.defaultView)!=null?un:window,B=(bo=(yo=r.launcher)==null?void 0:yo.mobileFullscreen)!=null?bo:!0,we=($o=(xo=r.launcher)==null?void 0:xo.mobileBreakpoint)!=null?$o:640,pe=U.innerWidth<=we,Y=B&&pe&&T,he=(Vt=(_o=r.launcher)==null?void 0:_o.position)!=null?Vt:"bottom-left",Se=he==="bottom-left"||he==="top-left",Oe=(Zr=(vo=r.launcher)==null?void 0:vo.zIndex)!=null?Zr:fn,nt=f||Y?"none":"1px solid var(--persona-border)",Xe=Y?"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&&!Y&&(Xe="none",nt="none");let at=f||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=$(M==null?void 0:M.border,nt),ke=$(M==null?void 0:M.shadow,Xe),Me=$(M==null?void 0:M.borderRadius,at),ze=J.scrollTop;e.style.cssText="",ie.style.cssText="",re.style.cssText="",ce.style.cssText="",J.style.cssText="",je.style.cssText="";let E=()=>{var Kt;if(ze<=0)return;((Kt=J.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(J.scrollTop===ze)return;let Wn=J.scrollHeight-J.clientHeight;Wn<=0||(J.scrollTop=Math.min(ze,Wn))})};if(Y){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 Ws=e=>({isError:!0,content:[{type:"text",text:e}]
37
37
  padding: 0 !important;
38
38
  display: flex !important;
39
39
  flex-direction: column !important;
40
- z-index: ${Oe} !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 Ws=e=>({isError:!0,content:[{type:"text",text:e}]
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 Ws=e=>({isError:!0,content:[{type:"text",text:e}]
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",je.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,He=Te!=null?Te:sr;if(!f&&!c)b&&y?(re.style.width="100%",re.style.maxWidth="100%"):(re.style.width=He,re.style.maxWidth=He);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&&!Y&&(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",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",je.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: ${Oe} !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 Ws=e=>({isError:!0,content:[{type:"text",text:e}]
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 Ws=e=>({isError:!0,content:[{type:"text",text:e}]
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
- `,je.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(),Mo(e,r),li(e,r),ci(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(()=>{Ce!==null&&(cancelAnimationFrame(Ce),Ce=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=Bi(()=>{Mo(e,r)}))};qr(),gt.push(()=>{Un&&(Un(),Un=null)});let tr=(uc=r.features)==null?void 0:uc.streamAnimation;if(tr!=null&&tr.type&&tr.type!=="none"){let c=_s(tr.type,tr.plugins);c&&(Fi(c,e),gt.push(()=>ou(e)))}let cr=Iu(Et),qn=null,S,zn=!1,dr=Yp(),Lr=new Map,Cr=new Map,as=0,pr=_a(),ur=0,mr=null,Pr=!1,uo=!1,ta=4,is=24,na=80,Ro=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ls=(gc=(mc=r.voiceRecognition)==null?void 0:mc.autoResume)!=null?gc:!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}}))},ra=()=>{var b,M;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=ml(d.voiceState),f=!!c.active,y=Number((M=c.timestamp)!=null?M:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-y<Eb&&setTimeout(()=>{var N,$;mt.active||(mt.manuallyDeactivated=!1,(($=(N=r.voiceRecognition)==null?void 0:N.provider)==null?void 0:$.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("restore"),S.isVoiceActive()&&j()}):ho("restore"))},1e3)},oa=()=>S?Ju(S.getMessages()).filter(c=>!c.__skipPersist):[];function Ho(c){if(!(i!=null&&i.save))return;let y={messages:c?Ju(c):S?oa():[],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,sa=()=>ie.querySelector("#persona-scroll-container")||J,mo=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),Pr=!1},cs=()=>{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=Ns(J)>0;St.style.display=pr.isFollowing()||!c?"none":""},ds=()=>{pr.pause()&&(cs(),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()&&aa(sa(),c?220:140)})))},aa=(c,f=500)=>{let y=c.scrollTop,b=Ns(c),M=b-y;if(Math.abs(M)<1){ur=c.scrollTop;return}if(Math.abs(M)>=na){mo(),Pr=!0,c.scrollTop=b,ur=c.scrollTop,Pr=!1;return}mo();let N=performance.now();Pr=!0;let $=B=>1-Math.pow(1-B,3),U=B=>{if(!pr.isFollowing()){mo();return}let we=Ns(c);we!==b&&(b=we,M=b-y);let pe=B-N,Y=Math.min(pe/f,1),he=$(Y),Se=y+M*he;c.scrollTop=Se,ur=c.scrollTop,Y<1?Ir=requestAnimationFrame(U):(c.scrollTop=b,ur=c.scrollTop,Ir=null,Pr=!1)};Ir=requestAnimationFrame(U)},ia=c=>{let f=new Map;c.forEach(y=>{let b=Ro.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}))}),Ro.clear(),f.forEach((y,b)=>{Ro.set(b,y)})},go=(c,f,y)=>{var Xe,at,it,ke,Me,ze;let b=document.createElement("div"),N=(()=>{var Te;let E=s.find(He=>He.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((Te=r.loadingIndicator)!=null&&Te.render)return r.loadingIndicator.render})(),$=(E,Te)=>Te==null?!1:typeof Te=="string"?(E.textContent=Te,!0):(E.appendChild(Te),!0),U=new Set,B=new Set,we=s.some(E=>E.renderAskUserQuestion),pe=[],Y=[],he=r.enableComponentStreaming!==!1;if(f.forEach(E=>{var wn,dn,Ze,lt,An,un,yo,bo,xo,$o,_o,Vt,vo,Zr;U.add(E.id);let Te=we&&oo(E),He=!Te&&E.role==="assistant"&&!E.variant&&he&&cl(E);if(!He&&Cr.has(E.id)){let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),Cr.delete(E.id)}let Je=oo(E)?`:${(wn=E.agentMetadata)!=null&&wn.askUserQuestionAnswered?"a":"u"}:${(dn=E.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(E.agentMetadata.askUserQuestionAnswers).length:0}`:"",xe=Qp(E,as)+Je,kt=Te||He?null:Zp(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)&&(B.add(E.toolCall.id),Xs(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){(($o=E.agentMetadata)==null?void 0:$o.awaitingLocalTool)===!0&&!((_o=E.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(B.add(E.toolCall.id),Xs(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)&&(B.add(E.toolCall.id),Xs(E,r,Ie.composerOverlay));return}}else if(Qt)if(E.variant==="reasoning"&&E.reasoning&&Qt.renderReasoning){if(!Ue)return;st=Qt.renderReasoning({message:E,defaultRenderer:()=>zi(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Qt.renderToolCall){if(!Fe)return;st=Qt.renderToolCall({message:E,defaultRenderer:()=>Vi(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Qt.renderApproval){if(r.approval===!1)return;st=Qt.renderApproval({message:E,defaultRenderer:()=>Zi(E,r),config:r})}else Qt.renderMessage&&(st=Qt.renderMessage({message:E,defaultRenderer:()=>{let ht=Js(E,y,cn,r.messageActions,X,{loadingIndicatorRenderer:N,widgetConfig:r});return E.role!=="user"&&rl(ht,E,r,S),ht},config:r}));if(!st&&He){let ht=dl(E);if(ht){let Pn=Cr.get(E.id),Br=Pn!==xe,Sn=r.wrapComponentDirectiveInBubble!==!1,In=null;if(Br){let Ht=ll(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),Y.push({messageId:E.id,fingerprint:xe,bubble:In});return}}}if(!st)if(E.variant==="reasoning"&&E.reasoning){if(!Ue)return;st=zi(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!Fe)return;st=Vi(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;st=Zi(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=Js(E,y,ht,r.messageActions,X,{loadingIndicatorRenderer:N,widgetConfig:r}),E.role!=="user"&&st&&rl(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),eu(dr,E.id,xe,It),b.appendChild(It)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let He=Te.getAttribute("data-persona-ask-sheet-for");He&&!B.has(He)&&Po(Ie.composerOverlay,He)}),(at=(Xe=r.features)==null?void 0:Xe.toolCallDisplay)!=null&&at.grouped){let E=[],Te=[];f.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&Fe){Te.push(He);return}Te.length>1&&E.push(Te),Te=[]}),Te.length>1&&E.push(Te),E.forEach((He,Je)=>{var dn,Ze;let xe=He.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-${Je}-${He[0].id}`,kt.setAttribute("data-wrapper-id",`tool-group-${Je}-${He[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 ${He.length} tools`,It=(Ze=(dn=r.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Ze.call(dn,{messages:He,toolCalls:He.map(lt=>lt.toolCall).filter(lt=>!!lt),defaultSummary:cn,config:r});$(Qt,It)||(Qt.textContent=cn);let wn=document.createElement("div");wn.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Qt,wn),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),wn.appendChild(un)})})}tu(dr,U);let Se=f.some(E=>E.role==="assistant"&&E.streaming),Oe=f[f.length-1],nt=(Oe==null?void 0:Oe.role)==="assistant"&&!Oe.streaming&&Oe.variant!=="approval";if(zn&&f.some(E=>E.role==="user")&&!Se&&!nt){let E={config:r,streaming:!0,location:"standalone",defaultRenderer:Qo},Te=s.find(Je=>Je.renderLoadingIndicator),He=null;if(Te!=null&&Te.renderLoadingIndicator&&(He=Te.renderLoadingIndicator(E)),He===null&&((it=r.loadingIndicator)!=null&&it.render)&&(He=r.loadingIndicator.render(E)),He===null&&(He=Qo()),He){let Je=document.createElement("div"),xe=((ke=r.loadingIndicator)==null?void 0:ke.showBubble)!==!1;Je.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(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.appendChild(He);let kt=document.createElement("div");kt.className="persona-flex",kt.id="wrapper-typing-indicator",kt.setAttribute("data-wrapper-id","typing-indicator"),kt.appendChild(Je),b.appendChild(kt)}}if(!zn&&f.length>0){let E=f[f.length-1],Te={config:r,lastMessage:E,messageCount:f.length},He=s.find(xe=>xe.renderIdleIndicator),Je=null;if(He!=null&&He.renderIdleIndicator&&(Je=He.renderIdleIndicator(Te)),Je===null&&((Me=r.loadingIndicator)!=null&&Me.renderIdle)&&(Je=r.loadingIndicator.renderIdle(Te)),Je){let xe=document.createElement("div"),kt=((ze=r.loadingIndicator)==null?void 0:ze.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(Je);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(Oa(c,b),pe.length>0)for(let{messageId:E,fingerprint:Te,bubble:He}of pe){let Je=c.querySelector(`#wrapper-${E}`);Je&&He!==null&&(Je.replaceChildren(He),Je.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(Y.length>0)for(let{messageId:E,fingerprint:Te,bubble:He}of Y){let Je=c.querySelector(`#wrapper-${E}`);Je&&He!==null&&(Je.replaceChildren(He),Je.setAttribute("data-bubble-fp",Te),Cr.set(E,Te))}if(Cr.size>0)for(let E of Cr.keys())U.has(E)||Cr.delete(E)},Kr=null,la=()=>{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)},ps=()=>{var f;if(!Kr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Kr,!0),Kr=null};gt.push(()=>ps());let Jr=null,ca=()=>{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)},us=()=>{var f;if(!Jr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Jr,!0),Jr=null};gt.push(()=>us());let Gr=!1,ms=new Set,da=()=>{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(R){c.classList.remove("persona-pill-peek--visible");return}let y=(at=S==null?void 0:S.getMessages())!=null?at:[],b;for(let ze=y.length-1;ze>=0;ze--){let E=y[ze];if(E.role==="assistant"&&E.content){b=E;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let M=b.content,N=!!b.streaming,$=da(),U=qa($),B=U.type!=="none"?_s(U.type,$==null?void 0:$.plugins):null,we=((it=B==null?void 0:B.isAnimating)==null?void 0:it.call(B,b))===!0,pe=B!==null&&(N||we);pe&&B&&!ms.has(B.name)&&(Fi(B,e),ms.add(B.name));let Y=pe&&(B!=null&&B.containerClass)?B.containerClass:null,he=(ke=f.dataset.personaPeekStreamClass)!=null?ke:null;he&&he!==Y&&(f.classList.remove(he),delete f.dataset.personaPeekStreamClass),Y&&he!==Y&&(f.classList.add(Y),f.dataset.personaPeekStreamClass=Y),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?za(M,U.buffer,B,b,N):M;if(pe&&U.placeholder==="skeleton"&&N&&(!Se||!Se.trim())){let ze=document.createElement("div"),E=Us();E.classList.add("persona-pill-peek__skeleton"),ze.appendChild(E),Oa(f,ze)}else{let ze=Math.max(0,Se.length-100),E=Se.length>100?Se.slice(-100):Se,Te=Uo(E);if(!pe||!B){let He=Se.length>100?`\u2026${E}`:E;f.textContent!==He&&(f.textContent=He)}else{let He=Te;(B.wrap==="char"||B.wrap==="word")&&(He=js(Te,B.wrap,`peek-${b.id}`,{skipTags:B.skipTags,startIndex:ze}));let Je=document.createElement("div");if(Je.innerHTML=He,B.useCaret&&E.length>0){let xe=Va(),kt=Je.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=kt[kt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(xe,st.nextSibling):Je.appendChild(xe)}Oa(f,Je),(Me=B.onAfterRender)==null||Me.call(B,{container:f,bubble:c,messageId:b.id,message:b,speed:U.speed,duration:U.duration})}}let Xe=zn||Gr;c.classList.toggle("persona-pill-peek--visible",Xe)};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 pa=c=>{var he,Se,Oe,nt,Xe,at,it,ke;let f=(Se=(he=r.launcher)==null?void 0:he.composerBar)!=null?Se:{},y=(Oe=f.expandedSize)!=null?Oe:"anchored",b=(nt=f.bottomOffset)!=null?nt:"16px",M=f.collapsedMaxWidth,N=(Xe=f.expandedMaxWidth)!=null?Xe:"880px",$=(at=f.expandedTopOffset)!=null?at:"5vh",U=(it=f.modalMaxWidth)!=null?it:"880px",B=(ke=f.modalMaxHeight)!=null?ke:"min(90vh, 800px)",we="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",Y=ie.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",Qe){let Me=Qe.style;Me.bottom=b,Me.width=M!=null?M:""}if(c&&y!=="fullscreen"){if(y==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=U,Y.maxWidth=we,Y.maxHeight=B,Y.height=B;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${pe})`,Y.top=$,Y.width=N,Y.maxWidth=we}},Xr=()=>{var B,we,pe,Y,he,Se,Oe,nt;if(!D())return;if(O()){let at=(pe=((we=(B=r.launcher)==null?void 0:B.composerBar)!=null?we:{}).expandedSize)!=null?pe:"anchored",it=R?"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"),pa(R),ce.style.display=R?"flex":"none",lr(),R?(la(),ca()):(ps(),us()),Rr();return}let c=an(r),f=(Y=e.ownerDocument.defaultView)!=null?Y:window,y=(Se=(he=r.launcher)==null?void 0:he.mobileBreakpoint)!=null?Se:640,b=(nt=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?nt:!0,M=f.innerWidth<=y,N=b&&M&&T,$=yr(r).reveal;R?(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":Ge&&(Ge.style.display="none")):(c?c&&($==="overlay"||$==="push")&&!N?(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":"":Ge&&(Ge.style.display=c?"none":""))},Rt=(c,f="user")=>{var N,$;if(!D()||R===c)return;let y=R;R=c,Xr();let b=(()=>{var Oe,nt,Xe,at,it,ke,Me,ze,E,Te;let U=(nt=(Oe=r.launcher)==null?void 0:Oe.sidebarMode)!=null?nt:!1,B=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,we=(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,Y=B.innerWidth<=pe,he=an(r)&&we&&Y,Se=O()&&((Te=(E=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:E.expandedSize)!=null?Te:"fullscreen")==="fullscreen";return U||we&&Y&&T||he||Se})();if(R&&b){if(!Jt){let U=e.getRootNode(),B=U instanceof ShadowRoot?U.host:e.closest(".persona-host");B&&(Jt=Oi(B,($=(N=r.launcher)==null?void 0:N.zIndex)!=null?$:fn))}Gt||(Gt=$i(e.ownerDocument))}else R||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null);R&&(Pt(),Vr(!0));let M={open:R,source:f,timestamp:Date.now()};R&&!y?o.emit("widget:opened",M):!R&&y&&o.emit("widget:closed",M),o.emit("widget:state",{open:R,launcherEnabled:T,voiceActive:mt.active,streaming:S.isStreaming()})},Bo=c=>{_t(c?"stop":"send"),q&&(q.disabled=c),cr.buttons.forEach(f=>{f.disabled=c}),je.dataset.personaComposerStreaming=c?"true":"false",je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Do=()=>{mt.active||de&&de.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Do(),200)});let gs=()=>{var y,b,M,N,$,U,B,we,pe,Y,he;Hn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",Xn.textContent=(N=(M=r.copy)==null?void 0:M.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",de.placeholder=(U=($=r.copy)==null?void 0:$.inputPlaceholder)!=null?U:"How can I help...";let c=J.querySelector("[data-persona-intro-card]");if(c){let Se=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;c.style.display=Se?"":"none",Se?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}!((pe=(we=r.sendButton)==null?void 0:we.useIcon)!=null&&pe)&&!(S!=null&&S.isStreaming())&&(ae.textContent=(he=(Y=r.copy)==null?void 0:Y.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 wr=null,ua=()=>{wr==null&&(wr=setInterval(()=>{let c=_e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(wr),wr=null;return}let f=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=Ea(f-b))})},100))};if(S=new Rs(r,{onMessagesChanged(c){go(_e,c,Re),ua(),S&&(c.some(M=>M.role==="user")?cr.render([],S,de,c):cr.render(r.suggestionChips,S,de,c,r.suggestionChipsConfig)),Vr(!zn),ia(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),Ho(c),Rr()},onStatusChanged(c){var b;let f=(b=r.statusIndicator)!=null?b:{};ue(ln,(M=>{var N,$,U,B;return M==="idle"?(N=f.idleText)!=null?N:gn.idle:M==="connecting"?($=f.connectingText)!=null?$:gn.connecting:M==="connected"?(U=f.connectedText)!=null?U:gn.connected:M==="error"?(B=f.errorText)!=null?B:gn.error:gn[M]})(c),f,c)},onStreamingChanged(c){zn=c,Bo(c),S&&go(_e,S.getMessages(),Re),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":Z(),L();break;case"speaking":Z(),Q();break;default:c==="idle"&&S.isBargeInActive()?(Z(),j(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,Z(),nr("system"),Ln());break}},onArtifactsState(c){On=c,jn(),Ho()}}),Lt.current=S,((hc=(fc=r.voiceRecognition)==null?void 0:fc.provider)==null?void 0:hc.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=ml(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 fs=()=>{var f,y,b;!O()||R||!((b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Rt(!0,"auto")},hs=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;fs();let b;y&&(b=[],b.push(...tt.getContentParts()),f&&b.push(Wa(f))),de.value="",de.style.height="auto",fo(),S.sendMessage(f,{contentParts:b}),y&&tt.clearAttachments()},ma=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},No={...$a},Fo=!1,fo=()=>{No={...$a}},ga=()=>S.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),fa=c=>{if(!de)return;Fo=!0,de.value=c,de.dispatchEvent(new Event("input",{bubbles:!0})),Fo=!1;let f=de.value.length;de.setSelectionRange(f,f)},ys=()=>{Fo||fo()},bs=c=>{if(de){if(ma()&&(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=Xp({direction:c.key==="ArrowUp"?"up":"down",history:ga(),currentValue:de.value,atStart:f,state:No});if(No=y.state,y.handled){c.preventDefault(),y.value!==void 0&&fa(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(S.isStreaming()){c.preventDefault();return}fo(),c.preventDefault(),ae.click()}}},xs=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())},vs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!tt)return;let f=kb(c.clipboardData);f.length!==0&&(c.preventDefault(),await tt.handleFiles(f))},vn=null,Vn=!1,Hr=null,ot=null,Cs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ho=(c="user")=>{var N,$,U,B,we,pe,Y;if(Vn||S.isStreaming())return;let f=Cs();if(!f)return;vn=new f;let b=($=((N=r.voiceRecognition)!=null?N:{}).pauseDuration)!=null?$:2e3;vn.continuous=!0,vn.interimResults=!0,vn.lang="en-US";let M=de.value;vn.onresult=he=>{let Se="",Oe="";for(let Xe=0;Xe<he.results.length;Xe++){let at=he.results[Xe],it=at[0].transcript;at.isFinal?Se+=it+" ":Oe=it}let nt=M+Se+Oe;de.value=nt,Hr&&clearTimeout(Hr),(Se||Oe)&&(Hr=window.setTimeout(()=>{let Xe=de.value.trim();Xe&&vn&&Vn&&(gr(),de.value="",de.style.height="auto",S.sendMessage(Xe,{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:(B=he.iconName)!=null?B:"mic",iconSize:parseFloat((Y=(pe=he.iconSize)!=null?pe:(we=r.sendButton)==null?void 0:we.size)!=null?Y:"40")||24};let Se=he.recordingBackgroundColor,Oe=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=Oe!=null?Oe:"var(--persona-voice-recording-indicator, #ffffff)",Oe){let Xe=q.querySelector("svg");Xe&&Xe.setAttribute("stroke",Oe)}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")}}},ha=(c,f)=>{var at,it,ke,Me,ze,E,Te,He;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 N=h("div","persona-send-button-wrapper"),$=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button",$.setAttribute("aria-label","Start voice recognition");let U=(it=c==null?void 0:c.iconName)!=null?it:"mic",B=(ke=f==null?void 0:f.size)!=null?ke:"40px",we=(Me=c==null?void 0:c.iconSize)!=null?Me:B,pe=parseFloat(we)||24,Y=(ze=c==null?void 0:c.backgroundColor)!=null?ze:f==null?void 0:f.backgroundColor,he=(E=c==null?void 0:c.iconColor)!=null?E:f==null?void 0:f.textColor;$.style.width=we,$.style.height=we,$.style.minWidth=we,$.style.minHeight=we,$.style.fontSize="18px",$.style.lineHeight="1",he?$.style.color=he:$.style.color="var(--persona-text, #111827)";let Oe=be(U,pe,he||"currentColor",1.5);Oe?$.appendChild(Oe):$.textContent="\u{1F3A4}",Y?$.style.backgroundColor=Y:$.style.backgroundColor="",c!=null&&c.borderWidth&&($.style.borderWidth=c.borderWidth,$.style.borderStyle="solid"),c!=null&&c.borderColor&&($.style.borderColor=c.borderColor),c!=null&&c.paddingX&&($.style.paddingLeft=c.paddingX,$.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&($.style.paddingTop=c.paddingY,$.style.paddingBottom=c.paddingY),N.appendChild($);let nt=(Te=c==null?void 0:c.tooltipText)!=null?Te:"Start voice recognition";if(((He=c==null?void 0:c.showTooltip)!=null?He:!1)&&nt){let Je=h("div","persona-send-button-tooltip");Je.textContent=nt,N.appendChild(Je)}return{micButton:$,micButtonWrapper:N}},Qr=()=>{var f,y,b,M,N;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((N=(M=c.iconSize)!=null?M:(b=r.sendButton)==null?void 0:b.size)!=null?N:"40")||24}},Ke=(c,f)=>{var N,$,U,B,we;if(!q)return;let y=q.querySelector("svg");y&&y.remove();let b=(we=ot==null?void 0:ot.iconSize)!=null?we:parseFloat((B=(U=(N=r.voiceRecognition)==null?void 0:N.iconSize)!=null?U:($=r.sendButton)==null?void 0:$.size)!=null?B:"40")||24,M=be(c,b,f,1.5);M&&q.appendChild(M)},w=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},j=()=>{var M;if(!q)return;Qr();let c=(M=r.voiceRecognition)!=null?M:{},f=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(w(),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 N=q.querySelector("svg");N&&N.setAttribute("stroke",y)}b&&(q.style.borderColor=b),q.setAttribute("aria-label","Stop voice recognition")},L=()=>{var U,B,we,pe,Y,he,Se,Oe;if(!q)return;Qr();let c=(U=r.voiceRecognition)!=null?U:{},f=S.getVoiceInterruptionMode(),y=(B=c.processingIconName)!=null?B:"loader",b=(pe=(we=c.processingIconColor)!=null?we:ot==null?void 0:ot.color)!=null?pe:"",M=(he=(Y=c.processingBackgroundColor)!=null?Y:ot==null?void 0:ot.backgroundColor)!=null?he:"",N=(Oe=(Se=c.processingBorderColor)!=null?Se:ot==null?void 0:ot.borderColor)!=null?Oe:"";w(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=M,q.style.borderColor=N;let $=b||"currentColor";q.style.color=$,Ke(y,$),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},Q=()=>{var we,pe,Y,he,Se,Oe,nt,Xe,at,it,ke,Me;if(!q)return;Qr();let c=(we=r.voiceRecognition)!=null?we:{},f=S.getVoiceInterruptionMode(),y=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=(pe=c.speakingIconName)!=null?pe:y,M=(Oe=c.speakingIconColor)!=null?Oe:f==="barge-in"?(he=(Y=c.recordingIconColor)!=null?Y:ot==null?void 0:ot.color)!=null?he:"":(Se=ot==null?void 0:ot.color)!=null?Se:"",N=(at=c.speakingBackgroundColor)!=null?at:f==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=ot==null?void 0:ot.backgroundColor)!=null?Xe:"",$=(Me=c.speakingBorderColor)!=null?Me:f==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(ke=ot==null?void 0:ot.borderColor)!=null?ke:"";w(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=N,q.style.borderColor=$;let U=M||"currentColor";q.style.color=U,Ke(b,U);let B=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",B),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},Z=()=>{var c,f,y;q&&(w(),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:"",Ke(ot.iconName,ot.color||"currentColor"),ot=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},K=()=>{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"),Z()});return}S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),mt.manuallyDeactivated=!S.isVoiceActive(),Ln(),nr("user"),S.isVoiceActive()?j():Z()});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=K,q&&(q.addEventListener("click",K),gt.push(()=>{var c,f;((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(S.isVoiceActive()&&S.toggleVoice(),Z()):gr("system"),q&&q.removeEventListener("click",K)}));let We=o.on("assistant:complete",()=>{ls&&(mt.active||mt.manuallyDeactivated||ls==="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()&&j()}):ho("auto"))},600))});gt.push(We);let $e=o.on("action:resubmit",()=>{setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)});gt.push($e);let et=()=>{Rt(!R,"user")},Ee=null,Ge=null;if(T&&!O()){let c=s.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:r,defaultRenderer:()=>zs(r,et).element,onToggle:et});f&&(Ge=f)}Ge||(Ee=zs(r,et))}Ee?e.appendChild(Ee.element):Ge&&e.appendChild(Ge),Xr(),cr.render(r.suggestionChips,S,de,void 0,r.suggestionChipsConfig),gs(),Bo(S.isStreaming()),Vr(!0),ra(),k&&(!T||O()?setTimeout(()=>Do(),0):R&&setTimeout(()=>Do(),200));let Pt=()=>{var B,we,pe,Y,he,Se,Oe,nt,Xe,at,it,ke,Me,ze,E,Te,He,Je,xe,kt,st,Qt;if(O()){yt(),Xr();return}let c=an(r),f=(we=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?we:!1,y=c||f||((Y=(pe=r.launcher)==null?void 0:pe.fullHeight)!=null?Y:!1),b=(he=e.ownerDocument.defaultView)!=null?he:window,M=(Oe=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?Oe:!0,N=(Xe=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?Xe:640,$=b.innerWidth<=N,U=M&&$&&T;try{if(U){lr(),Mo(e,r);return}if(I&&(I=!1,lr(),Mo(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,wn=(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-wn);re.style.height=`${lt}px`}}finally{if(yt(),Xr(),R&&T){let It=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((Te=(E=r.launcher)==null?void 0:E.mobileBreakpoint)!=null?Te:640),wn=(Je=(He=r.launcher)==null?void 0:He.sidebarMode)!=null?Je:!1,dn=(kt=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?kt:!0,Ze=an(r)&&dn&&It,lt=wn||dn&&It&&T||Ze;if(lt&&!Gt){let An=e.getRootNode(),un=An instanceof ShadowRoot?An.host:e.closest(".persona-host");un&&!Jt&&(Jt=Oi(un,(Qt=(st=r.launcher)==null?void 0:st.zIndex)!=null?Qt:fn)),Gt=$i(e.ownerDocument)}else lt||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null)}}};Pt();let nn=(yc=e.ownerDocument.defaultView)!=null?yc:window;if(nn.addEventListener("resize",Pt),gt.push(()=>nn.removeEventListener("resize",Pt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yt()});c.observe(je),gt.push(()=>c.disconnect())}ur=J.scrollTop;let wt=J.scrollHeight,Mt=()=>{let c=J.scrollTop,f=J.scrollHeight,y=f<wt;wt=f;let{action:b,nextLastScrollTop:M}=ja({following:pr.isFollowing(),currentScrollTop:c,lastScrollTop:ur,nearBottom:Fs(J,is),userScrollThreshold:ta,isAutoScrolling:Pr||uo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ur=M,b==="resume"){zr();return}b==="pause"&&ds()};J.addEventListener("scroll",Mt,{passive:!0}),gt.push(()=>J.removeEventListener("scroll",Mt));let rn=c=>{let f=Ua({following:pr.isFollowing(),deltaY:c.deltaY,nearBottom:Fs(J,is),resumeWhenNearBottom:!0});f==="pause"?ds():f==="resume"&&zr()};J.addEventListener("wheel",rn,{passive:!0}),gt.push(()=>J.removeEventListener("wheel",rn)),St.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,ur=J.scrollTop,zr(),Vr(!0)}),gt.push(()=>St.remove()),gt.push(()=>{cs()});let pn=()=>{qe&&(qn&&(qe.removeEventListener("click",qn),qn=null),D()?(qe.style.display="",qn=()=>{Rt(!1,"user")},qe.addEventListener("click",qn)):qe.style.display="none")};pn(),(()=>{let{clearChatButton:c}=Ie;c&&c.addEventListener("click",()=>{S.clearMessages(),dr.clear(),zr(),Po(Ie.composerOverlay);try{localStorage.removeItem(os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${os}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==os)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",hs),de==null||de.addEventListener("keydown",bs),de==null||de.addEventListener("input",ys),de==null||de.addEventListener("paste",vs);let Xt=(bc=e.ownerDocument)!=null?bc:document;Xt.addEventListener("keydown",xs,!0);let rr="persona-attachment-drop-active",ws=0,Ai=()=>{ws=0,ce.classList.remove(rr)},Oo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&tt!==null},Tl=c=>{!mi(c.dataTransfer)||!Oo()||(ws++,ws===1&&ce.classList.add(rr))},El=c=>{!mi(c.dataTransfer)||!Oo()||(ws--,ws<=0&&Ai())},Ml=c=>{!mi(c.dataTransfer)||!Oo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},kl=c=>{var y;if(!mi(c.dataTransfer)||!Oo())return;c.preventDefault(),c.stopPropagation(),Ai();let f=Array.from((y=c.dataTransfer.files)!=null?y:[]);f.length!==0&&tt.handleFiles(f)},Yr=!0;ce.addEventListener("dragenter",Tl,Yr),ce.addEventListener("dragleave",El,Yr),e.addEventListener("dragover",Ml,Yr),e.addEventListener("drop",kl,Yr);let ya=e.ownerDocument,Ll=c=>{Oo()&&c.preventDefault()},Pl=c=>{Oo()&&c.preventDefault()};ya.addEventListener("dragover",Ll),ya.addEventListener("drop",Pl),gt.push(()=>{Ot&&Ot.removeEventListener("submit",hs),de==null||de.removeEventListener("keydown",bs),de==null||de.removeEventListener("input",ys),de==null||de.removeEventListener("paste",vs),Xt.removeEventListener("keydown",xs,!0)}),gt.push(()=>{ce.removeEventListener("dragenter",Tl,Yr),ce.removeEventListener("dragleave",El,Yr),e.removeEventListener("dragover",Ml,Yr),e.removeEventListener("drop",kl,Yr),ya.removeEventListener("dragover",Ll),ya.removeEventListener("drop",Pl),Ai()}),gt.push(()=>{S.cancel()}),Ee?gt.push(()=>{Ee==null||Ee.destroy()}):Ge&&gt.push(()=>{Ge==null||Ge.remove()});let en={update(c){var tn,Ar,Dr,ba,xa,va,Co,Ca,As,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,Cd,wd,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,vp;let f=r.toolCall,y=r.messageActions,b=(tn=r.layout)==null?void 0:tn.messages,M=r.colorScheme,N=r.loadingIndicator,$=r.iterationDisplay,U=(Ar=r.features)==null?void 0:Ar.showReasoning,B=(Dr=r.features)==null?void 0:Dr.showToolCalls,we=(ba=r.features)==null?void 0:ba.toolCallDisplay,pe=(xa=r.features)==null?void 0:xa.reasoningDisplay;r={...r,...c},lr(),Mo(e,r),li(e,r),ci(e,r),jn(),r.colorScheme!==M&&qr();let Y=di.getForInstance(r.plugins);s.length=0,s.push(...Y),T=(Co=(va=r.launcher)==null?void 0:va.enabled)!=null?Co:!0,H=(As=(Ca=r.launcher)==null?void 0:Ca.autoExpand)!=null?As:!1,Ue=(Ec=(Tc=r.features)==null?void 0:Tc.showReasoning)!=null?Ec:!0,Fe=(kc=(Mc=r.features)==null?void 0:Mc.showToolCalls)!=null?kc:!0,ye=(Pc=(Lc=r.features)==null?void 0:Lc.scrollToBottom)!=null?Pc:{},zt(),Wr();let he=ge;if(ge=(Wc=(Ic=r.features)==null?void 0:Ic.showEventStreamToggle)!=null?Wc:!1,ge&&!he){if(V||(ee=new Ys(Be),V=new Qs(Pe,ee),le=le!=null?le:new Zs,ee.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),S.setSSEEventCallback((G,xt)=>{var Nt;(Nt=r.onSSEEvent)==null||Nt.call(r,G,xt),le==null||le.processEvent(G,xt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:G,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!ut&&Ne){let G=(Hc=(Rc=r.features)==null?void 0:Rc.eventStream)==null?void 0:Hc.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"+(G!=null&&G.toggleButton?" "+G.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===Ne?Ne.insertBefore(ut,on):Ne.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(((Bc=r.launcher)==null?void 0:Bc.enabled)===!1&&Ee&&(Ee.destroy(),Ee=null),((Dc=r.launcher)==null?void 0:Dc.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((Nc=r.launcher)==null?void 0:Nc.enabled)!==!1&&!Ee&&!Ge){let G=s.find(xt=>xt.renderLauncher);if(G!=null&&G.renderLauncher){let xt=G.renderLauncher({config:r,defaultRenderer:()=>zs(r,et).element,onToggle:et});xt&&(Ge=xt,e.appendChild(Ge))}Ge||(Ee=zs(r,et),e.appendChild(Ee.element))}Ee&&Ee.update(r),Ae&&((Fc=r.launcher)==null?void 0:Fc.title)!==void 0&&(Ae.textContent=r.launcher.title),De&&((Oc=r.launcher)==null?void 0:Oc.subtitle)!==void 0&&(De.textContent=r.launcher.subtitle);let Se=($c=r.layout)==null?void 0:$c.header;if((Se==null?void 0:Se.layout)!==A&&Ne){let G=Se?Vs(r,Se,{showClose:D(),onClose:()=>Rt(!1,"user")}):ro({config:r,showClose:D(),onClose:()=>Rt(!1,"user")});Ne.replaceWith(G.header),Ne=G.header,F=G.iconHolder,Ae=G.headerTitle,De=G.headerSubtitle,qe=G.closeButton,A=Se==null?void 0:Se.layout}else if(Se&&(F&&(F.style.display=Se.showIcon===!1?"none":""),Ae&&(Ae.style.display=Se.showTitle===!1?"none":""),De&&(De.style.display=Se.showSubtitle===!1?"none":""),qe&&(qe.style.display=Se.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let G=Se.showClearChat;if(G!==void 0){Ie.clearChatButtonWrapper.style.display=G?"":"none";let{closeButtonWrapper:xt}=Ie;xt&&!xt.classList.contains("persona-absolute")&&(G?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let nt=((_c=r.layout)==null?void 0:_c.showHeader)!==!1;Ne&&(Ne.style.display=nt?"":"none");let Xe=((jc=r.layout)==null?void 0:jc.showFooter)!==!1;je&&(je.style.display=Xe?"":"none"),yt(),Wr(),T!==W?T?Rt(H,"auto"):(R=!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),ze=JSON.stringify((Uc=r.layout)==null?void 0:Uc.messages)!==JSON.stringify(b),E=((qc=r.loadingIndicator)==null?void 0:qc.render)!==(N==null?void 0:N.render)||((zc=r.loadingIndicator)==null?void 0:zc.renderIdle)!==(N==null?void 0:N.renderIdle)||((Vc=r.loadingIndicator)==null?void 0:Vc.showBubble)!==(N==null?void 0:N.showBubble),Te=r.iterationDisplay!==$,He=((Jc=(Kc=r.features)==null?void 0:Kc.showReasoning)!=null?Jc:!0)!==(U!=null?U:!0)||((Xc=(Gc=r.features)==null?void 0:Gc.showToolCalls)!=null?Xc:!0)!==(B!=null?B:!0)||JSON.stringify((Qc=r.features)==null?void 0:Qc.toolCallDisplay)!==JSON.stringify(we)||JSON.stringify((Yc=r.features)==null?void 0:Yc.reasoningDisplay)!==JSON.stringify(pe);(ke||Me||ze||E||Te||He)&&S&&(as++,go(_e,S.getMessages(),Re));let xe=(Zc=r.launcher)!=null?Zc:{},kt=(ed=xe.headerIconHidden)!=null?ed:!1,st=(nd=(td=r.layout)==null?void 0:td.header)==null?void 0:nd.showIcon,Qt=kt||st===!1,cn=xe.headerIconName,It=(rd=xe.headerIconSize)!=null?rd:"48px";if(F){let G=ce.querySelector(".persona-border-b-persona-divider"),xt=G==null?void 0:G.querySelector(".persona-flex-col");if(Qt)F.style.display="none",G&&xt&&!G.contains(xt)&&G.insertBefore(xt,G.firstChild);else{if(F.style.display="",F.style.height=It,F.style.width=It,G&&xt&&(G.contains(F)?F.nextSibling!==xt&&(F.remove(),G.insertBefore(F,xt)):G.insertBefore(F,xt)),cn){let ct=parseFloat(It)||24,Tt=be(cn,ct*.6,"#ffffff",2);Tt?F.replaceChildren(Tt):F.textContent=(od=xe.agentIconText)!=null?od:"\u{1F4AC}"}else if(xe.iconUrl){let ct=F.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,F.replaceChildren(Tt)}}else{let ct=F.querySelector("svg"),Tt=F.querySelector("img");(ct||Tt)&&F.replaceChildren(),F.textContent=(sd=xe.agentIconText)!=null?sd:"\u{1F4AC}"}let Nt=F.querySelector("img");Nt&&(Nt.style.height=It,Nt.style.width=It)}}let wn=(id=(ad=r.layout)==null?void 0:ad.header)==null?void 0:id.showTitle,dn=(cd=(ld=r.layout)==null?void 0:ld.header)==null?void 0:cd.showSubtitle;if(Ae&&(Ae.style.display=wn===!1?"none":""),De&&(De.style.display=dn===!1?"none":""),qe){((pd=(dd=r.layout)==null?void 0:dd.header)==null?void 0:pd.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let xt=(ud=xe.closeButtonSize)!=null?ud:"32px",Nt=(md=xe.closeButtonPlacement)!=null?md:"inline";qe.style.height=xt,qe.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=(fd=(gd=xe.clearChat)==null?void 0:gd.placement)!=null?fd:"inline",sn=(yd=(hd=xe.clearChat)==null?void 0:hd.enabled)!=null?yd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Rn=ce.querySelector(".persona-border-b-persona-divider");Rn&&Rn.appendChild(ct)}if(qe.style.color=xe.closeButtonColor||En.actionIconColor,xe.closeButtonBackgroundColor?(qe.style.backgroundColor=xe.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let pt=xe.closeButtonBorderWidth||"0px",sn=xe.closeButtonBorderColor||"transparent";qe.style.border=`${pt} solid ${sn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");xe.closeButtonBorderRadius?(qe.style.borderRadius=xe.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(qe.style.paddingLeft=xe.closeButtonPaddingX,qe.style.paddingRight=xe.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),xe.closeButtonPaddingY?(qe.style.paddingTop=xe.closeButtonPaddingY,qe.style.paddingBottom=xe.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let mn=(bd=xe.closeButtonIconName)!=null?bd:"x",fr=(xd=xe.closeButtonIconText)!=null?xd:"\xD7";qe.innerHTML="";let Tn=be(mn,"28px","currentColor",1);Tn?qe.appendChild(Tn):qe.textContent=fr;let Yt=(vd=xe.closeButtonTooltipText)!=null?vd:"Close chat",Jn=(Cd=xe.closeButtonShowTooltip)!=null?Cd:!0;if(qe.setAttribute("aria-label",Yt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Jn&&Yt)){let pt=null,sn=()=>{if(pt||!qe)return;let wo=qe.ownerDocument,Ss=wo.body;if(!Ss)return;pt=Sr(wo,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Ts=Sr(wo,"div");Ts.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ts);let Ao=qe.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%)",Ss.appendChild(pt)},Rn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Rn),qe.addEventListener("focus",sn),qe.addEventListener("blur",Rn),ct._cleanupTooltip=()=>{Rn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Rn)),qe&&(qe.removeEventListener("focus",sn),qe.removeEventListener("blur",Rn))}}}let{clearChatButton:Ze,clearChatButtonWrapper:lt}=Ie;if(Ze){let G=(wd=xe.clearChat)!=null?wd:{},xt=(Ad=G.enabled)!=null?Ad:!0,Nt=(Td=(Sd=r.layout)==null?void 0:Sd.header)==null?void 0:Td.showClearChat,ct=Nt!==void 0?Nt:xt,Tt=(Ed=G.placement)!=null?Ed:"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=(Md=G.size)!=null?Md:"32px";Ze.style.height=pt,Ze.style.width=pt}let on=(kd=G.iconName)!=null?kd:"refresh-cw",mn=(Ld=G.iconColor)!=null?Ld:"";Ze.style.color=mn||En.actionIconColor,Ze.innerHTML="";let fr=O()?"14px":"20px",Tn=be(on,fr,"currentColor",2);if(Tn&&Ze.appendChild(Tn),G.backgroundColor?(Ze.style.backgroundColor=G.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),G.borderWidth||G.borderColor){let pt=G.borderWidth||"0px",sn=G.borderColor||"transparent";Ze.style.border=`${pt} solid ${sn}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");G.borderRadius?(Ze.style.borderRadius=G.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),G.paddingX?(Ze.style.paddingLeft=G.paddingX,Ze.style.paddingRight=G.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),G.paddingY?(Ze.style.paddingTop=G.paddingY,Ze.style.paddingBottom=G.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let Yt=(Pd=G.tooltipText)!=null?Pd:"Clear chat",Jn=(Id=G.showTooltip)!=null?Id:!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 wo=Ze.ownerDocument,Ss=wo.body;if(!Ss)return;pt=Sr(wo,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Ts=Sr(wo,"div");Ts.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ts);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%)",Ss.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:[pi],un=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[rs.message,rs.messageAndClick];C=ui({parsers:An,handlers:un,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Re=Gu(r,C,oe),S.updateConfig(r),go(_e,S.getMessages(),Re),cr.render(r.suggestionChips,S,de,void 0,r.suggestionChipsConfig),gs(),Bo(S.isStreaming());let yo=((Wd=r.voiceRecognition)==null?void 0:Wd.enabled)===!0,bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),xo=((Hd=(Rd=r.voiceRecognition)==null?void 0:Rd.provider)==null?void 0:Hd.type)==="runtype";if(yo&&(bo||xo))if(!q||!$t){let G=ha(r.voiceRecognition,r.sendButton);G&&(q=G.micButton,$t=G.micButtonWrapper,At.insertBefore($t,Mn),q.addEventListener("click",K),q.disabled=S.isStreaming())}else{let G=(Bd=r.voiceRecognition)!=null?Bd:{},xt=(Dd=r.sendButton)!=null?Dd:{},Nt=(Nd=G.iconName)!=null?Nd:"mic",ct=(Fd=xt.size)!=null?Fd:"40px",Tt=(Od=G.iconSize)!=null?Od:ct,on=parseFloat(Tt)||24;q.style.width=Tt,q.style.height=Tt,q.style.minWidth=Tt,q.style.minHeight=Tt;let mn=(_d=($d=G.iconColor)!=null?$d:xt.textColor)!=null?_d:"currentColor";q.innerHTML="";let fr=be(Nt,on,mn,2);fr?q.appendChild(fr):q.textContent="\u{1F3A4}";let Tn=(jd=G.backgroundColor)!=null?jd:xt.backgroundColor;Tn?q.style.backgroundColor=Tn:q.style.backgroundColor="",mn?q.style.color=mn:q.style.color="var(--persona-text, #111827)",G.borderWidth?(q.style.borderWidth=G.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),G.borderColor?q.style.borderColor=G.borderColor:q.style.borderColor="",G.paddingX?(q.style.paddingLeft=G.paddingX,q.style.paddingRight=G.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),G.paddingY?(q.style.paddingTop=G.paddingY,q.style.paddingBottom=G.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Yt=$t==null?void 0:$t.querySelector(".persona-send-button-tooltip"),Jn=(Ud=G.tooltipText)!=null?Ud:"Start voice recognition";if(((qd=G.showTooltip)!=null?qd:!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",((Vd=(zd=r.voiceRecognition)==null?void 0:zd.provider)==null?void 0:Vd.type)==="runtype"?S.isVoiceActive()&&S.toggleVoice():Vn&&gr());if(((Kd=r.attachments)==null?void 0:Kd.enabled)===!0)if(!Dt||!Ye){let G=(Jd=r.attachments)!=null?Jd:{},Nt=(Xd=((Gd=r.sendButton)!=null?Gd:{}).size)!=null?Xd:"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=((Qd=G.allowedTypes)!=null?Qd:Nr).join(","),ne.multiple=((Yd=G.maxFiles)!=null?Yd: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",(Zd=G.buttonTooltipText)!=null?Zd:"Attach file");let ct=(ep=G.buttonIconName)!=null?ep:"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=(tp=G.buttonTooltipText)!=null?tp:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=Tn,Dt.appendChild(Yt),rt.append(Dt),!tt&&ne&&me&&(tt=Jo.fromConfig(G),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(Xu(G.dropOverlay))}else{Dt.style.display="";let G=(np=r.attachments)!=null?np:{};ne&&(ne.accept=((rp=G.allowedTypes)!=null?rp:Nr).join(","),ne.multiple=((op=G.maxFiles)!=null?op:4)>1),tt&&tt.updateConfig({allowedTypes:G.allowedTypes,maxFileSize:G.maxFileSize,maxFiles:G.maxFiles})}else Dt&&(Dt.style.display="none"),tt&&tt.clearAttachments(),(sp=ce.querySelector(".persona-attachment-drop-overlay"))==null||sp.remove();let Vt=(ap=r.sendButton)!=null?ap:{},vo=(ip=Vt.useIcon)!=null?ip:!1,Zr=(lp=Vt.iconText)!=null?lp:"\u2191",ht=Vt.iconName,Pn=(cp=Vt.tooltipText)!=null?cp:"Send message",Br=(dp=Vt.showTooltip)!=null?dp:!1,Sn=(pp=Vt.size)!=null?pp:"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 G=parseFloat(Sn)||24,xt=(Ht==null?void 0:Ht.trim())||"currentColor",Nt=be(ht,G,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=(mp=(up=r.copy)==null?void 0:up.sendButtonLabel)!=null?mp:"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 G=document.createElement("div");G.className="persona-send-button-tooltip",G.textContent=Pn,Mn==null||Mn.insertBefore(G,ae)}else Ut&&(Ut.style.display="none");let Bt=(bp=(gp=r.layout)==null?void 0:gp.contentMaxWidth)!=null?bp:O()?(yp=(hp=(fp=r.launcher)==null?void 0:fp.composerBar)==null?void 0:hp.contentMaxWidth)!=null?yp:"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=(xp=r.statusIndicator)!=null?xp:{},Wn=(vp=Kt.visible)!=null?vp:!0;if(ln.style.display=Wn?"":"none",S){let G=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]})(G),Kt,G)}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(){D()&&Rt(!0,"api")},close(){D()&&Rt(!1,"api")},toggle(){D()&&Rt(!R,"api")},clearChat(){bn=!1,S.clearMessages(),dr.clear(),zr();try{localStorage.removeItem(os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${os}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==os)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:(!R&&D()&&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?(!R&&D()&&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()||(!R&&D()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,Ln(),S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("user"),S.isVoiceActive()&&j()})),!0):Vn?!0:Cs()?(!R&&D()&&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"),Z()}),!0):!1:Vn?(mt.manuallyDeactivated=!0,Ln(),gr("user"),!0):!1},injectMessage(c){return!R&&D()&&Rt(!0,"system"),S.injectMessage(c)},injectAssistantMessage(c){!R&&D()&&Rt(!0,"system");let f=S.injectAssistantMessage(c);return _&&(_=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)),f},injectUserMessage(c){return!R&&D()&&Rt(!0,"system"),S.injectUserMessage(c)},injectSystemMessage(c){return!R&&D()&&Rt(!0,"system"),S.injectSystemMessage(c)},injectMessageBatch(c){return!R&&D()&&Rt(!0,"system"),S.injectMessageBatch(c)},injectComponentDirective(c){return!R&&D()&&Rt(!0,"system"),S.injectComponentDirective(c)},injectTestMessage(c){!R&&D()&&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&&!R&&!O()||!de?!1:(de.focus(),!0)},async resolveApproval(c,f){let b=S.getMessages().find(M=>{var N;return M.variant==="approval"&&((N=M.approval)==null?void 0:N.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 D()&&R},isVoiceActive(){return mt.active},getState(){return{open:D()&&R,launcherEnabled:T,voiceActive:mt.active,streaming:S.isStreaming()}},showCSATFeedback(c){!R&&D()&&Rt(!0,"system");let f=_e.querySelector(".persona-feedback-container");f&&f.remove();let y=pl({onSubmit:async(b,M)=>{var N;S.isClientTokenMode()&&await S.submitCSATFeedback(b,M),(N=c==null?void 0:c.onSubmit)==null||N.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&D()&&Rt(!0,"system");let f=_e.querySelector(".persona-feedback-container");f&&f.remove();let y=ul({onSubmit:async(b,M)=>{var N;S.isClientTokenMode()&&await S.submitNPSFeedback(b,M),(N=c==null?void 0:c.onSubmit)==null||N.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(){wr!=null&&(clearInterval(wr),wr=null),gt.forEach(c=>c()),ie.remove(),Qe==null||Qe.remove(),Ee==null||Ee.destroy(),Ge==null||Ge.remove(),qn&&qe.removeEventListener("click",qn)}};if((((xc=n==null?void 0:n.debugTools)!=null?xc:!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 B=U.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",f),gt.push(()=>{window.removeEventListener("persona:focusInput",f)}),ge){let U=we=>{let pe=we.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.showEventStream()},B=we=>{let pe=we.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",B),gt.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",B)})}let y=U=>{let B=U.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&en.showArtifacts()},b=U=>{let B=U.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&en.hideArtifacts()},M=U=>{let B=U.detail;B!=null&&B.instanceId&&B.instanceId!==c||B!=null&&B.artifact&&en.upsertArtifact(B.artifact)},N=U=>{let B=U.detail;B!=null&&B.instanceId&&B.instanceId!==c||typeof(B==null?void 0:B.id)=="string"&&en.selectArtifact(B.id)},$=U=>{let B=U.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",$),gt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",$)})}let or=Lb(r.persistState);if(or&&D()){let c=Pb(or.storage),f=`${or.keyPrefix}widget-open`,y=`${or.keyPrefix}widget-voice`,b=`${or.keyPrefix}widget-voice-mode`;if(c){let M=((vc=or.persist)==null?void 0:vc.openState)&&c.getItem(f)==="true",N=((Cc=or.persist)==null?void 0:Cc.voiceState)&&c.getItem(y)==="true",$=((wc=or.persist)==null?void 0:wc.voiceState)&&c.getItem(b)==="true";if(M&&setTimeout(()=>{en.open(),setTimeout(()=>{var U;if(N||$)en.startVoiceRecognition();else if((U=or.persist)!=null&&U.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(Ac=or.persist)!=null&&Ac.openState&&(o.on("widget:opened",()=>{c.setItem(f,"true")}),o.on("widget:closed",()=>{c.setItem(f,"false")})),(Sc=or.persist)!=null&&Sc.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)},B=()=>U();window.addEventListener("persona:clear-chat",B),gt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return p&&D()&&setTimeout(()=>{en.open()},0),Rr(),en};var Ib=(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},Qu=(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"},bl=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=""},Yu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",bl(e)},fl=e=>{e.style.transition=""},hl=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=""},yl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},gi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Wb=(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))},Rb=(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)},Zu=(e,t,n,r,s,o,a)=>{var v,x,C,T,H,k;let i=yr(o),d=i.reveal==="push";Wb(e,t,n,r,d),Rb(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"),hl(t),fl(r),Yu(r),yl(n),gi(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((k=(H=o==null?void 0:o.launcher)==null?void 0:H.zIndex)!=null?k: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"),Yu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",hl(t),fl(r),yl(n),gi(s,r);let P=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=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=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",fl(r),bl(r),gi(s,r);let P=Ib(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),A=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=A,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="",hl(t),bl(r),yl(n),gi(s,r);let P=i.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",A=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=A,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")}},Hb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Qu(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Qu(n,r)},destroy(){n.remove()}}},Bb=(e,t)=>{var H,k,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=(k=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)==null||k?(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(()=>{Zu(a,i,d,l,p,t,m)}),g.observe(a))},x=()=>{Zu(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(A){let I=A.launcherEnabled?A.open:!0;m!==I&&(m=I,x())},updateConfig(A){var I,O;t=A,((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()}}},fi=(e,t)=>an(t)?Bb(e,t):Hb(e,t);var xl={},em=!1,Db=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},Nb=()=>{try{if(typeof xl!="undefined"&&xl.url)return new URL("../widget.css",xl.url).href}catch{}return null},tm=(e,t)=>{let n=Nb(),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)}},nm=e=>{let t=Db(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=fi(t,s),a,i=[],d=(C,T)=>{var W,A;let k=!((A=(W=T==null?void 0:T.launcher)==null?void 0:W.enabled)!=null?A:!0)||an(T),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),k&&(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),tm(I,r)}else C.appendChild(P),tm(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=gl(C,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(C=>C()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(em||(em=!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=fi(t,C),s=C,m()},v={update(C){var A,I,O,D,R,_;let T={...s,...C,launcher:{...(A=s==null?void 0:s.launcher)!=null?A:{},...(I=C==null?void 0:C.launcher)!=null?I:{},dock:{...(D=(O=s==null?void 0:s.launcher)==null?void 0:O.dock)!=null?D:{},...(_=(R=C==null?void 0:C.launcher)==null?void 0:R.dock)!=null?_:{}}}},H=an(s),k=an(T),P=no(s),W=no(T);if(H!==k||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 k=a[T];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var im=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Fb=new Set(["button","a","input","select","textarea","details","summary"]),Ob=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),vl=/\b(product|card|item|listing|result)\b/i,wl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,$b=3e3,_b=100;function lm(e){let t=typeof e.className=="string"?e.className:"";if(vl.test(t)||e.id&&vl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&vl.test(r.value))return!0}return!1}function cm(e){var t;return wl.test(((t=e.textContent)!=null?t:"").trim())}function dm(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 jb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function rm(e){let t=e.match(wl);return t?t[0]:null}function om(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 Ub(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 qb="commerce-card",zb="result-card";function sm(e){return!lm(e)||!cm(e)||!dm(e)&&!jb(e)?0:5200}function am(e){var r;return!lm(e)||cm(e)||!dm(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 pm=[{id:qb,scoreElement(e){return sm(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(sm(e)===0)return null;let{title:n,href:r}=om(e),s=(p=(l=rm(((d=e.textContent)!=null?d:"").trim()))!=null?l:rm(t.text))!=null?p:"",o=Ub(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:zb,scoreElement(e){return am(e)},formatSummary(e,t){if(am(e)===0)return null;let{title:n,href:r}=om(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
- `)}}];function Vb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Kb(e){var p,m,g,u,v,x,C,T,H,k,P,W,A;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=(k=t.root)!=null?k:e.root,i=(P=t.mode)!=null?P:"structured",d=(W=t.maxCandidates)!=null?W:Math.max(500,n*10),l=(A=e.rules)!=null?A:pm;return i==="simple"&&e.rules&&e.rules.length>0?(Vb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function Cl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Jb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Gb(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"||Fb.has(t)||n&&Ob.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function um(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 Xb(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 mm(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Cl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Jb){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${Cl(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=>Cl(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 Qb(e){return e==="static"?_b:$b}function gm(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:mm(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Gb(e),attributes:Xb(e)}}function Yb(e,t,n,r){let s=Qb(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 Zb(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 ex(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(im.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!um(l)){i=a.nextNode();continue}let m=gm(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}=Yb(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;Zb(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 tx(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(im.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!um(d)){o=s.nextNode();continue}let p=gm(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 nx(e={}){var r;let t=Kb(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?tx(t,n):ex(t,n):[]}var hi=100;function rx(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,hi)}" (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,hi)}" (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,hi)}" (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,hi)}"`);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 fm={name:"@runtypelabs/persona",version:"3.29.1",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 ss=fm.version;function sx(){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 ax(){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 ix(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 lx(){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 cx(){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 dx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var px={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"}}},hm={components:{panel:{borderRadius:"0",shadow:"none"}}},ym={id:"shop",label:"Shopping Assistant",config:{theme:px,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?"]}},bm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:hm}},xm={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:hm}},vm={shop:ym,minimal:bm,fullscreen:xm};function ux(e){return vm[e]}var mx=nm;function Fr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function gx(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 Cm=`({ 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
- }`,wm=`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
- }`,Am=`(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
- }`,Sm=`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
- }`,fx=`(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
- }`,hx=`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 yx(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 yi(e){var t,n;return(n=(t=e.parserType)!=null?t:yx(e.streamParser))!=null?n:"plain"}function bi(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 xi(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 vi(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 Ci(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 Al(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 Tm(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}: {`),Tm(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}: {`),Tm(e,n,`${r} `),e.push(`${r}},`))}function ea(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function bx(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:gx(n.hooks)}:void 0;return t==="esm"?xx(r,s):t==="script-installer"?wx(r,s):t==="script-advanced"?Sx(r,s):t==="react-component"?vx(r,s):t==="react-advanced"?Cx(r,s):Ax(r,s)}function xx(e,t){let n=t==null?void 0:t.hooks,r=yi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ea(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(...bi(e," ")),o.push(...xi(e," ",n)),o.push(...vi(e," ")),o.push(...Ci(e," ")),o.push(...Al(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 vx(e,t){let n=t==null?void 0:t.hooks,r=yi(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: '${ea(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(...bi(e," ")),o.push(...xi(e," ",n)),o.push(...vi(e," ")),o.push(...Ci(e," ")),o.push(...Al(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 Cx(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: '${ea(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(...bi(e," ")),r.push(...xi(e," ",n)),r.push(...vi(e," ")),r.push(...Ci(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(${fx}),`)),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(` ${Cm}`),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(` ${Cm}`),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(` ${Am}`),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(` ${Am}`),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 Em(e){var s;let t=yi(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 wx(e,t){let n=Em(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@${ss}/dist/install.global.js" data-config='${o}'></script>`}function Ax(e,t){let n=t==null?void 0:t.hooks,r=yi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ss}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ss}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${ea(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(...bi(e," ")),o.push(...xi(e," ",n)),o.push(...vi(e," ")),o.push(...Ci(e," ")),o.push(...Al(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 Sx(e,t){let n=t==null?void 0:t.hooks,r=Em(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@${ss}/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(${hx});`),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(` ${wm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${wm}`),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(` ${Sm}`),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(` ${Sm}`),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: '${ea(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 Mm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},km=.1,Lm=.15,Pm=1.5,Sl=24,Im=40,Tx=`
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: ${Sl}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 Ex(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Tx,document.head.appendChild(e)}function Mx(e,t){let n=e.clientWidth-Sl*2-Im,r=e.clientHeight-Sl*2-Im;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function kx(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 Lx(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");Ex();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"),k=h("div","persona-dc-toolbar-trail"),P=qt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ce(-1)}),W=h("div");W.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 I=h("span","persona-dc-title-text"),O=h("span","persona-dc-title-chevron"),D=be("chevron-down",12,"currentColor",2);D&&O.appendChild(D),A.append(I,O);let R=h("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let _=!1;function z(){R.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",()=>{Re(),Ve(ue)}),R.appendChild(re)}}function oe(){_=!_,R.style.display=_?"":"none",A.setAttribute("aria-expanded",_?"true":"false"),_&&z()}function Re(){_&&(_=!1,R.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",ue=>{ue.stopPropagation(),oe()});let Ue=()=>Re();document.addEventListener("click",Ue),W.append(A,R);let Fe=qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ce(1)}),ge=h("span","persona-dc-counter");H.append(P,W,Fe,ge);let ye=null;i&&(ye=Qa({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,X()}}),k.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(Lm,Ie-km),X()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{u=1,X()});let re=qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ie=u!=null?u:v;u=Math.min(Pm,Ie+km),X()}}),Qe=qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{u=null,X()}});ue.append(ie,Le,re,Qe),k.appendChild(ue)}if(d){let ue=h("div","persona-dc-separator");k.appendChild(ue);let ie=Qa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:re=>{g=re,V.dataset.colorScheme=g,ve()}});k.appendChild(ie.element)}let Be=h("div","persona-dc-separator");k.appendChild(Be);let ee=qt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(ee),T.append(H,k);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 Ce(ue){let ie=((p+ue)%n.length+n.length)%n.length;Ve(ie)}function Ve(ue){ue<0||ue>=n.length||(p=ue,le.src=n[p].url,fe(),l==null||l(p,n[p]))}function X(){var re;if(x)return;let ue=(re=Mm[m])!=null?re:Mm.desktop;v=Mx(Pe,ue);let ie=Math.max(Lm,Math.min(Pm,u!=null?u:v));kx(V,le,ue,ie,m),Le&&(Le.textContent=`${Math.round(ie*100)}%`)}let te=new ResizeObserver(()=>X());te.observe(Pe),fe(),le.src=n[p].url,requestAnimationFrame(()=>X());function se(){x||(x=!0,te.disconnect(),document.removeEventListener("click",Ue),C.remove())}return{element:C,goTo:Ve,next:()=>Ce(1),prev:()=>Ce(-1),getIndex:()=>p,setDevice(ue){m=ue,V.dataset.device=ue,ye==null||ye.setSelected(ue),u=null,X()},setColorScheme(ue){g=ue,V.dataset.colorScheme=ue},setZoom(ue){u=ue,X()},destroy:se}}export{xu as ASK_USER_QUESTION_TOOL_NAME,zo as AgentWidgetClient,Rs as AgentWidgetSession,Jo as AttachmentManager,zp as DEFAULT_COMPONENTS,Ii as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,Up as DEFAULT_PALETTE,qp as DEFAULT_SEMANTIC,Ft as DEFAULT_WIDGET_CONFIG,vm as PRESETS,xm as PRESET_FULLSCREEN,bm as PRESET_MINIMAL,ym as PRESET_SHOP,Sh as THEME_ZONES,ss as VERSION,Sa as WEBMCP_TOOL_PREFIX,Ms as WebMcpBridge,sx as accessibilityPlugin,ax as animationsPlugin,Mo as applyThemeVariables,Xo as attachHeaderToContainer,ix as brandPlugin,Ks as buildComposer,su as buildDefaultHeader,ro as buildHeader,Vs as buildHeaderWithLayout,au as buildMinimalHeader,nx as collectEnrichedPageContext,lo as componentRegistry,ui as createActionManager,gl as createAgentExperience,Ny as createAskUserQuestionBubble,Pi as createBestAvailableVoiceProvider,ay as createBubbleWithLayout,pl as createCSATFeedback,_i as createComboButton,Sb as createComponentMiddleware,il as createComponentStreamParser,Tp as createDefaultSanitizer,Lx as createDemoCarousel,Bm as createDirectivePostprocessor,ko as createDropdownMenu,Qm as createFlexibleJsonStreamParser,qt as createIconButton,ig as createImagePart,Mi as createJsonStreamParser,Xa as createLabelButton,al as createLocalStorageAdapter,wa as createMarkdownProcessor,jo as createMarkdownProcessorFromConfig,fu as createMessageActions,ul as createNPSFeedback,Ti as createPlainTextParser,dx as createPlugin,Ei as createRegexJsonParser,Js as createStandardBubble,Wa as createTextPart,Bs as createTheme,Bi as createThemeObserver,Qa as createToggleGroup,Qo as createTypingIndicator,Ko as createVoiceProvider,fi as createWidgetHostLayout,ki as createXmlParser,mx as default,rs as defaultActionHandlers,pi as defaultJsonActionParser,pm as defaultParseRules,Fa as detectColorScheme,Dm as directivePostprocessor,Xs as ensureAskUserQuestionSheet,Uo as escapeHtml,dl as extractComponentDirectiveFromMessage,lg as fileToImagePart,rx as formatEnrichedContext,Vo as generateAssistantMessageId,bx as generateCodeSnippet,ng as generateMessageId,mm as generateStableSelector,Ps as generateUserMessageId,Ds as getActiveTheme,Gp as getColorScheme,og as getDisplayText,iu as getHeaderLayout,ag as getImageParts,ux as getPreset,cl as hasComponentDirective,sg as hasImages,ji as headerLayouts,cx as highContrastPlugin,nm as initAgentWidget,oo as isAskUserQuestionMessage,Ab as isComponentDirectiveType,an as isDockedMountMode,Da as isVoiceSupported,So as isWebMcpToolName,Hh as listRegisteredStreamAnimations,wp as markdownPostprocessor,Wi as mergeWithDefaults,rg as normalizeContent,so as parseAskUserQuestionPayload,di as pluginRegistry,lx as reducedMotionPlugin,Wh as registerStreamAnimationPlugin,Po as removeAskUserQuestionSheet,ll as renderComponentDirective,gu as renderLoadingIndicatorWithFallback,be as renderLucideIcon,yr as resolveDockConfig,Es as resolveSanitizer,Ri as resolveTokens,kp as stripWebMcpPrefix,Hi as themeToCssVariables,Rh as unregisterStreamAnimationPlugin,cg as validateImageFile,Vp 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