@runtypelabs/persona 3.29.1 → 3.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -2547
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-B_Qazlm4.d.cts → types-quh7NmYD.d.cts} +9 -0
- package/dist/animations/{types-B_Qazlm4.d.ts → types-quh7NmYD.d.ts} +9 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +6 -6
- package/dist/codegen.js +4 -4
- package/dist/index.cjs +50 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +164 -7
- package/dist/index.d.ts +164 -7
- package/dist/index.global.js +60 -60
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +49 -49
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/plugin-kit.cjs +1 -0
- package/dist/plugin-kit.d.cts +98 -0
- package/dist/plugin-kit.d.ts +98 -0
- package/dist/plugin-kit.js +1 -0
- package/dist/smart-dom-reader.d.cts +157 -4
- package/dist/smart-dom-reader.d.ts +157 -4
- package/dist/theme-editor.cjs +40 -40
- package/dist/theme-editor.d.cts +161 -6
- package/dist/theme-editor.d.ts +161 -6
- package/dist/theme-editor.js +40 -40
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +2 -0
- package/dist/theme-reference.d.ts +2 -0
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +19 -0
- package/package.json +8 -2
- package/src/client.ts +6 -0
- package/src/components/approval-bubble.test.ts +320 -0
- package/src/components/approval-bubble.ts +190 -20
- package/src/components/launcher.ts +6 -3
- package/src/components/panel.ts +7 -1
- package/src/components/tool-bubble.test.ts +39 -0
- package/src/components/tool-bubble.ts +4 -0
- package/src/defaults.ts +14 -0
- package/src/generated/runtype-openapi-contract.ts +4 -0
- package/src/index-core.ts +1 -0
- package/src/plugin-kit.test.ts +230 -0
- package/src/plugin-kit.ts +294 -0
- package/src/plugins/types.ts +49 -2
- package/src/session.test.ts +161 -0
- package/src/session.ts +41 -3
- package/src/styles/widget.css +19 -0
- package/src/theme-editor/preview-utils.test.ts +10 -0
- package/src/theme-editor/preview-utils.ts +29 -1
- package/src/theme-editor/sections.test.ts +17 -0
- package/src/theme-editor/sections.ts +31 -0
- package/src/theme-reference.ts +2 -2
- package/src/types/theme.ts +2 -0
- package/src/types.ts +109 -2
- package/src/ui.approval-plugin.test.ts +204 -0
- package/src/ui.scroll.test.ts +383 -0
- package/src/ui.ts +539 -56
- package/src/utils/auto-follow.test.ts +91 -0
- package/src/utils/auto-follow.ts +68 -0
- package/src/utils/theme.test.ts +6 -2
- package/src/utils/theme.ts +0 -8
- package/src/utils/tokens.ts +6 -1
- package/src/webmcp-bridge.test.ts +66 -0
- package/src/webmcp-bridge.ts +49 -0
package/dist/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{Marked as
|
|
1
|
+
import{Marked as xg}from"marked";var vg=e=>{if(e)return e},Ia=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new xg({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=vg(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},rs=e=>e?Ia({markedOptions:e.options,renderer:e.renderer}):Ia(),wg=Ia(),Qp=e=>wg(e),os=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Yp=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Xp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Zp=(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=Xp(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=Xp(t.length);return t.push({token:o,type:s}),o}),n},Cg=e=>{let t=rs(e);return n=>{let r=[],s=Zp(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="${Yp(i)}"></div>`;o=o.replace(d,p)}),o}},Ag=e=>{let t=[],n=Zp(e,t),r=Qp(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="${Yp(o)}"></div>`;r=r.replace(a,d)}),r};import Sg from"dompurify";var Tg={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"]},Eg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,eu=()=>{let e=Sg(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:")&&!Eg.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Tg)},_s=e=>e===!1?null:typeof e=="function"?e:eu();var po="webmcp:",Ni=new Map,tu=e=>{var t;Ni.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Ni.set(n.name,r)}},Oi=e=>Ni.get(Fi(e)),Wa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function ru(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}:${Mg(t.join(""))}`}function nu(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 Mg(e){let t=nu(e,0).toString(36),n=nu(e,2654435761).toString(36);return`${t}.${n}`}var js=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return Wa.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}tu(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=Lg(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return wr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let v=typeof document!="undefined"&&!!document.modelContext;return wr(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=Fi(t),a;try{a=await s.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return wr(`Failed to read WebMCP registry: ${x}`)}tu(a);let i=a.find(v=>v.name===o);if(!i)return wr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return wr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return wr("Aborted by cancel()");let d=Oi(o),l={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return wr("User declined the tool call.");if(r!=null&&r.aborted)return wr("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,Rg(n),{signal:p.signal});return Pg(v)}catch(v){if(u)return wr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return wr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return wr(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){Wa.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Wa.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:Ig;try{return await n(t)}catch(s){return Wa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>kg(t,r))}},Fi=e=>e.startsWith(po)?e.slice(po.length):e,Bo=e=>e.startsWith(po),kg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Lg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Pg=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:Hg(t)}]}},wr=e=>({isError:!0,content:[{type:"text",text:e}]}),Ig=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Wg(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)},
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
6
|
+
${e.description}`:"");return window.confirm(n)},Wg=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)}},Rg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Hg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as ou,STR as su,OBJ as au}from"partial-json";var Ra=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ss=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)}},Bg=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`},iu=e=>e.status==="complete"?Bg(e):e.status==="pending"?"Waiting":"",Dg=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 lu=e=>e.status==="complete"?Dg(e):"Using tool...",Ha=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},qs=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 Ha(t)},Ba=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 Ha(t)},$i=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=qs(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Da=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Us(r,n.slice(o,a.index),[]),a[1]!==void 0?Us(r,a[1],["bold"]):a[2]!==void 0?Us(r,a[2],["italic"]):a[3]!==void 0&&Us(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&Us(r,n.slice(o),[]),r},Us=(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})},Ng=()=>{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&>.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()=>{}}},Do=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},_i=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ji=()=>{var t;let e=Ng();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)}},Ui=()=>{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=ou(n,su|au);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ra(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ra(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Og=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ra(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ra(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=ou(o,su|au),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},qi=()=>{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 Na=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 Fg="https://api.runtype.com/v1/dispatch",Oa="https://api.runtype.com";function $g(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 zi=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 _g(e){switch(e){case"json":return Ui;case"regex-json":return ji;case"xml":return qi;default:return _i}}var cu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function jg(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=cu(n);if(!cu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Do(e);return Do(t)!==null&&a===null?t:e}var as=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:Fg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:_g(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 js(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$/,""))||Oa}/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$/,""))||Oa}/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,u={sessionId:d.sessionId,messages:t.messages.filter(zi).map(P=>{var I,A,M;return{id:P.id,role:P.role,content:(M=(A=(I=P.contentParts)!=null?I:P.llmContent)!=null?A:P.rawContent)!=null?M: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}},f=l.clientTools,m=!!(f&&f.length>0),v=m?ru(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,w=m&&x&&this.lastSentClientToolsFingerprint===v,S=!1,D=null,E;for(let P=0;;P++){let A={...u,...m&&(S||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),E=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),signal:r.signal}),E.status===409&&P===0&&m){let M=await E.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}D=M!=null?M:{error:"Chat request failed"}}break}if(!E.ok){let P=D!=null?D:await E.json().catch(()=>({error:"Chat request failed"}));if(E.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(E.status===429){let A=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:A}),A}let I=new Error(P.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!E.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(E.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$/,""))||Oa}/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(/\/+$/,""))||Oa}/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(zi).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(zi).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 Ht,an,er,Sr;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=W=>{let de=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,De=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Je=W.tools?W.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...W,reasoning:de,toolCall:De,tools:Je}},u=W=>{if(W.role!=="assistant"||W.variant)return!0;let de=Array.isArray(W.contentParts)&&W.contentParts.length>0,De=typeof W.rawContent=="string"&&W.rawContent.trim()!=="";return typeof W.content=="string"&&W.content.trim()!==""||de||De||!!W.stopReason},f=W=>{u(W)&&n({type:"message",message:p(W)})},m=null,v=null,x={current:null},w={current:null},S=!1,D=new Map,E=new Map,P=new Map,I=new Map,A={lastId:null,byStep:new Map},M={lastId:null,byCall:new Map},F=(W,de,De="")=>`${W}::${de}::${De}`,N=(W,de)=>`${W}::${de}::`,R=(W,de,De,Je)=>{let Fe=F(W,de,De),_e=P.get(Fe);if(_e)return _e;let ot=De?`-${De}`:"",Pt={id:`nested-${W}-${de}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Je,parentToolId:W,parentStepId:de}};return P.set(Fe,Pt),f(Pt),Pt},j=W=>{if(W==null)return null;try{return String(W)}catch{return null}},K=W=>{var de,De,Je,Fe,_e;return j((_e=(Fe=(Je=(De=(de=W.stepId)!=null?de:W.step_id)!=null?De:W.step)!=null?Je:W.parentId)!=null?Fe:W.flowStepId)!=null?_e:W.flow_step_id)},le=W=>{var de,De,Je,Fe,_e,ot,Pt;return j((Pt=(ot=(_e=(Fe=(Je=(De=(de=W.callId)!=null?de:W.call_id)!=null?De:W.requestId)!=null?Je:W.request_id)!=null?Fe:W.toolCallId)!=null?_e:W.tool_call_id)!=null?ot:W.stepId)!=null?Pt:W.step_id)},Ee=r,qe=!1,we=()=>{if(m)return m;let W;return!qe&&Ee?(W=Ee,qe=!0):Ee&&w.current?W=`${Ee}_${w.current}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:W,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},Ie=(W,de)=>{A.lastId=de,W&&A.byStep.set(W,de)},he=(W,de)=>{var _e;let De=(_e=W.reasoningId)!=null?_e:W.id,Je=K(W);if(De){let ot=String(De);return Ie(Je,ot),ot}if(Je){let ot=A.byStep.get(Je);if(ot)return A.lastId=ot,ot}if(A.lastId&&!de)return A.lastId;if(!de)return null;let Fe=`reason-${l()}`;return Ie(Je,Fe),Fe},Me=W=>{let de=D.get(W);if(de)return de;let De={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:W,status:"streaming",chunks:[]}};return D.set(W,De),f(De),De},We=(W,de)=>{M.lastId=de,W&&M.byCall.set(W,de)},ce=new Set,X=new Map,ne=new Set,ie=new Map,me=W=>{if(!W)return!1;let de=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return de==="emit_artifact_markdown"||de==="emit_artifact_component"},z=(W,de)=>{var _e;let De=(_e=W.toolId)!=null?_e:W.id,Je=le(W);if(De){let ot=String(De);return We(Je,ot),ot}if(Je){let ot=M.byCall.get(Je);if(ot)return M.lastId=ot,ot}if(M.lastId&&!de)return M.lastId;if(!de)return null;let Fe=`tool-${l()}`;return We(Je,Fe),Fe},oe=W=>{let de=E.get(W);if(de)return de;let De={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:W,status:"pending"}};return E.set(W,De),f(De),De},Re=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let de=Number(W);if(!Number.isNaN(de)&&Number.isFinite(de))return de;let De=Date.parse(W);if(!Number.isNaN(De))return De}return Date.now()},Y=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},Z=new Map,se=new Map,Ce=new Map,Ye=new Map,xe=null,ge=(W,de,De)=>{var Pt;let Je=Ce.get(W);Je||(Je=[],Ce.set(W,Je));let Fe=0,_e=Je.length;for(;Fe<_e;){let Vt=Fe+_e>>>1;Je[Vt].seq<de?Fe=Vt+1:_e=Vt}((Pt=Je[Fe])==null?void 0:Pt.seq)===de?Je[Fe]={seq:de,text:De}:Je.splice(Fe,0,{seq:de,text:De});let ot="";for(let Vt=0;Vt<Je.length;Vt++)ot+=Je[Vt].text;return ot},Ke=(W,de)=>{let De=Y(de),Je=se.get(W.id),Fe=jg(Je,De);W.rawContent=Fe;let _e=Z.get(W.id),ot=xt=>{var ve;let at=(ve=W.content)!=null?ve:"";xt.trim()!==""&&(at.trim().length===0||xt.startsWith(at)||xt.trimStart().startsWith(at.trim()))&&(W.content=xt)},Pt=()=>{var xt;if(_e){let at=(xt=_e.close)==null?void 0:xt.call(_e);at instanceof Promise&&at.catch(()=>{})}Z.delete(W.id),se.delete(W.id),W.streaming=!1,f(W)};if(!_e){ot(De),Pt();return}let Vt=Do(Fe);if(Vt!==null&&Vt.trim()!==""){ot(Vt),Pt();return}let Qt=xt=>{var ae;let at=typeof xt=="string"?xt:(ae=xt==null?void 0:xt.text)!=null?ae:null;if(at!==null&&at.trim()!=="")return at;let ve=_e.getExtractedText();return ve!==null&&ve.trim()!==""?ve:De},V;try{V=_e.processChunk(Fe)}catch{ot(De),Pt();return}if(V instanceof Promise){V.then(xt=>{ot(Qt(xt)),Pt()}).catch(()=>{ot(De),Pt()});return}ot(Qt(V)),Pt()},Be=[],q=!1,pe,nt=()=>{q||(q=!0,queueMicrotask(()=>{q=!1,pe()}))},Mt=new Na((W,de)=>{Be.push({payloadType:W,payload:de}),nt()}),ee=null,ze=new Map,Hn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(pe=()=>{var W,de,De,Je,Fe,_e,ot,Pt,Vt,Qt,V,xt,at,ve,ae,tt,Yt,Kt,Mn,yn,gt,kt,Ze,qt,ln,vn,wn,bn,Tr,At,$n,_n,Dr,gr,vt,Co,Er,Ao,Bn,qo,Gr,Nr,St,jn,Un,kn,Lt,tr,nr,qn,Xr,Or,Qr,zn,Bt,Ln,rr,Yr,Fr,Zr,Mr,Vn,fr,ht,Zt,en,Kn,eo,be,or,sr,$,kr,$r,_r,Lr,hr,ws,Jn,Gn,br,yr,So,jr,Cn,Pr,zo,To,Vo,ga,Ko,fa,Jo,yt,Cs,ar,Dn,ha,ba,Go,Ur,As,to,Ss,Ts,Es,Ms,Nn,Xo,Ir,Wr,ks,ya,Ls,Ps,Eo,xa,va,wa,Ca,Wi,Mo,no,Aa,Is,ro,Sa,Ws,oo,Rs,Ta,qr,Ea,so,Dt,Qo,Yo,Hs;for(let ir=0;ir<Be.length;ir++){let Ge=Be[ir].payloadType,C=Be[ir].payload;if(Ge==="reason_start"){let _=(W=he(C,!0))!=null?W:`reason-${l()}`,k=Me(_);k.reasoning=(de=k.reasoning)!=null?de:{id:_,status:"streaming",chunks:[]},k.reasoning.startedAt=(Je=k.reasoning.startedAt)!=null?Je:Re((De=C.startedAt)!=null?De:C.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",f(k)}else if(Ge==="reason_delta"||Ge==="reason_chunk"){let _=(_e=(Fe=he(C,!1))!=null?Fe:he(C,!0))!=null?_e:`reason-${l()}`,k=Me(_);k.reasoning=(ot=k.reasoning)!=null?ot:{id:_,status:"streaming",chunks:[]},k.reasoning.startedAt=(Vt=k.reasoning.startedAt)!=null?Vt:Re((Pt=C.startedAt)!=null?Pt:C.timestamp);let Q=(xt=(V=(Qt=C.reasoningText)!=null?Qt:C.text)!=null?V:C.delta)!=null?xt:"";if(Q&&C.hidden!==!0){let re=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(re!==void 0){let J=ge(_,re,String(Q));k.reasoning.chunks=[J]}else k.reasoning.chunks.push(String(Q))}if(k.reasoning.status=C.done?"complete":"streaming",C.done){k.reasoning.completedAt=Re((at=C.completedAt)!=null?at:C.timestamp);let re=(ve=k.reasoning.startedAt)!=null?ve:Date.now();k.reasoning.durationMs=Math.max(0,((ae=k.reasoning.completedAt)!=null?ae:Date.now())-re)}k.streaming=k.reasoning.status!=="complete",f(k)}else if(Ge==="reason_complete"){let _=(Yt=(tt=he(C,!1))!=null?tt:he(C,!0))!=null?Yt:`reason-${l()}`,k=D.get(_);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=Re((Kt=C.completedAt)!=null?Kt:C.timestamp);let re=(Mn=k.reasoning.startedAt)!=null?Mn:Date.now();k.reasoning.durationMs=Math.max(0,((yn=k.reasoning.completedAt)!=null?yn:Date.now())-re),k.streaming=!1,f(k)}let Q=K(C);Q&&A.byStep.delete(Q)}else if(Ge==="tool_start"){let _=(gt=z(C,!0))!=null?gt:`tool-${l()}`,k=(kt=C.toolName)!=null?kt:C.name;if(me(k)){ce.add(_);continue}let Q=oe(_),re=(Ze=Q.toolCall)!=null?Ze:{id:_,status:"pending"};re.name=k!=null?k:re.name,re.status="running",C.args!==void 0?re.args=C.args:C.parameters!==void 0&&(re.args=C.parameters),re.startedAt=(ln=re.startedAt)!=null?ln:Re((qt=C.startedAt)!=null?qt:C.timestamp),re.completedAt=void 0,re.durationMs=void 0,Q.toolCall=re,Q.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(Q.agentMetadata={executionId:(vn=J==null?void 0:J.executionId)!=null?vn:C.executionId,iteration:(wn=J==null?void 0:J.iteration)!=null?wn:C.iteration}),f(Q)}else if(Ge==="tool_chunk"||Ge==="tool_delta"){let _=(Tr=(bn=z(C,!1))!=null?bn:z(C,!0))!=null?Tr:`tool-${l()}`;if(ce.has(_))continue;let k=oe(_),Q=(At=k.toolCall)!=null?At:{id:_,status:"running"};Q.startedAt=(_n=Q.startedAt)!=null?_n:Re(($n=C.startedAt)!=null?$n:C.timestamp);let re=(vt=(gr=(Dr=C.text)!=null?Dr:C.delta)!=null?gr:C.message)!=null?vt:"";re&&(Q.chunks=(Co=Q.chunks)!=null?Co:[],Q.chunks.push(String(re))),Q.status="running",k.toolCall=Q,k.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(k.agentMetadata=(Bn=k.agentMetadata)!=null?Bn:{executionId:(Er=J==null?void 0:J.executionId)!=null?Er:C.executionId,iteration:(Ao=J==null?void 0:J.iteration)!=null?Ao:C.iteration}),f(k)}else if(Ge==="tool_complete"){let _=(Gr=(qo=z(C,!1))!=null?qo:z(C,!0))!=null?Gr:`tool-${l()}`;if(ce.has(_)){ce.delete(_);continue}let k=oe(_),Q=(Nr=k.toolCall)!=null?Nr:{id:_,status:"running"};Q.status="complete",C.result!==void 0&&(Q.result=C.result),typeof C.duration=="number"&&(Q.duration=C.duration),Q.completedAt=Re((St=C.completedAt)!=null?St:C.timestamp);let re=(jn=C.duration)!=null?jn:C.executionTime;if(typeof re=="number")Q.durationMs=re;else{let Oe=(Un=Q.startedAt)!=null?Un:Date.now();Q.durationMs=Math.max(0,((kn=Q.completedAt)!=null?kn:Date.now())-Oe)}k.toolCall=Q,k.streaming=!1;let J=C.agentContext;(J||C.executionId)&&(k.agentMetadata=(nr=k.agentMetadata)!=null?nr:{executionId:(Lt=J==null?void 0:J.executionId)!=null?Lt:C.executionId,iteration:(tr=J==null?void 0:J.iteration)!=null?tr:C.iteration}),f(k);let Le=le(C);Le&&M.byCall.delete(Le)}else if(Ge==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let _=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,k=(qn=_!=null?_:C.toolId)!=null?qn:`local-${l()}`,Q=oe(k),re=C.toolName,J=Bo(re),Le=(Xr=Q.toolCall)!=null?Xr:{id:k,status:"pending"};Le.name=re,Le.args=C.parameters,Le.status=J?"running":"complete",Le.chunks=(Or=Le.chunks)!=null?Or:[],Le.startedAt=(zn=Le.startedAt)!=null?zn:Re((Qr=C.startedAt)!=null?Qr:C.timestamp),J?(Le.completedAt=void 0,Le.duration=void 0,Le.durationMs=void 0):Le.completedAt=(Bt=Le.completedAt)!=null?Bt:Le.startedAt,Q.toolCall=Le,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(rr=C.executionId)!=null?rr:(Ln=Q.agentMetadata)==null?void 0:Ln.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},f(Q)}else if(Ge==="text_start"){if((Yr=C.toolContext)!=null&&Yr.toolId)continue;let _=C.partId;if(_!==void 0&&w.current!==null&&_!==w.current){let k=m;k&&(k.streaming=!1,f(k),xe=k,m=null,S=!0)}_!==void 0&&(w.current=_)}else if(Ge==="text_end"){if((Fr=C.toolContext)!=null&&Fr.toolId)continue;let _=m;_&&(_.streaming=!1,f(_),xe=_,m=null,S=!0)}else if(Ge==="step_chunk"||Ge==="step_delta"){let _=C.stepType,k=C.executionType;if(_==="tool"||k==="context")continue;let Q=C.toolContext;if(Q!=null&&Q.toolId){let Oe=String((Mr=(Zr=C.id)!=null?Zr:Q.stepId)!=null?Mr:`step-${l()}`),it=C.partId!==void 0&&C.partId!==null?String(C.partId):"",et=`${Q.toolId}::${Oe}`,Rt=I.get(et);if(it!==""&&Rt!==void 0&&Rt!==""&&Rt!==it){let lt=P.get(F(Q.toolId,Oe,Rt));lt&<.streaming!==!1&&(lt.streaming=!1,f(lt))}it!==""&&I.set(et,it);let _t=R(Q.toolId,Oe,it,Q.executionId),Ot=(Zt=(ht=(fr=(Vn=C.text)!=null?Vn:C.delta)!=null?fr:C.content)!=null?ht:C.chunk)!=null?Zt:"";Ot&&(_t.content+=String(Ot),_t.streaming=!0,f(_t)),C.isComplete&&(_t.streaming=!1,f(_t));continue}let re=C.partId;if(re!==void 0&&w.current!==null&&re!==w.current){let Oe=m;Oe&&(Oe.streaming=!1,f(Oe),xe=Oe,m=null,S=!0)}re!==void 0&&(w.current=re);let J=re!==void 0&&(en=Ye.get(re))!=null?en:we();re!==void 0&&(J.partId||(J.partId=re),Ye.set(re,J));let Le=(or=(be=(eo=(Kn=C.text)!=null?Kn:C.delta)!=null?eo:C.content)!=null?be:C.chunk)!=null?or:"";if(Le){let Oe=typeof C.seq=="number"?C.seq:void 0,it=re!=null?re:J.id,et=Oe!==void 0?ge(it,Oe,String(Le)):((sr=se.get(J.id))!=null?sr:"")+Le;J.rawContent=et,Z.has(J.id)||Z.set(J.id,this.createStreamParser());let Rt=Z.get(J.id),_t=et.trim().startsWith("{")||et.trim().startsWith("[");if(_t&&se.set(J.id,et),Rt.__isPlainTextParser===!0){J.content=Oe!==void 0?et:J.content+Le,se.delete(J.id),Z.delete(J.id),J.rawContent=void 0,f(J);continue}let lt=Rt.processChunk(et);if(lt instanceof Promise)lt.then(Tt=>{var An;let je=typeof Tt=="string"?Tt:(An=Tt==null?void 0:Tt.text)!=null?An:null;if(je!==null&&je.trim()!=="")J.content=je,f(J);else if(!_t&&!et.trim().startsWith("<")){let mn=m,jt=mn&&mn.id===J.id?mn:J;jt.id===J.id&&(jt.content=Oe!==void 0?et:jt.content+Le,se.delete(jt.id),Z.delete(jt.id),jt.rawContent=void 0,f(jt))}}).catch(()=>{J.content=Oe!==void 0?et:J.content+Le,se.delete(J.id),Z.delete(J.id),J.rawContent=void 0,f(J)});else{let Tt=typeof lt=="string"?lt:($=lt==null?void 0:lt.text)!=null?$:null;Tt!==null&&Tt.trim()!==""?(J.content=Tt,f(J)):!_t&&!et.trim().startsWith("<")&&(J.content=Oe!==void 0?et:J.content+Le,se.delete(J.id),Z.delete(J.id),J.rawContent=void 0,f(J))}}if(C.isComplete){let Oe=($r=(kr=C.result)==null?void 0:kr.response)!=null?$r:J.content;if(Oe){let it=se.get(J.id),et=it!=null?it:Y(Oe);J.rawContent=et;let Rt=Z.get(J.id),_t=null,Ot=!1;if(Rt&&(_t=Rt.getExtractedText(),_t===null&&(_t=Do(et)),_t===null)){let lt=Rt.processChunk(et);lt instanceof Promise?(Ot=!0,lt.then(Tt=>{var An;let je=typeof Tt=="string"?Tt:(An=Tt==null?void 0:Tt.text)!=null?An:null;if(je!==null){let mn=m;mn&&mn.id===J.id&&(mn.content=je,mn.streaming=!1,Z.delete(mn.id),se.delete(mn.id),f(mn))}})):_t=typeof lt=="string"?lt:(_r=lt==null?void 0:lt.text)!=null?_r:null}if(!Ot){_t!==null&&_t.trim()!==""?J.content=_t:se.has(J.id)||(J.content=Y(Oe));let lt=Z.get(J.id);if(lt){let Tt=(Lr=lt.close)==null?void 0:Lr.call(lt);Tt instanceof Promise&&Tt.catch(()=>{}),Z.delete(J.id)}se.delete(J.id),J.streaming=!1,f(J)}}}}else if(Ge==="step_complete"){let _=C.stepType,k=C.executionType;if(_==="tool"||k==="context")continue;let Q=C.toolContext;if(Q!=null&&Q.toolId){let Oe=String((ws=(hr=C.id)!=null?hr:Q.stepId)!=null?ws:"");if(Oe){let it=N(Q.toolId,Oe);for(let[et,Rt]of P)et.startsWith(it)&&Rt.streaming!==!1&&(Rt.streaming=!1,f(Rt));I.delete(`${Q.toolId}::${Oe}`)}continue}let re=C.stopReason;if(S){if(m!==null){let et=m;re&&(et.stopReason=re),Z.delete(et.id),se.delete(et.id),et.streaming!==!1&&(et.streaming=!1,f(et))}let Oe=(Jn=C.result)==null?void 0:Jn.response,it=xe;it&&(re&&(it.stopReason=re),Oe!=null?Ke(it,Oe):(Z.delete(it.id),se.delete(it.id))),xe=null;continue}let J=(Gn=C.result)==null?void 0:Gn.response,Le=we();if(re&&(Le.stopReason=re),J!=null){let Oe=Z.get(Le.id),it=!1,et=!1;if(Oe){let Rt=Oe.getExtractedText(),_t=se.get(Le.id),Ot=_t!=null?_t:Y(J);if(Le.rawContent=Ot,Rt!==null&&Rt.trim()!=="")Le.content=Rt,it=!0;else{let lt=Do(Ot);if(lt!==null)Le.content=lt,it=!0;else{let Tt=Oe.processChunk(Ot);if(Tt instanceof Promise)et=!0,Tt.then(je=>{var mn;let An=typeof je=="string"?je:(mn=je==null?void 0:je.text)!=null?mn:null;if(An!==null&&An.trim()!==""){let jt=m;jt&&jt.id===Le.id&&(jt.content=An,jt.streaming=!1,Z.delete(jt.id),se.delete(jt.id),f(jt))}else{let jt=Oe.getExtractedText(),xr=m;xr&&xr.id===Le.id&&(jt!==null&&jt.trim()!==""?xr.content=jt:se.has(xr.id)||(xr.content=Y(J)),xr.streaming=!1,Z.delete(xr.id),se.delete(xr.id),f(xr))}});else{let je=typeof Tt=="string"?Tt:(br=Tt==null?void 0:Tt.text)!=null?br:null;if(je!==null&&je.trim()!=="")Le.content=je,it=!0;else{let An=Oe.getExtractedText();An!==null&&An.trim()!==""&&(Le.content=An,it=!0)}}}}}if(!et){if(!Le.rawContent){let Rt=se.get(Le.id);Le.rawContent=Rt!=null?Rt:Y(J)}if(!it&&!se.has(Le.id)&&(Le.content=Y(J)),Oe){let Rt=(yr=Oe.close)==null?void 0:yr.call(Oe);Rt instanceof Promise&&Rt.catch(()=>{})}Z.delete(Le.id),se.delete(Le.id),Le.streaming=!1,f(Le)}}else Z.delete(Le.id),se.delete(Le.id),Le.streaming=!1,f(Le)}else if(Ge==="flow_complete"){let _=(So=C.result)==null?void 0:So.response;if(S){if(m!==null){let k=m;Z.delete(k.id),se.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}}else if(_!=null){let k=we(),Q=se.get(k.id),re=Q!=null?Q:Y(_);k.rawContent=re;let J=Y(_),Le=Z.get(k.id);if(Le){let et=Do(re);if(et!==null)J=et;else{let Rt=Le.processChunk(re);Rt instanceof Promise&&Rt.then(Ot=>{var Tt;let lt=typeof Ot=="string"?Ot:(Tt=Ot==null?void 0:Ot.text)!=null?Tt:null;lt!==null&&(k.content=lt,k.streaming=!1,f(k))});let _t=Le.getExtractedText();_t!==null&&(J=_t)}}Z.delete(k.id),se.delete(k.id);let Oe=J!==k.content,it=k.streaming!==!1;Oe&&(k.content=J),k.streaming=!1,(Oe||it)&&f(k)}else if(m!==null){let k=m;Z.delete(k.id),se.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}n({type:"status",status:"idle"})}else if(Ge==="agent_start")ee={executionId:C.executionId,agentId:(jr=C.agentId)!=null?jr:"virtual",agentName:(Cn=C.agentName)!=null?Cn:"",status:"running",currentIteration:0,maxTurns:(Pr=C.maxTurns)!=null?Pr:1,startedAt:Re(C.startedAt)};else if(Ge==="agent_iteration_start"){if(ee&&(ee.currentIteration=C.iteration),Hn==="separate"&&C.iteration>1){let _=m;_&&(_.streaming=!1,f(_),ze.set(C.iteration-1,_),m=null)}}else if(Ge==="agent_turn_start")v=null;else if(Ge==="agent_turn_delta"){if(C.contentType==="text"){let _=we();_.content+=(zo=C.delta)!=null?zo:"",_.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:ee==null?void 0:ee.agentName},v=_,f(_)}else if(C.contentType==="thinking"){let _=(To=C.turnId)!=null?To:`agent-think-${C.iteration}`,k=Me(_);k.reasoning=(Vo=k.reasoning)!=null?Vo:{id:_,status:"streaming",chunks:[]},k.reasoning.chunks.push((ga=C.delta)!=null?ga:""),k.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},f(k)}else if(C.contentType==="tool_input"){let _=(Ko=C.toolCallId)!=null?Ko:M.lastId;if(_){let k=E.get(_);k!=null&&k.toolCall&&(k.toolCall.chunks=(fa=k.toolCall.chunks)!=null?fa:[],k.toolCall.chunks.push((Jo=C.delta)!=null?Jo:""),f(k))}}}else if(Ge==="agent_turn_complete"){let _=C.turnId;if(_){let re=D.get(_);if(re!=null&&re.reasoning){re.reasoning.status="complete",re.reasoning.completedAt=Re(C.completedAt);let J=(yt=re.reasoning.startedAt)!=null?yt:Date.now();re.reasoning.durationMs=Math.max(0,((Cs=re.reasoning.completedAt)!=null?Cs:Date.now())-J),re.streaming=!1,f(re)}}let k=C.stopReason,Q=m!=null?m:v;if(k&&Q!==null){let re=C.turnId;(!re||((ar=Q.agentMetadata)==null?void 0:ar.turnId)===re)&&(Q.stopReason=k,f(Q))}}else if(Ge==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let _=(Dn=C.toolCallId)!=null?Dn:`agent-tool-${l()}`;We(le(C),_);let k=oe(_),Q=(ha=k.toolCall)!=null?ha:{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};Q.name=(Go=(ba=C.toolName)!=null?ba:C.name)!=null?Go:Q.name,Q.status="running",C.parameters!==void 0&&(Q.args=C.parameters),Q.startedAt=Re((Ur=C.startedAt)!=null?Ur:C.timestamp),k.toolCall=Q,k.streaming=!0,k.agentMetadata={executionId:C.executionId,iteration:C.iteration},f(k)}else if(Ge==="agent_tool_delta"){let _=(As=C.toolCallId)!=null?As:M.lastId;if(_){let k=(to=E.get(_))!=null?to:oe(_);k.toolCall&&(k.toolCall.chunks=(Ss=k.toolCall.chunks)!=null?Ss:[],k.toolCall.chunks.push((Ts=C.delta)!=null?Ts:""),k.toolCall.status="running",k.streaming=!0,f(k))}}else if(Ge==="agent_tool_complete"){let _=(Es=C.toolCallId)!=null?Es:M.lastId;if(_){let k=(Ms=E.get(_))!=null?Ms:oe(_);if(k.toolCall){k.toolCall.status="complete",C.result!==void 0&&(k.toolCall.result=C.result),typeof C.executionTime=="number"&&(k.toolCall.durationMs=C.executionTime),k.toolCall.completedAt=Re((Nn=C.completedAt)!=null?Nn:C.timestamp),k.streaming=!1,f(k);let Q=le(C);Q&&M.byCall.delete(Q)}}}else if(Ge==="agent_media"){let _=Array.isArray(C.media)?C.media:[],k=[];for(let Q of _){if(!Q||typeof Q!="object")continue;let re=Q,J=typeof re.type=="string"?re.type:void 0,Le=typeof re.mediaType=="string"?re.mediaType.toLowerCase():"",Oe=null,it="";if(J==="media"){let et=typeof re.data=="string"?re.data:void 0;if(!et)continue;it=Le.length>0?Le:"application/octet-stream",Oe=`data:${it};base64,${et}`}else if(J==="image-url"){let et=typeof re.url=="string"?re.url:void 0;if(!et)continue;it=Le,Oe=et}else if(J==="file-url"){let et=typeof re.url=="string"?re.url:void 0;if(!et)continue;it=Le,Oe=et}else continue;if(Oe)if(J==="image-url"||it.startsWith("image/"))k.push({type:"image",image:Oe,...it?{mimeType:it}:{}});else if(it.startsWith("audio/"))k.push({type:"audio",audio:Oe,mimeType:it});else if(it.startsWith("video/"))k.push({type:"video",video:Oe,mimeType:it});else{let et=it||"application/octet-stream";k.push({type:"file",data:Oe,mimeType:et,filename:$g(et)})}}if(k.length>0){let Q=l(),re=C.toolCallId,Le={id:`agent-media-${typeof re=="string"&&re.length>0?`${re}-${Q}`:String(Q)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Q,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(Le);let Oe=m;Oe&&(Oe.streaming=!1,f(Oe)),m=null,x.current=null}}else if(Ge!=="agent_iteration_complete"){if(Ge==="agent_reflection"||Ge==="agent_reflect"){let _=`agent-reflection-${C.executionId}-${C.iteration}`,k={id:_,role:"assistant",content:(Xo=C.reflection)!=null?Xo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"complete",chunks:[(Ir=C.reflection)!=null?Ir:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(k)}else if(Ge==="agent_complete"){ee&&(ee.status=C.success?"complete":"error",ee.completedAt=Re(C.completedAt),ee.stopReason=C.stopReason);let _=m;_&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"})}else if(Ge==="agent_error"){let _=typeof C.error=="string"?C.error:(ks=(Wr=C.error)==null?void 0:Wr.message)!=null?ks:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",_):n({type:"error",error:new Error(_)})}else if(Ge!=="agent_ping"){if(Ge==="agent_approval_start"){let _=(ya=C.approvalId)!=null?ya:`approval-${l()}`,k={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:"pending",agentId:(Ls=ee==null?void 0:ee.agentId)!=null?Ls:"virtual",executionId:(Eo=(Ps=C.executionId)!=null?Ps:ee==null?void 0:ee.executionId)!=null?Eo:"",toolName:(xa=C.toolName)!=null?xa:"",toolType:C.toolType,description:(wa=C.description)!=null?wa:`Execute ${(va=C.toolName)!=null?va:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ge==="step_await"&&C.awaitReason==="approval_required"){let _=(Ca=C.approvalId)!=null?Ca:`approval-${l()}`,k={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:"pending",agentId:(Wi=ee==null?void 0:ee.agentId)!=null?Wi:"virtual",executionId:(no=(Mo=C.executionId)!=null?Mo:ee==null?void 0:ee.executionId)!=null?no:"",toolName:(Aa=C.toolName)!=null?Aa:"",toolType:C.toolType,description:(ro=C.description)!=null?ro:`Execute ${(Is=C.toolName)!=null?Is:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ge==="agent_approval_complete"){let _=C.approvalId;if(_){let Q={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:(Sa=C.decision)!=null?Sa:"approved",agentId:(Ws=ee==null?void 0:ee.agentId)!=null?Ws:"virtual",executionId:(Rs=(oo=C.executionId)!=null?oo:ee==null?void 0:ee.executionId)!=null?Rs:"",toolName:(Ta=C.toolName)!=null?Ta:"",description:(qr=C.description)!=null?qr:"",resolvedAt:Date.now()}};f(Q)}}else if(Ge==="artifact_start"||Ge==="artifact_delta"||Ge==="artifact_update"||Ge==="artifact_complete"){if(Ge==="artifact_start"){let _=C.artifactType,k=String(C.id),Q=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:k,artifactType:_,title:Q,component:typeof C.component=="string"?C.component:void 0}),ie.set(k,{markdown:"",title:Q}),!ne.has(k)){ne.add(k);let re={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Q,artifactType:_,status:"streaming"}})};X.set(k,re),f(re)}}else if(Ge==="artifact_delta"){let _=String(C.id),k=typeof C.delta=="string"?C.delta:String((Ea=C.delta)!=null?Ea:"");n({type:"artifact_delta",id:_,artDelta:k});let Q=ie.get(_);Q&&(Q.markdown+=k)}else if(Ge==="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(Ge==="artifact_complete"){let _=String(C.id);n({type:"artifact_complete",id:_});let k=X.get(_);if(k){k.streaming=!1;try{let Q=JSON.parse((so=k.rawContent)!=null?so:"{}");if(Q.props){Q.props.status="complete";let re=ie.get(_);re!=null&&re.markdown&&(Q.props.markdown=re.markdown)}k.rawContent=JSON.stringify(Q)}catch{}ie.delete(_),f(k),X.delete(_)}}}else if(Ge==="transcript_insert"){let _=C.message;if(!_||typeof _!="object")continue;let k=String((Dt=_.id)!=null?Dt:`msg-${l()}`),Q=_.role,J={id:k,role:Q==="user"?"user":Q==="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 Le=JSON.parse(J.rawContent),Oe=(Qo=Le==null?void 0:Le.props)==null?void 0:Qo.artifactId;typeof Oe=="string"&&ne.add(Oe)}catch{}m=null,x.current=null,Z.delete(k),se.delete(k)}else if(Ge==="error"||Ge==="step_error"||Ge==="dispatch_error"||Ge==="flow_error"){let _=null;if(C.error instanceof Error)_=C.error;else if(Ge==="dispatch_error"){let k=(Yo=C.message)!=null?Yo:C.error;k!=null&&k!==""&&(_=new Error(String(k)))}else if(Ge==="step_error"||Ge==="flow_error"){let k=C.error;typeof k=="string"&&k!==""?_=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&(_=new Error(String((Hs=k.message)!=null?Hs:k)))}else Ge==="error"&&C.error!=null&&C.error!==""&&(_=new Error(String(C.error)));if(_){n({type:"error",error:_});let k=m;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:W,value:de}=await s.read();if(W)break;a+=o.decode(de,{stream:!0});let De=a.split(`
|
|
10
10
|
|
|
11
|
-
`);a=(
|
|
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=(an=De.pop())!=null?an:"";for(let Je of De){let Fe=Je.split(`
|
|
12
|
+
`),_e="message",ot="";for(let Qt of Fe)Qt.startsWith("event:")?_e=Qt.replace("event:","").trim():Qt.startsWith("data:")&&(ot+=Qt.replace("data:","").trim());if(!ot)continue;let Pt;try{Pt=JSON.parse(ot)}catch(Qt){n({type:"error",error:Qt instanceof Error?Qt:new Error("Failed to parse chat stream payload")});continue}let Vt=_e!=="message"?_e:(er=Pt.type)!=null?er:"message";if((Sr=this.onSSEEvent)==null||Sr.call(this,Vt,Pt),this.parseSSEEvent){x.current=m;let Qt=await this.handleCustomSSEEvent(Pt,n,x,f,l,w);if(x.current&&x.current!==m&&(m=x.current),Qt)continue}Mt.push(Vt,Pt),pe()}}Mt.flushPending(),pe(),Mt.destroy()}};function Ug(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function zs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function is(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Fa="[Image]";function qg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function zg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Vg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Kg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function $a(e){return{type:"text",text:e}}function Jg(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 Gg(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 Xg(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 du=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Qg=["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"],Vr=[...du,...Qg];function Yg(e){return du.includes(e)||e.startsWith("image/")}function _a(e){return Yg(e.type)}async function pu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;_a(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 uu(e,t=Vr,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 Zg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function mu(e,t){let n=Zg(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 ja=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 Ua=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 Vs=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 Ua;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 D=S.code!==1006?` (code ${S.code})`:"";x("WebSocket connection failed"+D+"."+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 ja(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 No=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 ls(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Vs(e.runtype);case"browser":if(!No.isSupported())throw new Error("Browser speech recognition not supported");return new No(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Vi(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ls({type:"runtype",runtype:e.runtype});if(No.isSupported())return ls({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function qa(e){try{return Vi(e),!0}catch{return!1}}function gu(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},
|
|
14
|
+
_Details: ${n.message}_`:r}var Ks=e=>({isError:!0,content:[{type:"text",text:e}]}),fu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Js=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)&&Bo(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 as(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 qa((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=ls(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 as(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"?zs():n==="assistant"?is():`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"?zs():s==="assistant"?is():`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=zs(),o=is(),a={id:s,role:"user",content:r||Fa,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=gu(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=is();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=gu(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,D,E,P,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,M=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(M.length===1){let F=typeof((w=M[0])==null?void 0:w.question)=="string"?M[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=(D=t.toolCall)==null?void 0:D.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(([M,F])=>`${M}: ${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((M,F)=>{let N=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!N)return;let R=A[N],j=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(s,{[o]:n});if(!A.ok){let M=await A.json().catch(()=>null);throw new Error((E=M==null?void 0:M.error)!=null?E:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let M=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(I=(P=this.callbacks).onError)==null||I.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 u=>{var P,I,A,M,F,N,R;let f=(P=u.toolCall)==null?void 0:P.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=(M=(A=u.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?M:f,D=this.client.executeWebMcpToolCall(f,(F=u.toolCall)==null?void 0:F.args,w.signal),E;if(!D)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await D}catch(j){let K=j instanceof Error&&(j.name==="AbortError"||j.message.includes("aborted")||j.message.includes("abort"));return K||(R=(N=this.callbacks).onError)==null||R.call(N,j instanceof Error?j:new Error(String(j))),this.markWebMcpToolComplete(u,Ks(K?"Aborted by cancel()":fu(j)),x),this.webMcpInflightKeys.delete(v),null}return w.signal.aborted?(this.markWebMcpToolComplete(u,Ks("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:S,output:E,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,Ks("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,D,E,P,I,A,M,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 N=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(N)||this.webMcpResolvedKeys.has(N))return;this.webMcpInflightKeys.add(N);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(N)}catch(R){(E=(D=this.callbacks).onError)==null||E.call(D,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(N)}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),u="execute",f=a;try{let N;if(p?N=await p:N={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ks("Aborted by cancel()"),a);return}let R=(A=(I=t.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?A:r;u="resume",await this.resumeWithToolOutput(n,R,N,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,N,a,f)},signal:d})}catch(N){let R=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));(u==="execute"||R||d.aborted)&&this.markWebMcpToolComplete(t,Ks(R||d.aborted?"Aborted by cancel()":fu(N)),a),R||(F=(M=this.callbacks).onError)==null||F.call(M,N instanceof Error?N:new Error(String(N)))}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,D,E,P,I,A;if(o!==r)return s;let a={...s,...n};if(((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}),s.approval&&n.approval&&s.approval.id===n.approval.id){let M=s.approval,F=n.approval;a.approval={...M,...F,executionId:F.executionId||M.executionId,toolName:F.toolName||M.toolName,description:F.description||M.description,toolType:(u=F.toolType)!=null?u:M.toolType,reason:(f=F.reason)!=null?f:M.reason,parameters:(m=F.parameters)!=null?m:M.parameters}}let i=(v=n.toolCall)==null?void 0:v.name,d=(x=n.agentMetadata)==null?void 0:x.executionId,l=(w=n.toolCall)==null?void 0:w.id;if(i&&Bo(i)&&d&&l&&((S=n.agentMetadata)==null?void 0:S.awaitingLocalTool)===!0){let M=`${d}:${l}`,F=this.webMcpInflightKeys.has(M),N=this.webMcpResolvedKeys.has(M),R=(D=s.toolCall)==null?void 0:D.name,j=((E=s.agentMetadata)==null?void 0:E.executionId)===d&&((P=s.toolCall)==null?void 0:P.id)===l&&R!==void 0&&Bo(R)&&((I=s.toolCall)==null?void 0:I.status)==="complete";(F||N||j)&&(a.agentMetadata={...(A=a.agentMetadata)!=null?A:{},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},Hr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import{Activity as ef,ArrowDown as tf,ArrowUp as nf,ArrowUpRight as rf,Bot as of,ChevronDown as sf,ChevronUp as af,ChevronRight as lf,ChevronLeft as cf,Check as df,Clipboard as pf,ClipboardCopy as uf,Copy as mf,File as gf,FileCode as ff,FileSpreadsheet as hf,FileText as bf,ImagePlus as yf,Loader as xf,LoaderCircle as vf,Mic as wf,Paperclip as Cf,RefreshCw as Af,Search as Sf,Send as Tf,ShieldAlert as Ef,ShieldCheck as Mf,ShieldX as kf,Square as Lf,ThumbsDown as Pf,ThumbsUp as If,Upload as Wf,Volume2 as Rf,X as Hf,User as Bf,Mail as Df,Phone as Nf,Calendar as Of,Clock as Ff,Building as $f,MapPin as _f,Lock as jf,Key as Uf,CreditCard as qf,AtSign as zf,Hash as Vf,Globe as Kf,Link as Jf,CircleCheck as Gf,CircleX as Xf,TriangleAlert as Qf,Info as Yf,Ban as Zf,Shield as eh,ArrowLeft as th,ArrowRight as nh,ExternalLink as rh,Ellipsis as oh,EllipsisVertical as sh,Menu as ah,House as ih,Plus as lh,Minus as ch,Pencil as dh,Trash as ph,Trash2 as uh,Save as mh,Download as gh,Share as fh,Funnel as hh,Settings as bh,RotateCw as yh,Maximize as xh,Minimize as vh,ShoppingCart as wh,ShoppingBag as Ch,Package as Ah,Truck as Sh,Tag as Th,Gift as Eh,Receipt as Mh,Wallet as kh,Store as Lh,DollarSign as Ph,Percent as Ih,Play as Wh,Pause as Rh,VolumeX as Hh,Camera as Bh,Image as Dh,Film as Nh,Headphones as Oh,MessageCircle as Fh,MessageSquare as $h,Bell as _h,Heart as jh,Star as Uh,Eye as qh,EyeOff as zh,Bookmark as Vh,CalendarDays as Kh,History as Jh,Timer as Gh,Folder as Xh,FolderOpen as Qh,Files as Yh,Sparkles as Zh,Zap as eb,Sun as tb,Moon as nb,Flag as rb,Monitor as ob,Smartphone as sb}from"lucide";var ab={activity:ef,"arrow-down":tf,"arrow-up":nf,"arrow-up-right":rf,bot:of,"chevron-down":sf,"chevron-up":af,"chevron-right":lf,"chevron-left":cf,check:df,clipboard:pf,"clipboard-copy":uf,copy:mf,file:gf,"file-code":ff,"file-spreadsheet":hf,"file-text":bf,"image-plus":yf,loader:xf,"loader-circle":vf,mic:wf,paperclip:Cf,"refresh-cw":Af,search:Sf,send:Tf,"shield-alert":Ef,"shield-check":Mf,"shield-x":kf,square:Lf,"thumbs-down":Pf,"thumbs-up":If,upload:Wf,"volume-2":Rf,x:Hf,user:Bf,mail:Df,phone:Nf,calendar:Of,clock:Ff,building:$f,"map-pin":_f,lock:jf,key:Uf,"credit-card":qf,"at-sign":zf,hash:Vf,globe:Kf,link:Jf,"circle-check":Gf,"circle-x":Xf,"triangle-alert":Qf,info:Yf,ban:Zf,shield:eh,"arrow-left":th,"arrow-right":nh,"external-link":rh,ellipsis:oh,"ellipsis-vertical":sh,menu:ah,house:ih,plus:lh,minus:ch,pencil:dh,trash:ph,"trash-2":uh,save:mh,download:gh,share:fh,funnel:hh,settings:bh,"rotate-cw":yh,maximize:xh,minimize:vh,"shopping-cart":wh,"shopping-bag":Ch,package:Ah,truck:Sh,tag:Th,gift:Eh,receipt:Mh,wallet:kh,store:Lh,"dollar-sign":Ph,percent:Ih,play:Wh,pause:Rh,"volume-x":Hh,camera:Bh,image:Dh,film:Nh,headphones:Oh,"message-circle":Fh,"message-square":$h,bell:_h,heart:jh,star:Uh,eye:qh,"eye-off":zh,bookmark:Vh,"calendar-days":Kh,history:Jh,timer:Gh,folder:Xh,"folder-open":Qh,files:Yh,sparkles:Zh,zap:eb,sun:tb,moon:nb,flag:rb,monitor:ob,smartphone:sb},Se=(e,t=24,n="currentColor",r=2)=>{let s=ab[e];return s?ib(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 ib(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 za={allowedTypes:Vr,maxFileSize:10*1024*1024,maxFiles:4};function lb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cb(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 cs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:za.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:za.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:za.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:za.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=uu(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 pu(l),f=_a(l)?URL.createObjectURL(l):null,m={id:lb(),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=_a(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=cb(t.file.type),d=Se(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=mu(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=Se("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 hu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Gs(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];hu(o)&&hu(s)?n[r]=Gs(o,s):n[r]=s}return n}var pr="min(440px, calc(100vw - 24px))",Ki="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:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},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 bu(e,t){if(!(!e&&!t))return e?t?Gs(e,t):e:t}function Ji(e){var t,n,r,s,o,a,i,d,l,p,u,f,m,v,x,w,S,D,E,P,I;return e?{...$t,...e,theme:bu($t.theme,e.theme),darkTheme:bu($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 ce,X,ne,ie,me,z,oe,Re,Y,Z;let A=(ce=$t.features)==null?void 0:ce.artifacts,M=(X=e.features)==null?void 0:X.artifacts,F=(ne=$t.features)==null?void 0:ne.scrollToBottom,N=(ie=e.features)==null?void 0:ie.scrollToBottom,R=(me=$t.features)==null?void 0:me.scrollBehavior,j=(z=e.features)==null?void 0:z.scrollBehavior,K=(oe=$t.features)==null?void 0:oe.streamAnimation,le=(Re=e.features)==null?void 0:Re.streamAnimation,Ee=(Y=$t.features)==null?void 0:Y.askUserQuestion,qe=(Z=e.features)==null?void 0:Z.askUserQuestion,we=A===void 0&&M===void 0?void 0:{...A,...M,layout:{...A==null?void 0:A.layout,...M==null?void 0:M.layout}},Ie=F===void 0&&N===void 0?void 0:{...F,...N},he=R===void 0&&j===void 0?void 0:{...R,...j},Me=K===void 0&&le===void 0?void 0:{...K,...le},We=Ee===void 0&&qe===void 0?void 0:{...Ee,...qe,styles:{...Ee==null?void 0:Ee.styles,...qe==null?void 0:qe.styles}};return{...$t.features,...e.features,...Ie!==void 0?{scrollToBottom:Ie}:{},...he!==void 0?{scrollBehavior:he}:{},...we!==void 0?{artifacts:we}:{},...Me!==void 0?{streamAnimation:Me}:{},...We!==void 0?{askUserQuestion:We}:{}}})(),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:{...(D=$t.layout)==null?void 0:D.slots,...(E=e.layout)==null?void 0:E.slots}},markdown:{...$t.markdown,...e.markdown,options:{...(P=$t.markdown)==null?void 0:P.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...$t.messageActions,...e.messageActions}}:$t}var yu={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"}},xu={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"}},vu={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:Ki,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 ds(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."))?ds(e,r):r}function Gi(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=ds(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 wu(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 Cu(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]=Cu(o,s):n[r]=s}return n}function db(e,t){return t?Cu(e,t):e}function Xs(e,t={}){var s,o,a,i,d,l,p,u,f,m,v,x,w;let n={palette:yu,semantic:xu,components:vu},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:db(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let S=wu(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(D=>D.message).join(", ")}`)}if(t.plugins)for(let S of t.plugins)r=S.transform(r);return r}function Xi(e){var x,w,S,D,E,P,I,A,M,F,N,R,j,K,le,Ee,qe,we,Ie,he,Me,We,ce,X,ne,ie,me,z,oe,Re,Y,Z,se,Ce,Ye,xe,ge,Ke,Be,q,pe,nt,Mt,ee,ze,Hn,Ht,an,er,Sr,W,de,De,Je,Fe,_e,ot,Pt,Vt,Qt,V,xt,at,ve,ae,tt,Yt,Kt,Mn,yn,gt,kt,Ze,qt,ln,vn,wn,bn,Tr,At,$n,_n,Dr,gr,vt,Co,Er,Ao,Bn,qo,Gr,Nr,St,jn,Un,kn,Lt,tr,nr,qn,Xr,Or,Qr,zn,Bt,Ln,rr,Yr,Fr,Zr,Mr,Vn,fr,ht,Zt,en,Kn,eo;let t=Gi(e),n={};for(let[be,or]of Object.entries(t)){let sr=be.replace(/\./g,"-");n[`--persona-${sr}`]=or.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"]=(D=n["--persona-semantic-colors-surface"])!=null?D:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(E=n["--persona-semantic-colors-background"])!=null?E: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"]=(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"]=(M=n["--persona-semantic-colors-text-inverse"])!=null?M: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"]=(N=n["--persona-semantic-colors-divider"])!=null?N: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"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(K=n["--persona-components-voice-processing-icon"])!=null?K:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(le=n["--persona-components-voice-speaking-icon"])!=null?le:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(qe=n["--persona-components-approval-requested-border"])!=null?qe:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(we=n["--persona-components-approval-requested-text"])!=null?we:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Ie=n["--persona-components-approval-requested-shadow"])!=null?Ie:"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"]=(Me=n["--persona-components-approval-deny-background"])!=null?Me:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(We=n["--persona-components-attachment-image-background"])!=null?We:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ce=n["--persona-components-attachment-image-border"])!=null?ce:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(X=n["--persona-semantic-typography-fontFamily"])!=null?X:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ne=n["--persona-semantic-typography-fontSize"])!=null?ne:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ie=n["--persona-semantic-typography-fontWeight"])!=null?ie:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(me=n["--persona-semantic-typography-lineHeight"])!=null?me: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"]=(z=n["--persona-palette-radius-sm"])!=null?z:"0.125rem",n["--persona-radius-md"]=(oe=n["--persona-palette-radius-md"])!=null?oe:"0.375rem",n["--persona-radius-lg"]=(Re=n["--persona-palette-radius-lg"])!=null?Re:"0.5rem",n["--persona-radius-xl"]=(Y=n["--persona-palette-radius-xl"])!=null?Y:"0.75rem",n["--persona-radius-full"]=(Z=n["--persona-palette-radius-full"])!=null?Z:"9999px",n["--persona-launcher-radius"]=(Ce=(se=n["--persona-components-launcher-borderRadius"])!=null?se:n["--persona-palette-radius-full"])!=null?Ce:"9999px",n["--persona-launcher-bg"]=(Ye=n["--persona-components-launcher-background"])!=null?Ye:n["--persona-primary"],n["--persona-launcher-fg"]=(xe=n["--persona-components-launcher-foreground"])!=null?xe:n["--persona-text-inverse"],n["--persona-launcher-border"]=(ge=n["--persona-components-launcher-border"])!=null?ge:n["--persona-border"],n["--persona-button-primary-bg"]=(Ke=n["--persona-components-button-primary-background"])!=null?Ke:n["--persona-primary"],n["--persona-button-primary-fg"]=(Be=n["--persona-components-button-primary-foreground"])!=null?Be:n["--persona-text-inverse"],n["--persona-button-radius"]=(pe=(q=n["--persona-components-button-primary-borderRadius"])!=null?q:n["--persona-palette-radius-full"])!=null?pe:"9999px",n["--persona-panel-radius"]=(Mt=(nt=n["--persona-components-panel-borderRadius"])!=null?nt:n["--persona-radius-xl"])!=null?Mt:"0.75rem",n["--persona-panel-border"]=(ee=n["--persona-components-panel-border"])!=null?ee:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Hn=(ze=n["--persona-components-panel-shadow"])!=null?ze:n["--persona-palette-shadows-xl"])!=null?Hn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Ht=n["--persona-components-launcher-shadow"])!=null?Ht:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(er=(an=n["--persona-components-input-borderRadius"])!=null?an:n["--persona-radius-lg"])!=null?er:"0.5rem",n["--persona-message-user-radius"]=(W=(Sr=n["--persona-components-message-user-borderRadius"])!=null?Sr:n["--persona-radius-lg"])!=null?W:"0.5rem",n["--persona-message-assistant-radius"]=(De=(de=n["--persona-components-message-assistant-borderRadius"])!=null?de:n["--persona-radius-lg"])!=null?De:"0.5rem",n["--persona-header-bg"]=(Je=n["--persona-components-header-background"])!=null?Je:n["--persona-surface"],n["--persona-header-border"]=(Fe=n["--persona-components-header-border"])!=null?Fe:n["--persona-divider"],n["--persona-header-icon-bg"]=(_e=n["--persona-components-header-iconBackground"])!=null?_e:n["--persona-primary"],n["--persona-header-icon-fg"]=(ot=n["--persona-components-header-iconForeground"])!=null?ot: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"]=(Vt=n["--persona-components-header-subtitleForeground"])!=null?Vt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Qt=n["--persona-components-header-actionIconForeground"])!=null?Qt:n["--persona-muted"];let r=(V=e.components)==null?void 0:V.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(xt=e.components)==null?void 0:xt.introCard;n["--persona-intro-card-bg"]=(at=n["--persona-components-introCard-background"])!=null?at:n["--persona-surface"],n["--persona-intro-card-radius"]=(ve=n["--persona-components-introCard-borderRadius"])!=null?ve:"1rem",n["--persona-intro-card-padding"]=(ae=n["--persona-components-introCard-padding"])!=null?ae:"1.5rem",n["--persona-intro-card-shadow"]=(Yt=(tt=s==null?void 0:s.shadow)!=null?tt:n["--persona-components-introCard-shadow"])!=null?Yt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Kt=n["--persona-components-input-background"])!=null?Kt:n["--persona-surface"],n["--persona-input-placeholder"]=(Mn=n["--persona-components-input-placeholder"])!=null?Mn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(yn=n["--persona-components-message-user-background"])!=null?yn:n["--persona-accent"],n["--persona-message-user-text"]=(gt=n["--persona-components-message-user-text"])!=null?gt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(kt=n["--persona-components-message-user-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Ze=n["--persona-components-message-assistant-background"])!=null?Ze:n["--persona-surface"],n["--persona-message-assistant-text"]=(qt=n["--persona-components-message-assistant-text"])!=null?qt:n["--persona-text"],n["--persona-message-assistant-border"]=(ln=n["--persona-components-message-assistant-border"])!=null?ln:n["--persona-border"],n["--persona-message-assistant-shadow"]=(vn=n["--persona-components-message-assistant-shadow"])!=null?vn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(bn=(wn=n["--persona-components-scrollToBottom-background"])!=null?wn:n["--persona-button-primary-bg"])!=null?bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(At=(Tr=n["--persona-components-scrollToBottom-foreground"])!=null?Tr:n["--persona-button-primary-fg"])!=null?At:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=($n=n["--persona-components-scrollToBottom-border"])!=null?$n:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(_n=n["--persona-components-scrollToBottom-size"])!=null?_n:"40px",n["--persona-scroll-to-bottom-radius"]=(vt=(gr=(Dr=n["--persona-components-scrollToBottom-borderRadius"])!=null?Dr:n["--persona-button-radius"])!=null?gr:n["--persona-radius-full"])!=null?vt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Er=(Co=n["--persona-components-scrollToBottom-shadow"])!=null?Co:n["--persona-palette-shadows-sm"])!=null?Er:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Ao=n["--persona-components-scrollToBottom-padding"])!=null?Ao:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Bn=n["--persona-components-scrollToBottom-gap"])!=null?Bn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Gr=(qo=n["--persona-components-scrollToBottom-fontSize"])!=null?qo:n["--persona-palette-typography-fontSize-sm"])!=null?Gr:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Nr=n["--persona-components-scrollToBottom-iconSize"])!=null?Nr:"14px",n["--persona-tool-bubble-shadow"]=(St=n["--persona-components-toolBubble-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(jn=n["--persona-components-reasoningBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Un=n["--persona-components-composer-shadow"])!=null?Un:"none",n["--persona-md-inline-code-bg"]=(kn=n["--persona-components-markdown-inlineCode-background"])!=null?kn:n["--persona-container"],n["--persona-md-inline-code-color"]=(Lt=n["--persona-components-markdown-inlineCode-foreground"])!=null?Lt:n["--persona-text"],n["--persona-md-link-color"]=(nr=(tr=n["--persona-components-markdown-link-foreground"])!=null?tr:n["--persona-accent"])!=null?nr:"#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"]=(qn=n["--persona-components-markdown-codeBlock-background"])!=null?qn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Xr=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Xr:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Or=n["--persona-components-markdown-codeBlock-textColor"])!=null?Or:"inherit",n["--persona-md-table-header-bg"]=(Qr=n["--persona-components-markdown-table-headerBackground"])!=null?Qr:n["--persona-container"],n["--persona-md-table-border-color"]=(zn=n["--persona-components-markdown-table-borderColor"])!=null?zn:n["--persona-border"],n["--persona-md-hr-color"]=(Bt=n["--persona-components-markdown-hr-color"])!=null?Bt:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Ln=n["--persona-components-markdown-blockquote-borderColor"])!=null?Ln:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(rr=n["--persona-components-markdown-blockquote-background"])!=null?rr:"transparent",n["--persona-md-blockquote-text-color"]=(Yr=n["--persona-components-markdown-blockquote-textColor"])!=null?Yr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(Fr=n["--persona-components-collapsibleWidget-container"])!=null?Fr:n["--persona-surface"],n["--cw-surface"]=(Zr=n["--persona-components-collapsibleWidget-surface"])!=null?Zr:n["--persona-surface"],n["--cw-border"]=(Mr=n["--persona-components-collapsibleWidget-border"])!=null?Mr:n["--persona-border"],n["--persona-message-border"]=(Vn=n["--persona-components-message-border"])!=null?Vn: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"]=(fr=n["--persona-dropdown-bg"])!=null?fr:be.copyMenuBackground),be.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=be.copyMenuBorder,n["--persona-dropdown-border"]=(ht=n["--persona-dropdown-border"])!=null?ht:be.copyMenuBorder),be.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=be.copyMenuShadow,n["--persona-dropdown-shadow"]=(Zt=n["--persona-dropdown-shadow"])!=null?Zt:be.copyMenuShadow),be.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=be.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(en=n["--persona-dropdown-radius"])!=null?en:be.copyMenuBorderRadius),be.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=be.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Kn=n["--persona-dropdown-item-hover-bg"])!=null?Kn: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 or=(eo=ds(e,be.toolbarBackground))!=null?eo:be.toolbarBackground;n["--persona-artifact-toolbar-bg"]=or}}return n}var pb={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 ub={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"}}},Au=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Va=()=>{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"},mb=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Va()},Su=e=>mb(e),gb=e=>Xs(e),fb=e=>{var n;let t=Xs(void 0,{validate:!1});return Xs({...e,palette:{...t.palette,colors:{...ub.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Qs=e=>{let t=Su(e),n=Au(e==null?void 0:e.theme),r=Au(e==null?void 0:e.darkTheme);return t==="dark"?fb(Gs(n!=null?n:{},r!=null?r:{})):gb(n)},hb=e=>Xi(e),Oo=(e,t)=>{let n=Qs(t),r=hb(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},Qi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Va())});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(Va());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 bb}from"idiomorph";var Ka=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;bb.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 Ja={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:{...Ja}}}function Eu(e,t){var n,r,s,o,a,i,d,l,p,u,f,m,v,x,w,S,D,E,P,I,A,M,F,N,R,j,K,le,Ee,qe,we,Ie,he,Me,We,ce,X,ne;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:"",(E=(D=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:D.length)!=null?E:0,(M=(A=(I=(P=e.toolCall)==null?void 0:P.chunks)==null?void 0:I[e.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?M:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:(N=e.toolCall)!=null&&N.args?JSON.stringify(e.toolCall.args).length:0,(K=(j=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:j.length)!=null?K:0,(we=(qe=(Ee=(le=e.reasoning)==null?void 0:le.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:qe.length)!=null?we:0,(We=(Me=(he=(Ie=e.reasoning)==null?void 0:Ie.chunks)==null?void 0:he[e.reasoning.chunks.length-1])==null?void 0:Me.slice(-32))!=null?We:"",(X=(ce=e.contentParts)==null?void 0:ce.length)!=null?X:0,(ne=e.stopReason)!=null?ne:"",t].join("\0")}function Mu(){return new Map}function ku(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Lu(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Pu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ga(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Kr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Fo(e,t){return Kr(e)-e.scrollTop<=t}function Xa(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 Qa(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"}function Iu(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Wu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Ru(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},En=1e5,uo=En+1;var Ys={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},yb=["pre","code","a","script","style"],Ya=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Ys.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ys.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ys.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ys.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ys.buffer}},Bu=[{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 Bu)Zs.set(e.name,e);var xb=e=>{Zs.set(e.name,e)},vb=e=>{Bu.some(t=>t.name===e)||Zs.delete(e)},wb=()=>Array.from(Zs.keys()),ea=(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},Cb=(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},Ab=(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},Yi=/\s/,Sb=(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},Tb=(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(Yi.test(o[i])){let l=i;for(;l<o.length&&Yi.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&&!Yi.test(o[p]);)l.appendChild(Cb(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},Eb=(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(Ab(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},ta=(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:yb).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Sb(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Tb:Eb;for(let m of i)p(m,n,l);return s.innerHTML},ei=(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},na=(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},Hu=new WeakMap,Mb=(e,t)=>{var o;if(!e.styles)return;let n=Hu.get(t);if(n||(n=new Set,Hu.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)},Zi=new WeakMap,kb=(e,t)=>{if(!e.onAttach)return;let n=Zi.get(t);if(n||(n=new Map,Zi.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Du=e=>{let t=Zi.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},el=(e,t)=>{Mb(e,t),kb(e,t)};function tl(e,t=En){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 ra=0,mo=null;function nl(e=document){var n;if(ra++,ra===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;mo={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,ra=Math.max(0,ra-1),ra===0&&mo)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=mo.originalOverflow,s.style.position=mo.originalPosition,s.style.top=mo.originalTop,s.style.width=mo.originalWidth,o.scrollTo(0,mo.scrollY),mo=null}}}var ti={side:"right",width:"420px",animate:!0,reveal:"resize"},hn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},go=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Cr=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:ti.side,width:(s=t==null?void 0:t.width)!=null?s:ti.width,animate:(o=t==null?void 0:t.animate)!=null?o:ti.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:ti.reveal}};var Ar={"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 oa=(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
|
-
`):""},
|
|
25
|
-
`);let s=
|
|
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 E,P,I,A,M,F,N,R,j,K,le,Ee,qe;let a=(E=o.launcher)!=null?E:{},i=hn(o),d=n.querySelector("[data-role='launcher-title']");if(d){let we=(P=a.title)!=null?P:"Chat Assistant";d.textContent=we,d.setAttribute("title",we)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let we=(I=a.subtitle)!=null?I:"Get answers fast";l.textContent=we,l.setAttribute("title",we)}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 we=(A=a.agentIconSize)!=null?A:"40px";if(u.style.height=we,u.style.width=we,u.innerHTML="",a.agentIconName){let Ie=parseFloat(we)||24,he=Se(a.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);he?(u.appendChild(he),u.style.display=""):(u.textContent=(M=a.agentIconText)!=null?M:"\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 we=(N=a.agentIconSize)!=null?N:"40px";f.style.height=we,f.style.width=we,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 we=(R=a.callToActionIconSize)!=null?R:"32px";m.style.height=we,m.style.width=we,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 Ie=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Ie=(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(we)||24,Me=Math.max(he-Ie,8),We=Se(a.callToActionIconName,Me,"currentColor",2);We?m.appendChild(We):m.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else m.textContent=(K=a.callToActionIconText)!=null?K:"\u2197"}let v=a.position&&Ar[a.position]?Ar[a.position]:Ar["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((le=a.zIndex)!=null?le:En));let S="1px solid var(--persona-border, #e5e7eb)",D="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=(Ee=a.border)!=null?Ee:S,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:D,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=(qe=a.collapsedMaxWidth)!=null?qe:"",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 Lb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ni=(e,t={})=>{var x,w,S,D,E,P;let{showClose:n=!0,wrapperClassName:r=Lb,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=(D=a.closeButtonShowTooltip)!=null?D:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(E=a.closeButtonIconName)!=null?E:"x",m=(P=a.closeButtonIconText)!=null?P:"\xD7";l.style.color=a.closeButtonColor||Rn.actionIconColor;let v=Se(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,N=F.body;if(!N)return;I=Hr(F,"div","persona-clear-chat-tooltip"),I.textContent=p;let R=Hr(F,"div");R.className="persona-clear-chat-tooltip-arrow",I.appendChild(R);let j=l.getBoundingClientRect();I.style.position="fixed",I.style.zIndex=String(uo),I.style.left=`${j.left+j.width/2}px`,I.style.top=`${j.top-8}px`,I.style.transform="translate(-50%, -100%)",N.appendChild(I)},M=()=>{I&&I.parentNode&&(I.parentNode.removeChild(I),I=null)};d.addEventListener("mouseenter",A),d.addEventListener("mouseleave",M),l.addEventListener("focus",A),l.addEventListener("blur",M),d._cleanupTooltip=()=>{M(),d.removeEventListener("mouseenter",A),d.removeEventListener("mouseleave",M),l.removeEventListener("focus",A),l.removeEventListener("blur",M)}}return{button:l,wrapper:d}},Pb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ri=(e,t={})=>{var I,A,M,F,N,R,j,K,le,Ee,qe,we,Ie;let{wrapperClassName:n=Pb,buttonSize:r,iconSize:s="20px"}=t,a=(A=((I=e==null?void 0:e.launcher)!=null?I:{}).clearChat)!=null?A:{},i=(M=r!=null?r:a.size)!=null?M:"32px",d=(F=a.iconName)!=null?F:"refresh-cw",l=(N=a.iconColor)!=null?N:"",p=(R=a.backgroundColor)!=null?R:"",u=(j=a.borderWidth)!=null?j:"",f=(K=a.borderColor)!=null?K:"",m=(le=a.borderRadius)!=null?le:"",v=(Ee=a.paddingX)!=null?Ee:"",x=(qe=a.paddingY)!=null?qe:"",w=(we=a.tooltipText)!=null?we:"Clear chat",S=(Ie=a.showTooltip)!=null?Ie:!0,D=h("div",n),E=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");E.style.height=i,E.style.width=i,E.type="button",E.setAttribute("aria-label",w),E.style.color=l||Rn.actionIconColor;let P=Se(d,s,"currentColor",1);if(P&&(P.style.display="block",E.appendChild(P)),p&&(E.style.backgroundColor=p,E.classList.remove("hover:persona-bg-gray-100")),u||f){let he=u||"0px",Me=f||"transparent";E.style.border=`${he} solid ${Me}`,E.classList.remove("persona-border-none")}if(m&&(E.style.borderRadius=m,E.classList.remove("persona-rounded-full")),v&&(E.style.paddingLeft=v,E.style.paddingRight=v),x&&(E.style.paddingTop=x,E.style.paddingBottom=x),D.appendChild(E),S&&w){let he=null,Me=()=>{if(he)return;let ce=E.ownerDocument,X=ce.body;if(!X)return;he=Hr(ce,"div","persona-clear-chat-tooltip"),he.textContent=w;let ne=Hr(ce,"div");ne.className="persona-clear-chat-tooltip-arrow",he.appendChild(ne);let ie=E.getBoundingClientRect();he.style.position="fixed",he.style.zIndex=String(uo),he.style.left=`${ie.left+ie.width/2}px`,he.style.top=`${ie.top-8}px`,he.style.transform="translate(-50%, -100%)",X.appendChild(he)},We=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};D.addEventListener("mouseenter",Me),D.addEventListener("mouseleave",We),E.addEventListener("focus",Me),E.addEventListener("blur",We),D._cleanupTooltip=()=>{We(),D.removeEventListener("mouseenter",Me),D.removeEventListener("mouseleave",We),E.removeEventListener("focus",Me),E.removeEventListener("blur",We)}}return{button:E,wrapper:D}};var Rn={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))"},fo=e=>{var I,A,M,F,N,R,j,K,le,Ee,qe,we,Ie,he,Me,We;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=(M=s.closeButtonPlacement)!=null?M:"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 ce=parseFloat(o)||24,X=Se(d,ce*.6,"currentColor",1);X?l.replaceChildren(X):l.textContent=(R=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?R:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let ce=h("img");ce.src=t.launcher.iconUrl,ce.alt="",ce.className="persona-rounded-xl persona-object-cover",ce.style.height=o,ce.style.width=o,l.replaceChildren(ce)}else l.textContent=(le=(K=t==null?void 0:t.launcher)==null?void 0:K.agentIconText)!=null?le:"\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=Rn.titleColor,u.textContent=(qe=(Ee=t==null?void 0:t.launcher)==null?void 0:Ee.title)!=null?qe:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Rn.subtitleColor,f.textContent=(Ie=(we=t==null?void 0:t.launcher)==null?void 0:we.subtitle)!=null?Ie:"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=(Me=m.enabled)!=null?Me:!0,x=(We=m.placement)!=null?We:"inline",w=null,S=null;if(v){let X=ri(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=X.button,S=X.wrapper,x==="top-right"&&(S.style.right="48px"),x==="inline"&&r.appendChild(S)}let D=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:E,wrapper:P}=ni(t,{showClose:n,wrapperClassName:D});return a!=="top-right"&&r.appendChild(P),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:E,closeButtonWrapper:P,clearChatButton:w,clearChatButtonWrapper:S}},ps=(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 $o(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(uo)):(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=Se(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 Gt(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=Se(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 oi(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=Se(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 si(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=Gt({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 rl(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=Se(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=$o({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 Nu=e=>{var r;let t=fo({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 Ib(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=Se(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=$o({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Ou=e=>{var D,E,P,I,A,M,F,N,R;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(D=t==null?void 0:t.launcher)!=null?D:{},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=rl({label:(E=a.title)!=null?E:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Rn.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=Rn.titleColor,p.textContent=(I=a.title)!=null?I:"Chat Assistant",l.appendChild(p),Ib(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 K=s.onTitleClick;l.addEventListener("click",le=>{le.target.closest("button")||K()}),l.addEventListener("keydown",le=>{(le.key==="Enter"||le.key===" ")&&(le.preventDefault(),K())})}let j=s==null?void 0:s.titleRowHover;j&&(l.style.borderRadius=(M=j.borderRadius)!=null?M:"10px",l.style.padding=(F=j.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 K,le;l.style.backgroundColor=(K=j.background)!=null?K:"",l.style.borderColor=(le=j.border)!=null?le:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(N=a.closeButtonSize)!=null?N:"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||Rn.actionIconColor;let v=(R=a.closeButtonIconName)!=null?R:"x",x=Se(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}},ol={default:Nu,minimal:Ou},Fu=e=>{var t;return(t=ol[e])!=null?t:ol.default},sa=(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=Fu(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 ai=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}},ii=e=>{var I,A,M,F,N,R,j,K,le,Ee,qe,we;let t=(I=e==null?void 0:e.sendButton)!=null?I:{},n=(A=t.useIcon)!=null?A:!1,r=(M=t.iconText)!=null?M:"\u2191",s=t.iconName,o=(F=t.stopIconName)!=null?F:"square",a=(N=t.tooltipText)!=null?N:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(K=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?K:"Send",l=(Ee=(le=e==null?void 0:e.copy)==null?void 0:le.stopButtonLabel)!=null?Ee:"Stop",p=(qe=t.showTooltip)!=null?qe:!1,u=(we=t.size)!=null?we:"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 Ie=parseFloat(u)||24,he=(m==null?void 0:m.trim())||"currentColor";s?(w=Se(s,Ie,he,2),w?x.appendChild(w):x.textContent=r):x.textContent=r,S=Se(o,Ie,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 D=null;p&&a&&(D=h("div","persona-send-button-tooltip"),D.textContent=a,v.appendChild(D)),x.setAttribute("aria-label",a),v.appendChild(x);let E="send";return{button:x,wrapper:v,setMode:Ie=>{if(Ie===E)return;E=Ie;let he=Ie==="stop"?i:a;if(x.setAttribute("aria-label",he),D&&(D.textContent=he),n){if(w&&S){let Me=Ie==="stop"?S:w;x.replaceChildren(Me)}}else x.textContent=Ie==="stop"?l:d}}},li=e=>{var D,E,P,I,A,M,F,N,R,j,K,le;let t=(D=e==null?void 0:e.voiceRecognition)!=null?D:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((E=t.provider)==null?void 0:E.type)==="runtype";if(!(r||s))return null;let a=(I=(P=e==null?void 0:e.sendButton)==null?void 0:P.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=(M=t.iconSize)!=null?M:a,u=parseFloat(p)||24,f=(N=t.backgroundColor)!=null?N:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,m=(j=t.iconColor)!=null?j:(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",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=Se(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=(K=t.tooltipText)!=null?K:"Start voice recognition";if(((le=t.showTooltip)!=null?le:!1)&&w){let Ee=h("div","persona-send-button-tooltip");Ee.textContent=w,i.appendChild(Ee)}return{button:d,wrapper:i}},ci=e=>{var v,x,w,S,D,E,P,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:Vr).join(","),s.multiple=((D=t.maxFiles)!=null?D: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",(E=t.buttonTooltipText)!=null?E:"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 u=Se(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}},di=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},pi=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var aa=e=>{var v,x,w,S,D,E;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=pi(),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}=ai(t);a();let i=ii(t),d=li(t),l=ci(t),p=di(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",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:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(D=l==null?void 0:l.input)!=null?D:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var $u=()=>{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=Se("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=Se("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},_u=e=>{var v,x,w,S,D,E;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=pi();r.style.display="none";let s=di(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=ai(t);o.style.maxHeight="100px",a();let i=ii(t),d=li(t),l=ci(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",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(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:(D=l==null?void 0:l.input)!=null?D:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var ju=e=>{var p,u,f,m,v,x,w,S,D,E,P,I,A,M,F,N,R;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=hn(e);if(go(e)){let j=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},K=h("div","persona-widget-wrapper persona-fixed persona-transition");K.setAttribute("data-persona-composer-bar",""),K.dataset.state="collapsed",K.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",K.style.zIndex=String((w=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?w:En);let le=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");le.style.width="100%",K.appendChild(le);let Ee=h("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(S=j.expandedSize)!=null?S:"anchored",Ee.style.zIndex=String((E=(D=e==null?void 0:e.launcher)==null?void 0:D.zIndex)!=null?E:En),{wrapper:K,panel:le,pillRoot:Ee}}if(n){let j=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),K=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(K),{wrapper:j,panel:K}}if(!t){let j=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),K=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),le=(I=(P=e==null?void 0:e.launcher)==null?void 0:P.width)!=null?I:"100%";return j.style.width=le,K.style.width="100%",j.appendChild(K),{wrapper:j,panel:K}}let s=(A=e==null?void 0:e.launcher)!=null?A:{},o=s.position&&Ar[s.position]?Ar[s.position]:Ar["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((F=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?F:En);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(N=e==null?void 0:e.launcher)==null?void 0:N.width)!=null?R: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}},Wb=(e,t)=>{var P,I,A,M,F,N,R,j,K;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}=ni(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=(P=e==null?void 0:e.launcher)==null?void 0:P.clearChat)==null?void 0:I.enabled)!=null?A:!0,a=null,i=null;if(o){let le=ri(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=le.button,i=le.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"),l.style.setProperty("scrollbar-gutter","stable");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=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?F:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(R=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",p.append(u,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((K=e==null?void 0:e.copy)==null?void 0:K.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=_u({config:e}),{root:D,textNode:E}=$u();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:D,peekTextNode:E}},Uu=(e,t=!0)=>{var w,S,D,E,P,I,A,M,F;if(go(e))return Wb(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?sa(e,r,{showClose:t}):fo({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"),a.style.setProperty("scrollbar-gutter","stable");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=hn(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=(E=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeTitle)!=null?E:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(I=(P=e==null?void 0:e.copy)==null?void 0:P.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",""),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let m=aa({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;s?ps(n,o,e):(o.header.style.display="none",ps(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 Rb=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}},Hb=(e,t)=>{if(!e)return null;let n=Rb(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Bb=(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},Db=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},sl=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(":"))},al=320,zu=320,Nb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ob=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Fb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),$b=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),_b=(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=`${al}px`,l.style.maxHeight=`${zu}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}),Db(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}},jb=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(!sl(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=`${al}px`,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","video");let n=0;return e.forEach(r=>{if(!sl(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=`${al}px`,s.style.maxHeight=`${zu}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}},qb=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(!sl(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}},us=()=>{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},Vu=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:us};if(t){let s=t(r);if(s!==null)return s}return us()},zb=(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},qu=(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},Vb=(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},Ku=(e,t,n)=>{var m,v,x,w,S,D;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 E=h("div");return E.style.display="none",E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id),E}let a=(w=t.visibility)!=null?w:"hover",i=(S=t.align)!=null?S:"right",d=(D=t.layout)!=null?D:"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=(E,P,I)=>{let A=Gt({icon:E,label:P,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},ia=(e,t,n,r,s,o)=>{var ce,X,ne,ie,me,z,oe,Re,Y,Z,se,Ce,Ye,xe,ge,Ke,Be;let a=n!=null?n:{},i=(ce=a.layout)!=null?ce:"bubble",d=a.avatar,l=a.timestamp,p=(X=d==null?void 0:d.show)!=null?X:!1,u=(ne=l==null?void 0:l.show)!=null?ne:!1,f=(ie=d==null?void 0:d.position)!=null?ie:"left",m=(me=l==null?void 0:l.position)!=null?me:"below",v=Vb(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=Nb(e),S=(oe=(z=e.content)==null?void 0:z.trim())!=null?oe:"",E=w.length>0&&S===Fa,P=Ya((Y=(Re=o==null?void 0:o.widgetConfig)==null?void 0:Re.features)==null?void 0:Y.streamAnimation),I=(Ce=(se=(Z=o==null?void 0:o.widgetConfig)==null?void 0:Z.features)==null?void 0:se.streamAnimation)==null?void 0:Ce.plugins,A=e.role==="assistant"&&P.type!=="none"?ea(P.type,I):null,M=e.role==="assistant"&&((Ye=A==null?void 0:A.isAnimating)==null?void 0:Ye.call(A,e))===!0,F=e.role==="assistant"&&A!==null&&(!!e.streaming||M);F&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),F&&A&&(A.containerClass&&N.classList.add(A.containerClass),N.style.setProperty("--persona-stream-step",`${P.speed}ms`),N.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let R=F?Za((xe=e.content)!=null?xe:"",P.buffer,A,e,!!e.streaming):(ge=e.content)!=null?ge:"",j=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),K=j;F&&(A==null?void 0:A.wrap)==="char"?K=ta(j,"char",e.id,{skipTags:A.skipTags}):F&&(A==null?void 0:A.wrap)==="word"&&(K=ta(j,"word",e.id,{skipTags:A.skipTags}));let le=null;if(E?(le=document.createElement("div"),le.innerHTML=K,le.style.display="none",N.appendChild(le)):N.innerHTML=K,F&&(A!=null&&A.useCaret)&&!E&&S){let q=ei(),pe=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),nt=pe[pe.length-1];if(nt!=null&&nt.parentNode)nt.parentNode.insertBefore(q,nt.nextSibling);else{let Mt=N.lastElementChild;Mt?Mt.appendChild(q):N.appendChild(q)}}if(u&&m==="inline"&&e.createdAt){let q=qu(e,l);q.classList.add("persona-ml-2","persona-inline"),N.appendChild(q)}if(w.length>0){let q=_b(w,!E&&!!S,()=>{E&&le&&(le.style.display="")});q?x.appendChild(q):E&&le&&(le.style.display="")}let Ee=Ob(e);if(Ee.length>0){let q=jb(Ee);q&&x.appendChild(q)}let qe=Fb(e);if(qe.length>0){let q=Ub(qe);q&&x.appendChild(q)}let we=$b(e);if(we.length>0){let q=qb(we);q&&x.appendChild(q)}if(x.appendChild(N),u&&m==="below"&&e.createdAt){let q=qu(e,l);q.classList.add("persona-mt-1"),x.appendChild(q)}let Ie=e.role==="assistant"?Hb(e.stopReason,(Be=(Ke=o==null?void 0:o.widgetConfig)==null?void 0:Ke.copy)==null?void 0:Be.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let q=!!(R&&R.trim()),pe=P.placeholder==="skeleton",nt=pe&&P.buffer==="line"&&q;if(q)nt&&x.appendChild(na());else if(pe)x.appendChild(na());else{let Mt=Vu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Mt&&x.appendChild(Mt)}}if(Ie&&e.stopReason&&!e.streaming&&(S||(N.style.display="none"),x.appendChild(Bb(e.stopReason,Ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let q=Ku(e,r,s);x.appendChild(q)}if(!p||e.role==="system")return x;let Me=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),We=zb(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Me.append(x,We):Me.append(We,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Me},Kb=(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}):ia(e,t,n,r,s,o)};var ms=new Set,Jb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Gb=(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
|
+
`):""},Ju=(e,t)=>{let n=ms.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=Se(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")},il=(e,t)=>{var qe,we,Ie,he,Me,We,ce,X,ne,ie,me;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=(we=(qe=t==null?void 0:t.features)==null?void 0:qe.reasoningDisplay)!=null?we:{},o=s.expandable!==!1,a=o&&ms.has(e.id),i=n.status!=="complete",d=Gb(e,(Ie=s.previewMaxLines)!=null?Ie: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((Me=n.startedAt)!=null?Me:Date.now()),x=()=>{let z=h("span","");return z.setAttribute("data-tool-elapsed",v),z.textContent=Ba(n),z},w=(We=m.renderCollapsedSummary)==null?void 0:We.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ba(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=iu(n),p.appendChild(S);let D=(ce=s.loadingAnimation)!=null?ce:"none",E=m.activeTextTemplate,P=m.completeTextTemplate,I=i?E:P,A=w instanceof HTMLElement,M=(z,oe,Re)=>{let Y=Re;for(let Z of oe){let se=h("span","persona-tool-char");se.style.setProperty("--char-index",String(Y)),se.textContent=Z===" "?"\xA0":Z,z.appendChild(se),Y++}return Y},F=(z,oe)=>{u.textContent="";let Re=Da(z,""),Y=0;for(let Z of Re){let se=Z.styles.length>0?(()=>{let Ce=h("span",Z.styles.map(Ye=>`persona-tool-text-${Ye}`).join(" "));return u.appendChild(Ce),Ce})():u;if(Z.isDuration&&i)se.appendChild(x());else{let Ce=Z.isDuration?Ba(n):Z.text;oe?Y=M(se,Ce,Y):se.appendChild(document.createTextNode(Ce))}}};if(!A&&I)if(S.style.display="none",u.style.display="",i&&D!=="none"){let z=(X=m.loadingAnimationDuration)!=null?X:2e3;u.setAttribute("data-preserve-animation","true"),D==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${z}ms`),F(I,!1)):(u.classList.add(`persona-tool-loading-${D}`),u.style.setProperty("--persona-tool-anim-duration",`${z}ms`),D==="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&&D!=="none"){u.style.display="";let z=(ne=m.loadingAnimationDuration)!=null?ne:2e3;if(u.setAttribute("data-preserve-animation","true"),D==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${z}ms`);else{u.classList.add(`persona-tool-loading-${D}`),u.style.setProperty("--persona-tool-anim-duration",`${z}ms`),D==="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 oe=u.textContent||f;u.textContent="",M(u,oe,0)}n.status==="complete"&&(u.style.display="none")}else A||(n.status==="complete"?u.style.display="none":u.style.display="");let N=null;if(o){N=h("div","persona-flex persona-items-center");let oe=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);oe?N.appendChild(oe):N.textContent=a?"Hide":"Show";let Re=h("div","persona-flex persona-items-center persona-ml-auto");Re.append(N),l.append(p,Re)}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 z=(me=(ie=t==null?void 0:t.reasoning)==null?void 0:ie.renderCollapsedPreview)==null?void 0:me.call(ie,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Jb(R,z)||(R.textContent=d),R.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,R),r;let j=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let K=n.chunks.join(""),le=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return le.textContent=K||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(le),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),N){N.innerHTML="";let oe=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);oe?N.appendChild(oe):N.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(l,R,j),r};var gs=new Set,Xb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Qb=(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=ss(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
+
`):""},Yb=(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=Qb(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?lu(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=$i(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=$i(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Gu=(e,t,n)=>{var p;let r=gs.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=Se(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")},ll=(e,t)=>{var K,le,Ee,qe,we,Ie,he,Me,We;let n=e.toolCall,r=(K=t==null?void 0:t.toolCall)!=null?K:{},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=(Ee=(le=t==null?void 0:t.features)==null?void 0:le.toolCallDisplay)!=null?Ee:{},a=o.expandable!==!1,i=a&&gs.has(e.id),{summary:d,previewText:l,isActive:p}=Yb(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((qe=n.startedAt)!=null?qe:Date.now()),x=()=>{let ce=h("span","");return ce.setAttribute("data-tool-elapsed",v),ce.textContent=qs(n),ce},w=(Ie=r.renderCollapsedSummary)==null?void 0:Ie.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(we=o.collapsedMode)!=null?we:"tool-call",isActive:p,config:t!=null?t:{},elapsed:qs(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",D=r.activeTextTemplate,E=r.completeTextTemplate,P=p?D:E,I=w instanceof HTMLElement,A=(ce,X,ne)=>{let ie=ne;for(let me of X){let z=h("span","persona-tool-char");z.style.setProperty("--char-index",String(ie)),z.textContent=me===" "?"\xA0":me,ce.appendChild(z),ie++}return ie},M=(ce,X)=>{var z;m.textContent="";let ne=((z=n.name)==null?void 0:z.trim())||"tool",ie=Da(ce,ne),me=0;for(let oe of ie){let Re=oe.styles.length>0?(()=>{let Y=h("span",oe.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(Y),Y})():m;if(oe.isDuration&&p)Re.appendChild(x());else{let Y=oe.isDuration?qs(n):oe.text;X?me=A(Re,Y,me):Re.appendChild(document.createTextNode(Y))}}};if(!I)if(p&&S!=="none"){let ce=(Me=r.loadingAnimationDuration)!=null?Me:2e3;if(m.setAttribute("data-preserve-animation","true"),S==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),P&&M(P,!1);else if(m.classList.add(`persona-tool-loading-${S}`),m.style.setProperty("--persona-tool-anim-duration",`${ce}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)),P)M(P,!0);else{let X=m.textContent||d;m.textContent="",A(m,X,0)}}else P&&M(P,!1);let F=null;if(a){F=h("div","persona-flex persona-items-center");let ce=r.toggleTextColor||r.headerTextColor||"currentColor",X=Se(i?"chevron-up":"chevron-down",16,ce,2);X?F.appendChild(X):F.textContent=i?"Hide":"Show";let ne=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ne.append(F),u.append(f,ne)}else u.append(f);let N=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","tool"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let ce=(We=r.renderCollapsedPreview)==null?void 0:We.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Xb(N,ce)||(N.textContent=l),N.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(u,N),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 ce=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ce.style.color=r.contentTextColor:r.headerTextColor&&(ce.style.color=r.headerTextColor),ce.textContent=n.name,R.appendChild(ce)}if(n.args!==void 0){let ce=h("div","persona-space-y-1"),X=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=ss(n.args),ce.append(X,ne),R.appendChild(ce)}if(n.chunks&&n.chunks.length){let ce=h("div","persona-space-y-1"),X=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=n.chunks.join(""),ce.append(X,ne),R.appendChild(ce)}if(n.status==="complete"&&n.result!==void 0){let ce=h("div","persona-space-y-1"),X=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=ss(n.result),ce.append(X,ne),R.appendChild(ce)}if(n.status==="complete"&&typeof n.duration=="number"){let ce=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ce.style.color=r.contentTextColor),ce.textContent=`Duration: ${n.duration}ms`,R.appendChild(ce)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let ce=r.toggleTextColor||r.headerTextColor||"currentColor",X=Se(i?"chevron-up":"chevron-down",16,ce,2);X?F.appendChild(X):F.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),s.append(u,N,R),s};import{parse as Zb,ARR as ey,OBJ as ty,STR as ny}from"partial-json";var Qu="ask_user_question",cl=8,fs="data-persona-ask-sheet-for",ry="Other",oy="Other\u2026",Yu="Type your own answer here",Zu="Send",sy="Next",ay="Back",iy="Submit all",ly="Skip",cy=3,dl="data-ask-current-index",pl="data-ask-question-count",em="data-ask-answers",ul="data-ask-grouped",tm="data-ask-layout",dy=e=>e.layout==="pills"?"pills":"rows",py=e=>e.getAttribute(tm)==="pills"?"pills":"rows",Xu=!1,nm=e=>e.replace(/["\\]/g,"\\$&"),ho=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Qu,ui=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},bo=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=Zb(s,ny|ty|ey);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},la=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>cl&&!Xu&&(Xu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${cl}.`)),t.slice(0,cl)},uy=e=>{var t;return(t=la(e)[0])!=null?t:null},my=(e,t)=>{var n;return(n=la(e)[t])!=null?n:null},rm=(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))},om=(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},gy=(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=om(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},fy=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},hy=(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<cy;m++)o.appendChild(fy(r));return o}if(d.forEach((m,v)=>{o.appendChild(gy(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?ry:oy;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:Yu,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=om(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},sm=(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:Yu,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:Zu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},by=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:Zu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},yy=(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:ay,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:ly,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:iy:(f=n.nextLabel)!=null?f:sy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},_o=e=>{let t=e.getAttribute(em);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},am=(e,t)=>{e.setAttribute(em,JSON.stringify(t))},ur=e=>{var n;let t=Number((n=e.getAttribute(dl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},xy=(e,t)=>{e.setAttribute(dl,String(Math.max(0,Math.floor(t))))},hs=e=>{var n;let t=Number((n=e.getAttribute(pl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=e=>e.getAttribute(ul)==="true",vy=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},wy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},mi=(e,t)=>{let{payload:n}=bo(t),r=la(n),s=_o(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},im=e=>{let t=_o(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=""},lm=e=>{if(!yo(e))return;let t=_o(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}},ml=(e,t,n)=>{let r=ui(n),s=py(e),{payload:o,complete:a}=bo(t),i=yo(e),d=ur(e),l=hs(e),p=i?my(o,d):uy(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 D=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=D,v.classList.toggle("persona-ask-question-skeleton",!D&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let D=hy(p,r,a,s);x.replaceWith(D)}if(s!=="rows"){let D=e.querySelector('[data-ask-free-text-row="true"]');D&&D.replaceWith(sm(r,s))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(by(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 D=yy(d,l,r);S?S.replaceWith(D):e.appendChild(D)}else S&&S.remove();im(e),lm(e)},Cy=(e,t,n)=>{let r=ui(t),s=dy(r),o=e.toolCall.id,a=la(n),i=Math.max(1,a.length),d=i>1,l=vy(e,a),p=d?wy(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(fs,o),u.setAttribute("data-tool-call-id",o),u.setAttribute("data-message-id",e.id),u.setAttribute(pl,String(i)),u.setAttribute(dl,String(p)),u.setAttribute(ul,d?"true":"false"),u.setAttribute(tm,s),am(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`),rm(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(sm(r,s)),ml(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Ay=(e,t,n)=>{let{payload:r}=bo(t),s=Math.max(1,la(r).length);s>hs(e)&&(e.setAttribute(pl,String(s)),s>1&&!yo(e)&&e.setAttribute(ul,"true")),ml(e,t,n)},Sy=(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=ui(t);rm(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=bo(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},ca=(e,t,n)=>{if(!n||!ho(e)||ui(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${fs}]`).forEach(l=>{l.getAttribute(fs)!==s&&l.remove()});let a=n.querySelector(`[${fs}="${nm(s)}"]`);if(a){Ay(a,e,t);return}let{payload:i}=bo(e),d=Cy(e,t,i);n.appendChild(d)},jo=(e,t)=>{if(!e)return;let n=t?`[${fs}="${nm(t)}"]`:`[${fs}]`;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)})},gl=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),xo=(e,t)=>{let n=_o(e),r=ur(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,am(e,n),im(e),lm(e)},gi=(e,t,n,r)=>{let s=hs(e),o=Math.max(0,Math.min(s-1,r));xy(e,o),ml(e,t,n)};var fi=new Map,Ty=e=>{let n=(e.startsWith(po)?e.slice(po.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)},cm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,dm=(e,t)=>{var r,s,o;let n=(s=(r=cm(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=fi.get(e))!=null?o:n==="expanded"},pm=(e,t,n)=>{var a,i;let r=cm(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=Se(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},um=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=dm(e,n);pm(r,o,n),s.style.display=o?"":"none"};var hi=(e,t)=>{var M,F,N,R,j,K,le,Ee,qe,we,Ie,he,Me,We,ce;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=(M=r==null?void 0:r.backgroundColor)!=null?M:"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)":(N=r==null?void 0:r.titleColor)!=null?N:"currentColor",p=Se(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=(R=r==null?void 0:r.title)!=null?R:"Approval Required",f.appendChild(m),!s){let X=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",n.status),n.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):n.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):n.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),f.appendChild(X)}u.appendChild(f);let x=n.toolType==="webmcp"||n.toolName.startsWith(po)?Oi(n.toolName):void 0,w=(j=r==null?void 0:r.formatDescription)==null?void 0:j.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),S=!n.toolName,D=w||(S?n.description:`The assistant wants to use \u201C${x!=null?x:Ty(n.toolName)}\u201D.`),E=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(E.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(E.style.color=r.descriptionColor),E.textContent=D,u.appendChild(E),n.reason){let X=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?X.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor);let ne=h("span","persona-font-medium");ne.textContent=`${(K=r==null?void 0:r.reasonLabel)!=null?K:"Agent's stated reason:"} `,X.appendChild(ne),X.appendChild(document.createTextNode(n.reason)),u.appendChild(X)}let P=(le=r==null?void 0:r.detailsDisplay)!=null?le:"collapsed",I=!!n.description&&!S,A=I||!!n.parameters;if(P!=="hidden"&&A){let X=dm(e.id,t),ne=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");ne.type="button",ne.setAttribute("data-expand-header","true"),ne.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ne.style.color=r.descriptionColor);let ie=h("span");ie.setAttribute("data-approval-details-label","true");let me=h("span","persona-inline-flex persona-items-center");me.setAttribute("data-approval-details-chevron","true"),ne.append(ie,me),pm(ne,X,t),u.appendChild(ne);let z=h("div");if(z.setAttribute("data-approval-details","true"),z.style.display=X?"":"none",I){let oe=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(oe.style.color=r.descriptionColor),oe.textContent=n.description,z.appendChild(oe)}if(n.parameters){let oe=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&&(oe.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(oe.style.color=r.parameterTextColor),oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",oe.textContent=ss(n.parameters),z.appendChild(oe)}u.appendChild(z)}if(s){let X=h("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let ne=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");ne.type="button",ne.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(qe=r==null?void 0:r.approveButtonTextColor)!=null?qe:"#ffffff",ne.setAttribute("data-approval-action","approve");let ie=Se("shield-check",14,(we=r==null?void 0:r.approveButtonTextColor)!=null?we:"#ffffff",2);ie&&(ie.style.marginRight="4px",ne.appendChild(ie));let me=document.createTextNode((Ie=r==null?void 0:r.approveLabel)!=null?Ie:"Approve");ne.appendChild(me);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-cursor-pointer");z.type="button",z.style.backgroundColor=(he=r==null?void 0:r.denyButtonColor)!=null?he:"transparent",z.style.color=(Me=r==null?void 0:r.denyButtonTextColor)!=null?Me:"var(--persona-feedback-error, #dc2626)",z.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,z.setAttribute("data-approval-action","deny");let oe=Se("shield-x",14,(We=r==null?void 0:r.denyButtonTextColor)!=null?We:"var(--persona-feedback-error, #dc2626)",2);oe&&(oe.style.marginRight="4px",z.appendChild(oe));let Re=document.createTextNode((ce=r==null?void 0:r.denyLabel)!=null?ce:"Deny");z.appendChild(Re),X.append(ne,z),u.appendChild(X)}return a.append(i,u),o.appendChild(a),o};var mm=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 da=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 pa=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 Ey=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),My=new Set(["step_start","execution_start"]),ky=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ly=new Set(["step_complete","agent_turn_complete"]),Py=new Set(["flow_complete","agent_complete"]),gm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),hm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Uo=(e,t)=>{let n=e[t];return hm(n)?n:void 0};function fl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function bi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Iy(e,t){return typeof t.type=="string"?t.type:e}function Wy(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 Ry(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 fm(e){var r,s,o,a,i;let t=Uo(e,"result"),n=[Uo(e,"tokens"),Uo(e,"totalTokens"),t?Uo(t,"tokens"):void 0,Uo(e,"usage"),t?Uo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Zn(d.output))!=null?r:Zn(d.outputTokens))!=null?s:Zn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Zn(e.outputTokens))!=null?o:Zn(e.completionTokens))!=null?i:t?(a=Zn(t.outputTokens))!=null?a:Zn(t.completionTokens):void 0}function Hy(e){var n,r,s,o,a;let t=Uo(e,"result");return(a=(s=(r=(n=Zn(e.executionTime))!=null?n:Zn(e.executionTimeMs))!=null?r:Zn(e.execution_time))!=null?s:Zn(e.duration))!=null?a:t?(o=Zn(t.executionTime))!=null?o:Zn(t.executionTimeMs):void 0}function By(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ua=class{constructor(t=By){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:bi(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(!hm(n)){gm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Iy(t,n),s=this.now();if(Ey.has(r)){this.startRun(s);return}if(My.has(r)){this.run||this.startRun(s);return}if(ky.has(r)){if(!Ry(r,n))return;let a=Wy(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+fl(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:bi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ly.has(r)){if(!this.run)return;let a=this.run,i=fm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+fl(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:bi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Py.has(r)){if(!this.run)return;let a=this.run,i=fm(n),d=i!=null?i:a.exactOutputTokens+fl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:bi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(gm.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=Hy(n);return o!=null?o:r-t.startedAt}};function bs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Dy={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Ny={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Oy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Fy=100;function $y(e,t){let n={...Dy,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Ny}function _y(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function jy(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 Uy(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 qy(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 zy(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 Vy(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Ky(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 Jy(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 hl(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");bs(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 K,le;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=Se(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]"),D=(K=r.timestampFormat)!=null?K:"relative";S.textContent=D==="relative"?_y(e.timestamp,n):jy(e.timestamp);let E=null;r.showSequenceNumbers!==!1&&(E=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),E.textContent=String(t+1));let P=$y(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=P.bg,I.style.color=P.text,I.style.borderColor=P.text+"50",I.textContent=e.type;let A=(le=r.descriptionFields)!=null?le:Oy,M=Uy(e.payload,A),F=null;M&&(F=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=M);let N=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"),j=Se("clipboard","12px","currentColor",1.5);return j&&R.appendChild(j),R.addEventListener("click",async Ee=>{Ee.stopPropagation(),await qy(zy(e)),R.innerHTML="";let qe=Se("check","12px","currentColor",1.5);qe&&R.appendChild(qe),setTimeout(()=>{R.innerHTML="";let we=Se("clipboard","12px","currentColor",1.5);we&&R.appendChild(we)},1500)}),v.appendChild(x),v.appendChild(S),E&&v.appendChild(E),v.appendChild(I),F&&v.appendChild(F),v.appendChild(N),v.appendChild(R),m.appendChild(v),d&&m.appendChild(Jy(e,a,i)),m}}function bm(e){var v,x,w,S,D;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=(D=(S=s==null?void 0:s.features)==null?void 0:S.eventStream)!=null?D:{},f=o.find(E=>E.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let E=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(E)return{element:E,update:()=>{},destroy:()=>{}}}return m();function m(){let E=u.classNames,P=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");bs(P,E==null?void 0:E.panel);let I=[],A="",M="",F=null,N=[],R={},j=0,K=Ga(),le=0,Ee=0,qe=!1,we=null,Ie=!1,he=0,Me=new Set,We=new Map,ce="",X="",ne=null,ie,me,z,oe,Re,Y=null,Z=null,se=null;function Ce(){let ve=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ae=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");bs(ae,E==null?void 0:E.headerBar);let tt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(tt.textContent="Events",ie=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"),ie.textContent="0",a){Z=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let vn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");vn.textContent="Throughput",Y=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"),Y.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 wn=Z,bn=se,Tr=()=>{if(!bn.textContent)return;let $n=wn.getBoundingClientRect(),_n=ve.getBoundingClientRect();bn.style.left=`${$n.left-_n.left}px`,bn.style.top=`${$n.bottom-_n.top+4}px`,bn.style.display="block"},At=()=>{bn.style.display="none"};Z.addEventListener("mouseenter",Tr),Z.addEventListener("mouseleave",At),Z.appendChild(vn),Z.appendChild(Y)}let Yt=h("div","persona-flex-1");me=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 Kt=h("option","");Kt.value="",Kt.textContent="All events",me.appendChild(Kt),z=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"),z.type="button",z.title="Copy All";let yn=Se("clipboard-copy","12px","currentColor",1.5);yn&&z.appendChild(yn);let gt=h("span","persona-text-xs");gt.textContent="Copy All",z.appendChild(gt),ae.appendChild(tt),ae.appendChild(ie),Z&&ae.appendChild(Z),ae.appendChild(Yt),ae.appendChild(me),ae.appendChild(z);let kt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");bs(kt,E==null?void 0:E.searchBar);let Ze=Se("search","14px","var(--persona-muted, #9ca3af)",1.5),qt=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");Ze&&qt.appendChild(Ze),oe=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"),bs(oe,E==null?void 0:E.searchInput),oe.type="text",oe.placeholder="Search event payloads...",Re=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"),Re.type="button",Re.style.display="none";let ln=Se("x","12px","currentColor",2);return ln&&Re.appendChild(ln),kt.appendChild(qt),kt.appendChild(oe),kt.appendChild(Re),ve.appendChild(ae),ve.appendChild(kt),se&&ve.appendChild(se),ve}let Ye,xe=o.find(ve=>ve.renderEventStreamToolbar);if(xe!=null&&xe.renderEventStreamToolbar&&s){let ve=xe.renderEventStreamToolbar({config:s,defaultRenderer:()=>Ce(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ae=>{A=ae,an(),W()},onSearchChange:ae=>{M=ae,an(),W()}});Ye=ve!=null?ve:Ce()}else Ye=Ce();let ge=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");ge.style.display="none";function Ke(){if(!a||!Y||!Z)return;let ve=a();Y.textContent=Vy(ve);let ae=Ky(ve);se&&(se.textContent=ae,ae||(se.style.display="none")),ae?Z.setAttribute("aria-label",ae):Z.removeAttribute("aria-label")}let Be=h("div","persona-flex-1 persona-min-h-0 persona-relative"),q=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let pe=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");bs(pe,E==null?void 0:E.scrollIndicator),pe.style.display="none",pe.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let nt=Se(l,"14px","currentColor",2);nt&&pe.appendChild(nt);let Mt=h("span","");Mt.textContent=p,pe.appendChild(Mt);let ee=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ee.style.display="none",Be.appendChild(q),Be.appendChild(ee),Be.appendChild(pe),P.setAttribute("tabindex","0"),P.appendChild(Ye),P.appendChild(ge),P.appendChild(Be);function ze(){let ve=t.getAll(),ae={};for(let gt of ve)ae[gt.type]=(ae[gt.type]||0)+1;let tt=Object.keys(ae).sort(),Yt=tt.length!==N.length||!tt.every((gt,kt)=>gt===N[kt]),Kt=!Yt&&tt.some(gt=>ae[gt]!==R[gt]),Mn=ve.length!==Object.values(R).reduce((gt,kt)=>gt+kt,0);if(!Yt&&!Kt&&!Mn||(N=tt,R=ae,!me))return;let yn=me.value;if(me.options[0].textContent="All events",Yt){for(;me.options.length>1;)me.remove(1);for(let gt of tt){let kt=h("option","");kt.value=gt,kt.textContent=`${gt} (${ae[gt]||0})`,me.appendChild(kt)}yn&&tt.includes(yn)?me.value=yn:yn&&(me.value="",A="")}else for(let gt=1;gt<me.options.length;gt++){let kt=me.options[gt];kt.textContent=`${kt.value} (${ae[kt.value]||0})`}}function Hn(){let ve=t.getAll();if(A&&(ve=ve.filter(ae=>ae.type===A)),M){let ae=M.toLowerCase();ve=ve.filter(tt=>tt.type.toLowerCase().includes(ae)||tt.payload.toLowerCase().includes(ae))}return ve}function Ht(){return A!==""||M!==""}function an(){j=0,le=0,K.resume(),pe.style.display="none"}function er(ve){Me.has(ve)?Me.delete(ve):Me.add(ve),ne=ve;let ae=q.scrollTop,tt=K.isFollowing();Ie=!0,K.pause(),W(),q.scrollTop=ae,tt&&K.resume(),Ie=!1}function Sr(){return Fo(q,50)}function W(){Ee=Date.now(),qe=!1,Ke(),ze();let ve=t.getEvictedCount();ve>0?(ge.textContent=`${ve.toLocaleString()} older events truncated`,ge.style.display=""):ge.style.display="none",I=Hn();let ae=I.length,tt=t.getSize()>0;ie&&(ie.textContent=String(t.getSize())),ae===0&&tt&&Ht()?(ee.textContent=M?`No events matching '${M}'`:"No events matching filter",ee.style.display="",q.style.display="none"):(ee.style.display="none",q.style.display=""),z&&(z.title=Ht()?`Copy Filtered (${ae})`:"Copy All"),d&&!K.isFollowing()&&ae>j&&(le+=ae-j,Mt.textContent=p?`${p}${le>0?` (${le})`:""}`:"",pe.style.display=""),j=ae;let Yt=t.getAll(),Kt=Yt.length>0?Yt[0].timestamp:0,Mn=new Set(I.map(kt=>kt.id));for(let kt of Me)Mn.has(kt)||Me.delete(kt);let yn=A!==ce||M!==X,gt=We.size===0&&I.length>0;if(yn||gt||I.length===0){q.innerHTML="",We.clear();let kt=document.createDocumentFragment();for(let Ze=0;Ze<I.length;Ze++){let qt=hl(I[Ze],Ze,Kt,u,Me,er,o,s);We.set(I[Ze].id,qt),kt.appendChild(qt)}q.appendChild(kt),ce=A,X=M,ne=null}else{if(ne!==null){let Ze=We.get(ne);if(Ze&&Ze.parentNode===q){let qt=I.findIndex(ln=>ln.id===ne);if(qt>=0){let ln=hl(I[qt],qt,Kt,u,Me,er,o,s);q.insertBefore(ln,Ze),Ze.remove(),We.set(ne,ln)}}ne=null}let kt=new Set(I.map(Ze=>Ze.id));for(let[Ze,qt]of We)kt.has(Ze)||(qt.remove(),We.delete(Ze));for(let Ze=0;Ze<I.length;Ze++){let qt=I[Ze];if(!We.has(qt.id)){let ln=hl(qt,Ze,Kt,u,Me,er,o,s);We.set(qt.id,ln),q.appendChild(ln)}}}K.isFollowing()&&(q.scrollTop=q.scrollHeight)}function de(){if(Date.now()-Ee>=Fy){we!==null&&(cancelAnimationFrame(we),we=null),W();return}qe||(qe=!0,we=requestAnimationFrame(()=>{we=null,W()}))}let De=(ve,ae)=>{if(!z)return;z.innerHTML="";let tt=Se(ve,"12px","currentColor",1.5);tt&&z.appendChild(tt);let Yt=h("span","persona-text-xs");Yt.textContent="Copy All",z.appendChild(Yt),setTimeout(()=>{z.innerHTML="";let Kt=Se("clipboard-copy","12px","currentColor",1.5);Kt&&z.appendChild(Kt);let Mn=h("span","persona-text-xs");Mn.textContent="Copy All",z.appendChild(Mn),z.disabled=!1},ae)},Je=async()=>{if(z){z.disabled=!0;try{let ve;Ht()?ve=I:n?(ve=await n(),ve.length===0&&(ve=t.getAll())):ve=t.getAll();let ae=ve.map(tt=>{try{return JSON.parse(tt.payload)}catch{return tt.payload}});await navigator.clipboard.writeText(JSON.stringify(ae,null,2)),De("check",1500)}catch{De("x",1500)}}},Fe=()=>{me&&(A=me.value,an(),W())},_e=()=>{!oe||!Re||(Re.style.display=oe.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{M=oe.value,an(),W()},150))},ot=()=>{!oe||!Re||(oe.value="",M="",Re.style.display="none",F&&clearTimeout(F),an(),W())},Pt=()=>{if(Ie)return;let ve=q.scrollTop,{action:ae,nextLastScrollTop:tt}=Xa({following:K.isFollowing(),currentScrollTop:ve,lastScrollTop:he,nearBottom:Sr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=tt,ae==="resume"?(K.resume(),le=0,pe.style.display="none"):ae==="pause"&&(K.pause(),d&&(Mt.textContent=p,pe.style.display=""))},Vt=ve=>{let ae=Qa({following:K.isFollowing(),deltaY:ve.deltaY,nearBottom:Sr(),resumeWhenNearBottom:!0});ae==="pause"?(K.pause(),d&&(Mt.textContent=p,pe.style.display="")):ae==="resume"&&(K.resume(),le=0,pe.style.display="none")},Qt=()=>{d&&(q.scrollTop=q.scrollHeight,K.resume(),le=0,pe.style.display="none")},V=ve=>{let ae=ve.target;if(!ae||ae.closest("button"))return;let tt=ae.closest("[data-event-id]");if(!tt)return;let Yt=tt.getAttribute("data-event-id");Yt&&er(Yt)},xt=ve=>{if((ve.metaKey||ve.ctrlKey)&&ve.key==="f"){ve.preventDefault(),oe==null||oe.focus(),oe==null||oe.select();return}ve.key==="Escape"&&(oe&&document.activeElement===oe?(ot(),oe.blur(),P.focus()):r&&r())};z&&z.addEventListener("click",Je),me&&me.addEventListener("change",Fe),oe&&oe.addEventListener("input",_e),Re&&Re.addEventListener("click",ot),q.addEventListener("scroll",Pt),q.addEventListener("wheel",Vt,{passive:!0}),q.addEventListener("click",V),pe.addEventListener("click",Qt),P.addEventListener("keydown",xt);function at(){F&&clearTimeout(F),we!==null&&(cancelAnimationFrame(we),we=null),qe=!1,We.clear(),z&&z.removeEventListener("click",Je),me&&me.removeEventListener("change",Fe),oe&&oe.removeEventListener("input",_e),Re&&Re.removeEventListener("click",ot),q.removeEventListener("scroll",Pt),q.removeEventListener("wheel",Vt),q.removeEventListener("click",V),pe.removeEventListener("click",Qt),P.removeEventListener("keydown",xt)}return{element:P,update:de,destroy:at}}}function ym(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 xm=(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:()=>ym(e,t)});if(p)return p}return ym(e,t)};var bl=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)})}},vo=new bl;vo.register("PersonaArtifactCard",xm);function Gy(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 vm(e,t){var me,z,oe,Re;let n=(z=(me=e.features)==null?void 0:me.artifacts)==null?void 0:z.layout,s=((oe=n==null?void 0:n.toolbarPreset)!=null?oe:"default")==="document",o=(Re=n==null?void 0:n.panePadding)==null?void 0:Re.trim(),a=e.markdown?rs(e.markdown):null,i=_s(e.sanitize),d=Y=>{let Z=a?a(Y):os(Y);return i?i(Z):Z},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"),j==null||j.hide()};l&&l.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.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 Y;p(),(Y=t.onDismiss)==null||Y.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?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),D=s?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),E=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),P=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,I=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,A=n==null?void 0:n.documentToolbarCopyMenuItems,M=!!(I&&A&&A.length>0),F=null,N,R=null,j=null;if(s&&(P||I)&&!M){if(N=P?oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let Y=Se("chevron-down",14,"currentColor",2);Y&&N.appendChild(Y)}}else s&&M?(F=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),N=P?oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Gt({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(N,R)):s?N=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):N=Gt({icon:"copy",label:"Copy"});let K=s?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),le=s?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Ee=()=>{var Ye,xe,ge;let Y=(Ye=We.find(Ke=>Ke.id===ce))!=null?Ye:We[We.length-1],Z=(xe=Y==null?void 0:Y.id)!=null?xe:null,se=(Y==null?void 0:Y.artifactType)==="markdown"&&(ge=Y.markdown)!=null?ge:"",Ce=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:se,jsonPayload:Ce,id:Z}},qe=async()=>{var Ye;let{markdown:Y,jsonPayload:Z}=Ee(),se=(Ye=We.find(xe=>xe.id===ce))!=null?Ye:We[We.length-1],Ce=(se==null?void 0:se.artifactType)==="markdown"?Y:se?Z:"";try{await navigator.clipboard.writeText(Ce)}catch{}};if(N.addEventListener("click",async()=>{let Y=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Y&&M){let{markdown:Z,jsonPayload:se,id:Ce}=Ee();try{await Y({actionId:"primary",artifactId:Ce,markdown:Z,jsonPayload:se})}catch{}return}await qe()}),R&&(A!=null&&A.length)){let Y=()=>{var se;return(se=u.closest("[data-persona-root]"))!=null?se:document.body},Z=()=>{j=$o({items:A.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:Ce,jsonPayload:Ye,id:xe}=Ee(),ge=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{ge?await ge({actionId:se,artifactId:xe,markdown:Ce,jsonPayload:Ye}):se==="markdown"||se==="md"?await navigator.clipboard.writeText(Ce):se==="json"||se==="source"?await navigator.clipboard.writeText(Ye):await navigator.clipboard.writeText(Ce||Ye)}catch{}},anchor:F!=null?F:R,position:"bottom-right",portal:Y()})};u.isConnected?Z():requestAnimationFrame(Z),R.addEventListener("click",se=>{se.stopPropagation(),j==null||j.toggle()})}K.addEventListener("click",async()=>{var Y;try{await((Y=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Y.call(n))}catch{}ne()}),le.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let we=()=>{s&&(S.setAttribute("aria-pressed",x==="rendered"?"true":"false"),D.setAttribute("aria-pressed",x==="source"?"true":"false"))};S.addEventListener("click",()=>{x="rendered",we(),ne()}),D.addEventListener("click",()=>{x="source",we(),ne()});let Ie=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),w.append(S,D),F?E.append(F,K,le):E.append(N,K,le),f.append(w,Ie,E),we()):(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"),Me=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,Me.style.padding=o),u.appendChild(f),u.appendChild(he),u.appendChild(Me);let We=[],ce=null,X=!1,ne=()=>{var Ce,Ye,xe,ge;let Y=s&&We.length<=1;he.classList.toggle("persona-hidden",Y),he.replaceChildren();for(let Ke of We){let Be=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");Be.type="button",Be.textContent=Ke.title||Ke.id.slice(0,8),Ke.id===ce&&Be.classList.add("persona-bg-persona-container","persona-border-persona-border"),Be.addEventListener("click",()=>t.onSelect(Ke.id)),he.appendChild(Be)}Me.replaceChildren();let Z=ce&&We.find(Ke=>Ke.id===ce)||We[We.length-1];if(!Z)return;if(s){let Ke=Z.artifactType==="markdown"?"MD":(Ce=Z.component)!=null?Ce:"Component",q=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${q} \xB7 ${Ke}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(s&&x==="source"){let Be=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Be.textContent=(Ye=Z.markdown)!=null?Ye:"",Me.appendChild(Be);return}let Ke=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ke.innerHTML=d((xe=Z.markdown)!=null?xe:""),Me.appendChild(Ke);return}let se=Z.component?vo.get(Z.component):void 0;if(se){let Be={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let q=se((ge=Z.props)!=null?ge:{},Be);if(q){Me.appendChild(q);return}}catch{}}Me.appendChild(Gy(Z))},ie=()=>{var Z;let Y=We.length>0;if(u.classList.toggle("persona-hidden",!Y),l){let se=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ye=((Z=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&Ye&&X?(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(Y){var Z,se,Ce;We=Y.artifacts,ce=(Ce=(se=Y.selectedId)!=null?se:(Z=Y.artifacts[Y.artifacts.length-1])==null?void 0:Z.id)!=null?Ce:null,We.length>0&&(X=!0),ne(),ie()},setMobileOpen(Y){X=Y,!Y&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):ie()}}}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 wm(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 Xy(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 yi(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"),Xy(e),wm(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"),wm(e,t)}var Cm=["panel","seamless"];function xi(e,t){var i,d,l,p,u,f;for(let m of Cm)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=Cm.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 Am(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 Qy(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 Yy(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 Zy(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ex(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function Sm(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 Tm(e,t,n,r,s,o){let a=Qy(s,200),i=ex(t,n,r,200);i=Math.max(a,i);let d=Yy(o);return d!==null&&(i=Math.min(i,d)),Zy(e,a,i)}var Em={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"}},yl=(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=Em[a])!=null?x:Em.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,M;let D=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");D.htmlFor=`${t.id}-${a}-${S.name}`;let E=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=S.label,D.appendChild(E);let P=(A=S.type)!=null?A:"text",I;P==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=P),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=(M=S.placeholder)!=null?M:"",S.required&&(I.required=!0),D.appendChild(I),p.appendChild(D)});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 D=(I=n.formEndpoint)!=null?I:"/form",E=new FormData(p),P={};E.forEach((M,F)=>{P[F]=M}),P.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let M=await fetch(D,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let F=await M.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(M){f.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var xl=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()}},vi=new xl;var Mm=()=>{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 tx=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},nx=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},wi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=tx(e),n=nx(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}},vl=e=>typeof e=="string"?e:e==null?"":String(e),ys={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:vl(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=vl(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:vl(n.text)}}},km=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ci=e=>{let t=new Set(km(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(km(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 rx=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}},ox=e=>e.map(t=>({...t,streaming:!1})),sx=e=>e.map(t=>({...t,status:"complete"})),wl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?rx(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?ox(n.messages):void 0,artifacts:n.artifacts?sx(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 ax,STR as ix,OBJ as lx}from"partial-json";function cx(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function dx(e,t){if(!cx(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 Cl(){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=ax(n,ix|lx),o=dx(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function px(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Al(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=vo.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 ux(){let e=Cl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Lm(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 Sl(e){let t=Lm(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 Tl(e){let t=Lm(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 mx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function El(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=mx}=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 M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${l[A-1]}`),M.title=l[A-1],M.dataset.rating=String(A),M.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
|
+
`,M.addEventListener("click",()=>{u=A,S.forEach((F,N)=>{let R=N<A;F.classList.toggle("selected",R),F.setAttribute("aria-checked",N===A-1?"true":"false")})}),S.push(M),w.appendChild(M)}f.appendChild(w);let D=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",D=document.createElement("textarea"),D.className="persona-feedback-comment",D.placeholder=o,D.rows=3,D.setAttribute("aria-label","Additional comments"),A.appendChild(D),f.appendChild(A)}let E=document.createElement("div");E.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 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=(D==null?void 0:D.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)}}),E.appendChild(P),E.appendChild(I),f.appendChild(E),p.appendChild(f),p}function Ml(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 D=document.createElement("div");D.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=l;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=p,D.appendChild(E),D.appendChild(P);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let j=0;j<=10;j++){let K=document.createElement("button");K.type="button",K.className="persona-feedback-rating-btn persona-feedback-number-btn",K.setAttribute("role","radio"),K.setAttribute("aria-checked","false"),K.setAttribute("aria-label",`Rating ${j} out of 10`),K.textContent=String(j),K.dataset.rating=String(j),j<=6?K.classList.add("persona-feedback-detractor"):j<=8?K.classList.add("persona-feedback-passive"):K.classList.add("persona-feedback-promoter"),K.addEventListener("click",()=>{f=j,A.forEach((le,Ee)=>{le.classList.toggle("selected",Ee===j),le.setAttribute("aria-checked",Ee===j?"true":"false")})}),A.push(K),I.appendChild(K)}S.appendChild(D),S.appendChild(I),m.appendChild(S);let M=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),j.appendChild(M),m.appendChild(j)}let F=document.createElement("div");F.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{n==null||n(),u.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(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let j=(M==null?void 0:M.value.trim())||void 0;await t(f,j),u.remove()}catch(j){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),F.appendChild(N),F.appendChild(R),m.appendChild(F),u.appendChild(m),u}var xs="persona-chat-history",gx=30*1e3,fx={"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 hx(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=fx[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 Ai(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 bx(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 yx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var kl=e=>!e||typeof e!="object"?{}:{...e},Pm=e=>e.map(t=>({...t,streaming:!1})),Im=(e,t,n)=>{let r=e!=null&&e.markdown?rs(e.markdown):null,s=_s(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=os(a),s?s(d):d}};function Wm(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=Se(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 Ll=(e,t,n)=>{var 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,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc;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=Ji(t),s=vi.getForInstance(r.plugins);r.components&&vo.registerAll(r.components);let o=Mm(),i=r.persistState===!1?null:(tc=r.storageAdapter)!=null?tc:wl(),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=kl(b.metadata)),(nc=b.messages)!=null&&nc.length&&(r={...r,initialMessages:b.messages}),(rc=b.artifacts)!=null&&rc.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(oc=b.selectedArtifactId)!=null?oc: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:{}});(sc=c.messages)!=null&&sc.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:{},Go()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[wi],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ys.message,ys.messageAndClick],w=Ci({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let S=(ic=(ac=r.launcher)==null?void 0:ac.enabled)!=null?ic:!0,D=(cc=(lc=r.launcher)==null?void 0:lc.autoExpand)!=null?cc:!1,E=(dc=r.autoFocusInput)!=null?dc:!1,P=D,I=S,A=(uc=(pc=r.layout)==null?void 0:pc.header)==null?void 0:uc.layout,M=!1,F=()=>go(r),N=()=>S||F(),R=F()?!1:S?D:!0,j=!1,K=null,le=()=>{j=!0,K&&clearTimeout(K),K=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},Ee=Im(r,w,le),qe=(gc=(mc=r.features)==null?void 0:mc.showReasoning)!=null?gc:!0,we=(hc=(fc=r.features)==null?void 0:fc.showToolCalls)!=null?hc:!0,Ie=(yc=(bc=r.features)==null?void 0:bc.showEventStreamToggle)!=null?yc:!1,he=(vc=(xc=r.features)==null?void 0:xc.scrollToBottom)!=null?vc:{},Me=(Cc=(wc=r.features)==null?void 0:wc.scrollBehavior)!=null?Cc:{},ce=`${(Sc=typeof r.persistState=="object"?(Ac=r.persistState)==null?void 0:Ac.keyPrefix:void 0)!=null?Sc:"persona-"}event-stream`,X=Ie?new pa(ce):null,ne=(Mc=(Ec=(Tc=r.features)==null?void 0:Tc.eventStream)==null?void 0:Ec.maxEvents)!=null?Mc:2e3,ie=Ie?new da(ne,X):null,me=Ie?new ua:null,z=null,oe=!1,Re=null,Y=0;X==null||X.open().then(()=>ie==null?void 0:ie.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Z={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)}},se=(kc=r.statusIndicator)!=null?kc:{},Ce=c=>{var g,b,y,T;return c==="idle"?(g=se.idleText)!=null?g:Tn.idle:c==="connecting"?(b=se.connectingText)!=null?b:Tn.connecting:c==="connected"?(y=se.connectedText)!=null?y:Tn.connected:c==="error"?(T=se.errorText)!=null?T:Tn.error:Tn[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:xe,panel:ge,pillRoot:Ke}=ju(r),Be=Uu(r,N()),{container:q,body:pe,messagesWrapper:nt,suggestions:Mt,textarea:ee,sendButton:ze,sendButtonWrapper:Hn,composerForm:Ht,statusText:an,introTitle:er,introSubtitle:Sr,closeButton:W,iconHolder:de,headerTitle:De,headerSubtitle:Je,header:Fe,footer:_e,actionsRow:ot,leftActions:Pt,rightActions:Vt}=Be,Qt=Be.setSendButtonMode,V=Be.micButton,xt=Be.micButtonWrapper,at=Be.attachmentButton,ve=Be.attachmentButtonWrapper,ae=Be.attachmentInput,tt=Be.attachmentPreviewsContainer;q.classList.add("persona-relative"),pe.classList.add("persona-relative");let Yt=12,Kt=()=>{var c;return(c=he.label)!=null?c:""},Mn=()=>{var c;return(c=he.iconName)!=null?c:"arrow-down"},yn=()=>he.enabled!==!1,gt=()=>{var c;return(c=Me.mode)!=null?c:"follow"},kt=()=>{var c;return(c=Me.anchorTopOffset)!=null?c:16},Ze=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");Ze.type="button",Ze.style.display="none",Ze.setAttribute("data-persona-scroll-to-bottom","true");let qt=h("span","persona-flex persona-items-center"),ln=h("span",""),vn=h("span","");vn.setAttribute("data-persona-scroll-to-bottom-count",""),vn.style.display="none",Ze.append(qt,ln,vn),q.appendChild(Ze);let wn=h("div","persona-stream-anchor-spacer");wn.setAttribute("aria-hidden","true"),wn.setAttribute("data-persona-anchor-spacer",""),wn.style.flexShrink="0",wn.style.pointerEvents="none",wn.style.height="0px",pe.appendChild(wn);let bn=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;Ze.style.bottom=`${g+Yt}px`};bn();let Tr=()=>{let c=!!Kt();Ze.setAttribute("aria-label",Kt()||"Jump to latest"),Ze.title=Kt(),Ze.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),qt.innerHTML="";let g=Se(Mn(),"14px","currentColor",2);g?(qt.appendChild(g),qt.style.display=""):qt.style.display="none",ln.textContent=Kt(),ln.style.display=c?"":"none"};Tr();let At=null,$n=null,_n=s.find(c=>c.renderHeader);if(_n!=null&&_n.renderHeader){let c=_n.renderHeader({config:r,defaultRenderer:()=>{let g=fo({config:r,showClose:N()});return ps(q,g,r),g.header},onClose:()=>Dt(!1,"user")});if(c){let g=q.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Fe=c)}}let Dr=()=>{var g,b,y,T;if(!ie)return;if(oe=!0,!z&&ie&&(z=bm({buffer:ie,getFullHistory:()=>ie.getAllFromStore(),onClose:()=>gr(),config:r,plugins:s,getThroughput:()=>{var B;return(B=me==null?void 0:me.getMetric())!=null?B:{status:"idle"}}})),z&&(pe.style.display="none",(g=_e.parentNode)==null||g.insertBefore(z.element,_e),z.update()),vt){vt.style.boxShadow=`inset 0 0 0 1.5px ${Rn.actionIconColor}`;let B=(T=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:T.toggleButtonActive;B&&B.split(/\s+/).forEach(O=>O&&vt.classList.add(O))}let c=()=>{if(!oe)return;let B=Date.now();B-Y>=200&&(z==null||z.update(),Y=B),Re=requestAnimationFrame(c)};Y=0,Re=requestAnimationFrame(c),Nn(),o.emit("eventStream:opened",{timestamp:Date.now()})},gr=()=>{var c,g,b;if(oe){if(oe=!1,z&&z.element.remove(),pe.style.display="",vt){vt.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&&vt.classList.remove(T))}Re!==null&&(cancelAnimationFrame(Re),Re=null),Nn(),o.emit("eventStream:closed",{timestamp:Date.now()})}},vt=null;if(Ie){let c=(Pc=(Lc=r.features)==null?void 0:Lc.eventStream)==null?void 0:Pc.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:"");vt=h("button",g),vt.style.width="28px",vt.style.height="28px",vt.style.color=Rn.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let b=Se("activity","18px","currentColor",1.5);b&&vt.appendChild(b);let y=Be.clearChatButtonWrapper,T=Be.closeButtonWrapper,B=y||T;B&&B.parentNode===Fe?Fe.insertBefore(vt,B):Fe.appendChild(vt),vt.addEventListener("click",()=>{oe?gr():Dr()})}let Co=c=>{var y,T,B;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 O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(b,O):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=h("input");O.type="file",O.accept=((y=g.allowedTypes)!=null?y:Vr).join(","),O.multiple=((T=g.maxFiles)!=null?T:4)>1,O.style.display="none",O.setAttribute("aria-label",(B=g.buttonTooltipText)!=null?B:"Attach files"),c.appendChild(O)}},Er=s.find(c=>c.renderComposer);if(Er!=null&&Er.renderComposer){let c=r.composer,g=Er.renderComposer({config:r,defaultRenderer:()=>aa({config:r}).footer,onSubmit:b=>{var O;if(!$||$.isStreaming())return;let y=b.trim(),T=(O=At==null?void 0:At.hasAttachments())!=null?O:!1;if(!y&&!T)return;C();let B;T&&(B=[],B.push(...At.getContentParts()),y&&B.push($a(y))),$.sendMessage(y,{contentParts:B}),T&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ae==null||ae.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:((Ic=r.voiceRecognition)==null?void 0:Ic.enabled)===!0?()=>{$n==null||$n()}:void 0});g&&(_e.replaceWith(g),_e=g)}let Ao=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]"),B=c.querySelector("[data-persona-composer-status]");g&&(Ht=g),b&&(ee=b),y&&(ze=y),T&&(V=T,xt=T.parentElement),B&&(an=B);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Mt=O);let U=c.querySelector(".persona-attachment-button");U&&(at=U,ve=U.parentElement),ae=c.querySelector('input[type="file"]'),tt=c.querySelector(".persona-attachment-previews");let H=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");H&&(ot=H)};Co(_e),Ao(_e);let Bn=(Dc=(Wc=r.layout)==null?void 0:Wc.contentMaxWidth)!=null?Dc:F()?(Bc=(Hc=(Rc=r.launcher)==null?void 0:Rc.composerBar)==null?void 0:Hc.contentMaxWidth)!=null?Bc:"720px":void 0;if(Bn&&(nt.style.maxWidth=Bn,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),Bn&&Ht&&!F()&&(Ht.style.maxWidth=Bn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Bn&&Mt&&!F()&&(Mt.style.maxWidth=Bn,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),Bn&&tt&&!F()&&(tt.style.maxWidth=Bn,tt.style.marginLeft="auto",tt.style.marginRight="auto"),(Nc=r.attachments)!=null&&Nc.enabled&&ae&&tt){At=cs.fromConfig(r.attachments),At.setPreviewsContainer(tt),ae.addEventListener("change",b=>{let y=b.target;At==null||At.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,g=Wm(c);q.appendChild(g)}(()=>{var y,T;let c=(T=(y=r.layout)==null?void 0:y.slots)!=null?T:{},g=B=>{switch(B){case"body-top":return q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return nt;case"footer-top":return Mt;case"composer":return Ht;case"footer-bottom":return an;default:return null}},b=(B,O)=>{var U;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")Fe.insertBefore(O,Fe.firstChild);else if(B==="header-right")Fe.appendChild(O);else{let H=Fe.querySelector(".persona-flex-col");H?(U=H.parentNode)==null||U.insertBefore(O,H.nextSibling):Fe.appendChild(O)}break;case"body-top":{let H=pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(O):pe.insertBefore(O,pe.firstChild);break}case"body-bottom":pe.appendChild(O);break;case"footer-top":Mt.replaceWith(O);break;case"footer-bottom":an.replaceWith(O);break;default:break}};for(let[B,O]of Object.entries(c))if(O)try{let U=O({config:r,defaultContent:()=>g(B)});U&&b(B,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,U)}})();let Gr=c=>{var O,U;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 B=b.getAttribute("data-bubble-type");if(B==="reasoning")ms.has(T)?ms.delete(T):ms.add(T),Ju(T,y);else if(B==="tool")gs.has(T)?gs.delete(T):gs.add(T),Gu(T,y,r);else if(B==="approval"){let H=r.approval!==!1?r.approval:void 0,ye=((O=H==null?void 0:H.detailsDisplay)!=null?O:"collapsed")==="expanded",ue=(U=fi.get(T))!=null?U:ye;fi.set(T,!ue),um(T,y,r)}$r.delete(T)};nt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Gr(c))}),nt.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Gr(c))});let Nr=new Map;nt.addEventListener("click",c=>{var O;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 B=b.getAttribute("data-action");if(B==="copy"){let H=$.getMessages().find(ye=>ye.id===T);if(H&&Z.onCopy){let ye=H.content||"";navigator.clipboard.writeText(ye).then(()=>{b.classList.add("persona-message-action-success");let ue=Se("check",14,"currentColor",2);ue&&(b.innerHTML="",b.appendChild(ue)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let te=Se("copy",14,"currentColor",2);te&&(b.innerHTML="",b.appendChild(te))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),Z.onCopy(H)}}else if(B==="upvote"||B==="downvote"){let H=((O=Nr.get(T))!=null?O:null)===B,ye=B==="upvote"?"thumbs-up":"thumbs-down";if(H){Nr.delete(T),b.classList.remove("persona-message-action-active");let ue=Se(ye,14,"currentColor",2);ue&&(b.innerHTML="",b.appendChild(ue))}else{let ue=B==="upvote"?"downvote":"upvote",te=y.querySelector(`[data-action="${ue}"]`);if(te){te.classList.remove("persona-message-action-active");let Ve=Se(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ve&&(te.innerHTML="",te.appendChild(Ve))}Nr.set(T,B),b.classList.add("persona-message-action-active");let Te=Se(ye,14,"currentColor",2);Te&&(Te.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Te)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Ae=$.getMessages().find(rt=>rt.id===T);Ae&&Z.onFeedback&&Z.onFeedback({type:B,messageId:Ae.id,message:Ae})}}}),nt.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 B=b.getAttribute("data-approval-action");if(!B)return;let O=B==="approve"?"approved":"denied",H=$.getMessages().find(ue=>ue.id===T);if(!(H!=null&&H.approval))return;let ye=y.querySelector("[data-approval-buttons]");ye&&ye.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?$.resolveWebMcpApproval(T,O):$.resolveApproval(H.approval,O)});let St=null,jn=null,Un={artifacts:[],selectedId:null},kn=!1,Lt={current:null};nt.addEventListener("click",c=>{var te,Te,$e,Ae,rt;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||(($e=(Te=(te=r.features)==null?void 0:te.artifacts)==null?void 0:Te.onArtifactAction)==null?void 0:$e.call(Te,{type:"download",artifactId:y}))===!0)return;let B=$.getArtifactById(y),O=B==null?void 0:B.markdown,U=(B==null?void 0:B.title)||"artifact";if(!O){let Ve=b.closest("[data-open-artifact]"),ct=Ve==null?void 0:Ve.closest("[data-message-id]"),dt=ct==null?void 0:ct.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);O=(Ae=Ue==null?void 0:Ue.props)==null?void 0:Ae.markdown,U=((rt=Ue==null?void 0:Ue.props)==null?void 0:rt.title)||U}catch{}}}if(!O)return;let H=new Blob([O],{type:"text/markdown"}),ye=URL.createObjectURL(H),ue=document.createElement("a");ue.href=ye,ue.download=`${U}.md`,ue.click(),URL.revokeObjectURL(ye)}),nt.addEventListener("click",c=>{var B,O,U;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((U=(O=(B=r.features)==null?void 0:B.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:U.call(O,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),kn=!1,$.selectArtifact(y),Vn())}),nt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let tr=Be.composerOverlay,nr=(c,g,b)=>{var U,H,ye,ue;let y=g.trim();if(!y||!Lt.current)return;let T=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",B=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:y,answers:b.structured,values:(H=b.values)!=null?H:b.source==="multi"?y.split(", "):[y],isFreeText:B,source:b.source},bubbles:!0,composed:!0})),jo(tr,T);let O=Lt.current.getMessages().find(te=>{var Te;return((Te=te.toolCall)==null?void 0:Te.id)===T});(ye=O==null?void 0:O.agentMetadata)!=null&&ye.awaitingLocalTool?Lt.current.resolveAskUserQuestion(O,(ue=b.structured)!=null?ue:y):Lt.current.sendMessage(y)},qn=c=>{var T;let g=Lt.current;if(!g)return;let b=(T=c.getAttribute("data-tool-call-id"))!=null?T:"",y=g.getMessages().find(B=>{var O;return((O=B.toolCall)==null?void 0:O.id)===b});y&&g.persistAskUserQuestionProgress(y,{answers:mi(c,y),currentIndex:ur(c)})},Xr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Or=c=>{var T,B,O;if(((B=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let g=ur(c),b=hs(c);if(g>=b-1)return;let y=(O=Lt.current)==null?void 0:O.getMessages().find(U=>{var H;return((H=U.toolCall)==null?void 0:H.id)===c.getAttribute("data-tool-call-id")});y&&(gi(c,y,r,g+1),qn(c))};tr.addEventListener("click",c=>{var B,O,U,H,ye,ue,te,Te,$e,Ae,rt,Ve,ct,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=(B=y.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),jo(tr,Pe);let ke=(O=Lt.current)==null?void 0:O.getMessages().find(Ue=>{var Xe;return((Xe=Ue.toolCall)==null?void 0:Xe.id)===Pe});(U=ke==null?void 0:ke.agentMetadata)!=null&&U.awaitingLocalTool&&((H=Lt.current)==null||H.markAskUserQuestionResolved(ke),(ye=Lt.current)==null||ye.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=yo(y);if(Ue&&ke){let Xe=_o(y)[ur(y)],wt=new Set(Array.isArray(Xe)?Xe:[]);wt.has(Pe)?wt.delete(Pe):wt.add(Pe),xo(y,Array.from(wt)),qn(y);return}if(Ue){xo(y,Pe),qn(y),Or(y);return}if(ke){let Xe=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",Xe?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!Xe);let wt=y.querySelector('[data-ask-user-action="submit-multi"]');wt&&(wt.disabled=gl(y).length===0);return}nr(y,Pe,{source:"pick",values:[Pe]});return}if(T==="submit-multi"){let Pe=gl(y);if(Pe.length===0)return;nr(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=(ue=Pe==null?void 0:Pe.value)!=null?ue:"";if(!ke.trim())return;if(yo(y)){xo(y,ke.trim()),qn(y),Or(y);return}nr(y,ke,{source:"free-text"});return}if(T==="next"||T==="back"){if(!Lt.current)return;let Pe=(te=y.getAttribute("data-tool-call-id"))!=null?te:"",ke=Lt.current.getMessages().find(He=>{var Ne;return((Ne=He.toolCall)==null?void 0:Ne.id)===Pe});if(!ke)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Xe=($e=(Te=Ue==null?void 0:Ue.value)==null?void 0:Te.trim())!=null?$e:"";if(Xe){let He=_o(y)[ur(y)];(typeof He!="string"||He!==Xe)&&xo(y,Xe)}let wt=T==="next"?1:-1,L=ur(y)+wt;gi(y,ke,r,L),qn(y);return}if(T==="submit-all"){if(!Lt.current)return;let Pe=(Ae=y.getAttribute("data-tool-call-id"))!=null?Ae:"",ke=Lt.current.getMessages().find(He=>{var Ne;return((Ne=He.toolCall)==null?void 0:Ne.id)===Pe});if(!ke)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Xe=(Ve=(rt=Ue==null?void 0:Ue.value)==null?void 0:rt.trim())!=null?Ve:"";Xe&&xo(y,Xe);let wt=mi(y,ke);Lt.current.persistAskUserQuestionProgress(ke,{answers:wt,currentIndex:ur(y)});let L=Xr(wt);nr(y,L||"(submitted)",{source:"submit-all",structured:wt});return}if(T==="skip"){if(!Lt.current)return;let Pe=(ct=y.getAttribute("data-tool-call-id"))!=null?ct:"",ke=Lt.current.getMessages().find(Ne=>{var fe;return((fe=Ne.toolCall)==null?void 0:fe.id)===Pe});if(!ke)return;let Ue=yo(y),Xe=ur(y),wt=hs(y),L=Xe>=wt-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),jo(tr,Pe),(dt=ke.agentMetadata)!=null&&dt.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(ke),Lt.current.resolveAskUserQuestion(ke,"(dismissed)"));return}xo(y,"");let He=y.querySelector('[data-ask-free-text-input="true"]');if(He&&(He.value=""),L){let Ne=mi(y,ke),fe=Xr(Ne);nr(y,fe||"(skipped)",{source:"submit-all",structured:Ne});return}gi(y,ke,r,Xe+1),qn(y);return}}),tr.addEventListener("keydown",c=>{var B;if(c.key!=="Enter")return;let b=c.target;if(!((B=b.matches)!=null&&B.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(yo(y)){xo(y,T.trim()),qn(y),Or(y);return}nr(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=tr.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),B=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];B&&(c.preventDefault(),B.click())};document.addEventListener("keydown",Qr);let zn=null,Bt=null,Ln=null,rr=null,Yr=()=>{};function Fr(){rr==null||rr(),rr=null}let Zr=()=>{var O;if(!zn||!Bt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((O=e.ownerDocument.defaultView)!=null?O: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=zn.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 B=y.offsetWidth-T/2;Bt.style.left=`${Math.max(0,B)}px`},Mr=()=>{},Vn=()=>{var b,y,T,B,O;if(!St||!mr(r))return;yi(e,r),xi(e,r),Mr();let c=(B=(T=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.layout)==null?void 0:T.narrowHostMaxWidth)!=null?B:520,g=ge.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),St.update(Un),kn?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(O=St.backdrop)==null||O.classList.add("persona-hidden")):Un.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),Yr()};if(mr(r)){ge.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(q),St=vm(r,{onSelect:b=>{var y;return(y=Lt.current)==null?void 0:y.selectArtifact(b)},onDismiss:()=>{kn=!0,Vn()}}),St.element.classList.add("persona-hidden"),zn=g,g.appendChild(c),g.appendChild(St.element),St.backdrop&&ge.appendChild(St.backdrop),ge.appendChild(g),Yr=()=>{var y,T,B,O;if(!zn||!St)return;if(!(((B=(T=(y=r.features)==null?void 0:y.artifacts)==null?void 0:T.layout)==null?void 0:B.resizable)===!0)){Ln==null||Ln(),Ln=null,Fr(),Bt&&(Bt.remove(),Bt=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Bt){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 H=e.ownerDocument,ye=(O=H.defaultView)!=null?O:window,ue=te=>{var ct,dt;if(!St||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||ye.innerWidth<=640)return;te.preventDefault(),Fr();let Te=te.clientX,$e=St.element.getBoundingClientRect().width,Ae=(dt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:dt.layout,rt=Pe=>{let ke=zn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),Xe=Ue?0:Sm(zn,ye),wt=Ue?0:U.getBoundingClientRect().width||6,L=$e-(Pe.clientX-Te),He=Tm(L,ke,Xe,wt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);St.element.style.width=`${He}px`,St.element.style.maxWidth="none",Zr()},Ve=()=>{H.removeEventListener("pointermove",rt),H.removeEventListener("pointerup",Ve),H.removeEventListener("pointercancel",Ve),rr=null;try{U.releasePointerCapture(te.pointerId)}catch{}};rr=Ve,H.addEventListener("pointermove",rt),H.addEventListener("pointerup",Ve),H.addEventListener("pointercancel",Ve);try{U.setPointerCapture(te.pointerId)}catch{}};U.addEventListener("pointerdown",ue),Bt=U,zn.insertBefore(U,St.element),Ln=()=>{U.removeEventListener("pointerdown",ue)}}if(Bt){let U=Un.artifacts.length>0&&!kn;Bt.classList.toggle("persona-hidden",!U),Zr()}},Mr=()=>{var ye,ue,te,Te,$e,Ae,rt,Ve,ct,dt,Pe,ke,Ue,Xe;if(!S||!St||((ue=(ye=r.launcher)==null?void 0:ye.sidebarMode)!=null?ue:!1)||hn(r)&&Cr(r).reveal==="emerge")return;let y=(te=e.ownerDocument.defaultView)!=null?te:window,T=($e=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?$e:!0,B=(rt=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?rt:640;if(T&&y.innerWidth<=B||!Am(r,S))return;let O=(dt=(ct=(Ve=r.launcher)==null?void 0:Ve.width)!=null?ct:r.launcherWidth)!=null?dt:pr,U=(Xe=(Ue=(ke=(Pe=r.features)==null?void 0:Pe.artifacts)==null?void 0:ke.layout)==null?void 0:Ue.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";Un.artifacts.length>0&&!kn?(ge.style.width=U,ge.style.maxWidth=U):(ge.style.width=O,ge.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(jn=new ResizeObserver(()=>{Vn()}),jn.observe(ge))}else ge.appendChild(q),F()&&Ke&&(Be.peekBanner&&Ke.appendChild(Be.peekBanner),Ke.appendChild(_e));e.appendChild(xe),Ke&&e.appendChild(Ke);let fr=()=>{var He,Ne,fe,Ft,Nt,Jt,Ct,zt,Xn,on,Qe,It,dn,cr,Qn,ko,Lo,ts,ns,Xt,Po,lo,co,zr,st,xn,Pn,sn;if(F()){ge.style.width="100%",ge.style.maxWidth="100%";let pt=(Ne=(He=r.launcher)==null?void 0:He.composerBar)!=null?Ne:{},bt=xe.dataset.state==="expanded",ut=(fe=pt.expandedSize)!=null?fe:"anchored";if(!(bt&&ut!=="fullscreen")){q.style.background="",q.style.border="",q.style.borderRadius="",q.style.overflow="",q.style.boxShadow="";return}let pn=(Nt=(Ft=r.theme)==null?void 0:Ft.components)==null?void 0:Nt.panel,Rr=Qs(r),un=(Wo,Pa)=>{var Os;return Wo==null||Wo===""?Pa:(Os=ds(Rr,Wo))!=null?Os:Wo},In="1px solid var(--persona-border)",dr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";q.style.background="var(--persona-surface, #ffffff)",q.style.border=un(pn==null?void 0:pn.border,In),q.style.borderRadius=un(pn==null?void 0:pn.borderRadius,Io),q.style.boxShadow=un(pn==null?void 0:pn.shadow,dr),q.style.overflow="hidden";return}let c=hn(r),g=(Ct=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?Ct:!1,b=c||g||((Xn=(zt=r.launcher)==null?void 0:zt.fullHeight)!=null?Xn:!1),y=((on=r.launcher)==null?void 0:on.enabled)===!1,T=(It=(Qe=r.theme)==null?void 0:Qe.components)==null?void 0:It.panel,B=Qs(r),O=(pt,bt)=>{var ut;return pt==null||pt===""?bt:(ut=ds(B,pt))!=null?ut:pt},U=(dn=e.ownerDocument.defaultView)!=null?dn:window,H=(Qn=(cr=r.launcher)==null?void 0:cr.mobileFullscreen)!=null?Qn:!0,ye=(Lo=(ko=r.launcher)==null?void 0:ko.mobileBreakpoint)!=null?Lo:640,ue=U.innerWidth<=ye,te=H&&ue&&S,Te=(ns=(ts=r.launcher)==null?void 0:ts.position)!=null?ns:"bottom-left",$e=Te==="bottom-left"||Te==="top-left",Ae=(Po=(Xt=r.launcher)==null?void 0:Xt.zIndex)!=null?Po:En,rt=g||te?"none":"1px solid var(--persona-border)",Ve=te?"none":g?$e?"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&&!te&&(Ve="none",rt="none");let ct=g||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",dt=O(T==null?void 0:T.border,rt),Pe=O(T==null?void 0:T.shadow,Ve),ke=O(T==null?void 0:T.borderRadius,ct),Ue=pe.scrollTop;e.style.cssText="",xe.style.cssText="",ge.style.cssText="",q.style.cssText="",pe.style.cssText="",_e.style.cssText="";let Xe=()=>{var bt;if(Ue<=0)return;((bt=pe.ownerDocument.defaultView)!=null?bt:window).requestAnimationFrame(()=>{if(pe.scrollTop===Ue)return;let ut=pe.scrollHeight-pe.clientHeight;ut<=0||(pe.scrollTop=Math.min(Ue,ut))})};if(te){xe.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"),xe.style.cssText=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -37,9 +37,9 @@ _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: ${
|
|
40
|
+
z-index: ${Ae} !important;
|
|
41
41
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
42
|
-
`,
|
|
42
|
+
`,ge.style.cssText=`
|
|
43
43
|
position: relative !important;
|
|
44
44
|
display: flex !important;
|
|
45
45
|
flex-direction: column !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
|
-
`,
|
|
55
|
+
`,q.style.cssText=`
|
|
56
56
|
display: flex !important;
|
|
57
57
|
flex-direction: column !important;
|
|
58
58
|
flex: 1 1 0% !important;
|
|
@@ -63,20 +63,20 @@ _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
|
-
`,
|
|
66
|
+
`,pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",_e.style.flexShrink="0",M=!0,Xe();return}let wt=(co=(lo=r==null?void 0:r.launcher)==null?void 0:lo.width)!=null?co:r==null?void 0:r.launcherWidth,L=wt!=null?wt:pr;if(!g&&!c)y&&b?(ge.style.width="100%",ge.style.maxWidth="100%"):(ge.style.width=L,ge.style.maxWidth=L);else if(c)if(Cr(r).reveal==="emerge"){let bt=Cr(r).width;ge.style.width=bt,ge.style.maxWidth=bt}else ge.style.width="100%",ge.style.maxWidth="100%";if(Mr(),ge.style.boxShadow=Pe,ge.style.borderRadius=ke,q.style.border=dt,q.style.borderRadius=ke,c&&!te&&(T==null?void 0:T.border)===void 0&&(q.style.border="none",Cr(r).side==="right"?q.style.borderLeft="1px solid var(--persona-border)":q.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%"),xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.height="100%",y&&(xe.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.height="100%",ge.style.overflow="hidden",q.style.display="flex",q.style.flexDirection="column",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.maxHeight="100%",q.style.overflow="hidden",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",_e.style.flexShrink="0"),xe.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&&((zr=Ar[Te])!=null?zr:Ar["bottom-right"]).split(" ").forEach(bt=>xe.classList.add(bt)),g){let pt=(xn=(st=r.launcher)==null?void 0:st.sidebarWidth)!=null?xn:"420px";xe.style.cssText=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
70
|
-
width: ${
|
|
70
|
+
width: ${pt} !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: ${
|
|
78
|
-
${
|
|
79
|
-
`,
|
|
77
|
+
z-index: ${Ae} !important;
|
|
78
|
+
${$e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
79
|
+
`,ge.style.cssText=`
|
|
80
80
|
position: relative !important;
|
|
81
81
|
display: flex !important;
|
|
82
82
|
flex-direction: column !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: ${
|
|
91
|
-
border-radius: ${
|
|
92
|
-
`,
|
|
90
|
+
box-shadow: ${Pe} !important;
|
|
91
|
+
border-radius: ${ke} !important;
|
|
92
|
+
`,ge.style.setProperty("width","100%","important"),ge.style.setProperty("max-width","100%","important"),q.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: ${
|
|
102
|
-
border: ${
|
|
103
|
-
`,
|
|
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&>.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&>.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&>.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:
|
|
109
|
-
`)}}];function
|
|
107
|
+
`}if(!y&&!c){let pt="max-height: -moz-available !important; max-height: stretch !important;",bt=g?"":"padding-top: 1.25em !important;",ut=g?"":`z-index: ${(sn=(Pn=r.launcher)==null?void 0:Pn.zIndex)!=null?sn:En} !important;`;xe.style.cssText+=pt+bt+ut}Xe()};fr(),Oo(e,r),yi(e,r),xi(e,r);let ht=[];ht.push(()=>{document.removeEventListener("keydown",Qr)});let Zt=null,en=null;ht.push(()=>{Zt==null||Zt(),Zt=null,en==null||en(),en=null}),jn&&ht.push(()=>{jn==null||jn.disconnect(),jn=null}),ht.push(()=>{Ln==null||Ln(),Ln=null,Fr(),Bt&&(Bt.remove(),Bt=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),Ie&&ht.push(()=>{Re!==null&&(cancelAnimationFrame(Re),Re=null),z==null||z.destroy(),z=null,ie==null||ie.destroy(),ie=null,X=null});let Kn=null,eo=()=>{Kn&&(Kn(),Kn=null),r.colorScheme==="auto"&&(Kn=Qi(()=>{Oo(e,r)}))};eo(),ht.push(()=>{Kn&&(Kn(),Kn=null)});let be=(Oc=r.features)==null?void 0:Oc.streamAnimation;if(be!=null&&be.type&&be.type!=="none"){let c=ea(be.type,be.plugins);c&&(el(c,e),ht.push(()=>Du(e)))}let or=mm(Mt),sr=null,$,kr=!1,$r=Mu(),_r=new Map,Lr=new Map,hr=new Map,ws=0,Jn=Ga(),Gn=0,br=null,yr=!1,So=!1,jr=0,Cn=null,Pr=null,zo=!1,To=!1,Vo=null,ga=4,Ko=24,fa=80,Jo=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Cs=($c=(Fc=r.voiceRecognition)==null?void 0:Fc.autoResume)!=null?$c:!1,ar=c=>{o.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},Dn=()=>{m(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},ha=()=>{var y,T;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=kl(d.voiceState),g=!!c.active,b=Number((T=c.timestamp)!=null?T:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<gx&&setTimeout(()=>{var B,O;yt.active||(yt.manuallyDeactivated=!1,((O=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:O.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),ar("restore"),$.isVoiceActive()&&Bs()}):mn("restore"))},1e3)},ba=()=>$?Pm($.getMessages()).filter(c=>!c.__skipPersist):[];function Go(c){if(!(i!=null&&i.save))return;let b={messages:c?Pm(c):$?ba():[],metadata:d,artifacts:Un.artifacts,selectedArtifactId:Un.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 Ur=null,As=()=>xe.querySelector("#persona-scroll-container")||pe,to=()=>{Ur!==null&&(cancelAnimationFrame(Ur),Ur=null),yr=!1},Ss=()=>{br!==null&&(cancelAnimationFrame(br),br=null),So=!1,to()},Ts=()=>{jr>0?(vn.textContent=String(jr),vn.style.display="",Ze.setAttribute("aria-label",`${Kt()||"Jump to latest"} (${jr} new)`)):(vn.textContent="",vn.style.display="none",Ze.setAttribute("aria-label",Kt()||"Jump to latest"))},Es=()=>{jr!==0&&(jr=0,Ts())},Ms=()=>gt()==="follow"?!Jn.isFollowing():!Fo(pe,Ko),Nn=()=>{if(!yn()||oe){Ze.parentNode&&Ze.remove(),Ze.style.display="none";return}Ze.parentNode!==q&&q.appendChild(Ze),bn();let g=Kr(pe)>0&&Ms();g||Es(),Ze.style.display=g?"":"none"},Xo=()=>{Jn.pause()&&(Ss(),Nn())},Ir=()=>{Jn.resume(),Es(),Nn()},Wr=(c=!1)=>{gt()==="follow"&&Jn.isFollowing()&&(!c&&!kr||(br!==null&&(cancelAnimationFrame(br),br=null),So=!0,br=requestAnimationFrame(()=>{br=null,So=!1,Jn.isFollowing()&&ya(As(),c?220:140)})))},ks=(c,g,b,y=()=>!0)=>{let T=c.scrollTop,B=g(),O=B-T;to();let U=performance.now();yr=!0;let H=ue=>1-Math.pow(1-ue,3),ye=ue=>{if(!y()){to();return}let te=g();te!==B&&(B=te,O=B-T);let Te=ue-U,$e=Math.min(Te/b,1),Ae=H($e),rt=T+O*Ae;c.scrollTop=rt,Gn=c.scrollTop,$e<1?Ur=requestAnimationFrame(ye):(c.scrollTop=B,Gn=c.scrollTop,Ur=null,yr=!1)};Ur=requestAnimationFrame(ye)},ya=(c,g=500)=>{let b=Kr(c)-c.scrollTop;if(Math.abs(b)<1){Gn=c.scrollTop;return}if(Math.abs(b)>=fa){to(),yr=!0,c.scrollTop=Kr(c),Gn=c.scrollTop,yr=!1;return}ks(c,()=>Kr(c),g,()=>Jn.isFollowing())},Ls=()=>{let c=As();yr=!0,c.scrollTop=Kr(c),Gn=c.scrollTop,yr=!1,Nn()},Ps=c=>{wn.style.height=`${Math.max(0,Math.round(c))}px`,Cn&&(Cn.spacerHeight=Math.max(0,c))},Eo=()=>{Pr!==null&&(cancelAnimationFrame(Pr),Pr=null),to(),Cn=null,wn.style.height="0px"},xa=c=>{Pr!==null&&cancelAnimationFrame(Pr),Pr=requestAnimationFrame(()=>{var ye;Pr=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=pe.querySelector(`[data-message-id="${g}"]`);if(!b)return;let y=0,T=b;for(;T&&T!==pe;)y+=T.offsetTop,T=T.offsetParent;let B=(ye=Cn==null?void 0:Cn.spacerHeight)!=null?ye:0,O=pe.scrollHeight-B,{targetScrollTop:U,spacerHeight:H}=Wu({anchorOffsetTop:y,topOffset:kt(),viewportHeight:pe.clientHeight,contentHeight:O});Cn={initialSpacerHeight:H,contentHeightAtAnchor:O,spacerHeight:H},Ps(H),ks(pe,()=>U,220)})},va=()=>{if(gt()==="follow"){if(!Jn.isFollowing()||Fo(pe,1))return;Wr(!kr);return}if(Cn&&Cn.initialSpacerHeight>0){let c=pe.scrollHeight-Cn.spacerHeight,g=Ru({initialSpacerHeight:Cn.initialSpacerHeight,contentHeightAtAnchor:Cn.contentHeightAtAnchor,currentContentHeight:c});g!==Cn.spacerHeight&&Ps(g)}Nn()},wa=c=>{let g=gt();g==="follow"?(Ir(),Wr(!0)):g==="anchor-top"&&xa(c)},Ca=c=>{let g=new Map;c.forEach(b=>{let y=Jo.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!y&&b.role==="assistant"&&(o.emit("assistant:message",b),!To&>()!=="anchor-top"&&Ms()&&(jr+=1,Ts(),Nn())),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}))}),Jo.clear(),g.forEach((b,y)=>{Jo.set(y,b)})},Mo=(c,g,b)=>{var dt,Pe,ke,Ue,Xe,wt;let y=document.createElement("div"),B=(()=>{var He;let L=s.find(Ne=>Ne.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((He=r.loadingIndicator)!=null&&He.render)return r.loadingIndicator.render})(),O=(L,He)=>He==null?!1:typeof He=="string"?(L.textContent=He,!0):(L.appendChild(He),!0),U=new Set,H=new Set,ye=s.some(L=>L.renderAskUserQuestion),ue=[],te=[],Te=r.enableComponentStreaming!==!1,$e=s.some(L=>L.renderApproval)&&r.approval!==!1,Ae=[];if(g.forEach(L=>{var Qe,It,dn,cr,Qn,ko,Lo,ts,ns,Xt,Po,lo,co,zr;U.add(L.id);let He=ye&&ho(L),Ne=$e&&L.variant==="approval"&&!!L.approval,fe=!He&&L.role==="assistant"&&!L.variant&&Te&&Sl(L);if(!Ne&&hr.has(L.id)){let st=c.querySelector(`#wrapper-${L.id}`);st==null||st.removeAttribute("data-preserve-runtime"),hr.delete(L.id)}if(!fe&&Lr.has(L.id)){let st=c.querySelector(`#wrapper-${L.id}`);st==null||st.removeAttribute("data-preserve-runtime"),Lr.delete(L.id)}let Ft=ho(L)?`:${(Qe=L.agentMetadata)!=null&&Qe.askUserQuestionAnswered?"a":"u"}:${(It=L.agentMetadata)!=null&&It.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt=Eu(L,ws)+Ft,Jt=He||Ne||fe?null:ku($r,L.id,Nt);if(Jt){y.appendChild(Jt.cloneNode(!0)),ho(L)&&((dn=L.toolCall)!=null&&dn.id)&&((cr=L.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Qn=L.agentMetadata)!=null&&Qn.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ca(L,r,Be.composerOverlay));return}let Ct=null,zt=s.find(st=>!!(L.variant==="reasoning"&&st.renderReasoning||L.variant==="tool"&&st.renderToolCall||!L.variant&&st.renderMessage)),Xn=(ko=r.layout)==null?void 0:ko.messages;if(ho(L)&&((Lo=L.agentMetadata)==null?void 0:Lo.askUserQuestionAnswered)===!0){_r.delete(L.id);let st=c.querySelector(`#wrapper-${L.id}`);st==null||st.removeAttribute("data-preserve-runtime");return}if(ho(L)&&((ns=(ts=r.features)==null?void 0:ts.askUserQuestion)==null?void 0:ns.enabled)!==!1){let st=s.find(xn=>typeof xn.renderAskUserQuestion=="function");if(st&&Lt.current){let xn=_r.get(L.id),Pn=xn!==Nt,sn=null;if(Pn){let{payload:ut,complete:On}=bo(L),pn=L.id,Rr=()=>{var un;return(un=Lt.current)==null?void 0:un.getMessages().find(In=>In.id===pn)};sn=st.renderAskUserQuestion({message:L,payload:ut,complete:On,resolve:un=>{var dr;let In=Rr();In&&((dr=Lt.current)==null||dr.resolveAskUserQuestion(In,un))},dismiss:()=>{var In,dr,Io;let un=Rr();(In=un==null?void 0:un.agentMetadata)!=null&&In.awaitingLocalTool&&((dr=Lt.current)==null||dr.markAskUserQuestionResolved(un),(Io=Lt.current)==null||Io.resolveAskUserQuestion(un,"(dismissed)"))},config:r})}let pt=xn!=null;if(Pn&&sn===null&&!pt){((Xt=L.agentMetadata)==null?void 0:Xt.awaitingLocalTool)===!0&&!((Po=L.agentMetadata)!=null&&Po.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ca(L,r,Be.composerOverlay));return}let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${L.id}`,bt.setAttribute("data-wrapper-id",L.id),bt.setAttribute("data-ask-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),y.appendChild(bt),ue.push({messageId:L.id,fingerprint:Nt,bubble:sn});return}else{((lo=L.agentMetadata)==null?void 0:lo.awaitingLocalTool)===!0&&!((co=L.agentMetadata)!=null&&co.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ca(L,r,Be.composerOverlay));return}}else if(Ne){let st=s.find(pt=>typeof pt.renderApproval=="function"),Pn=hr.get(L.id)!==Nt,sn=null;if(Pn&&(st!=null&&st.renderApproval)){let pt=L.id,bt=(ut,On)=>{var Rr,un,In;let pn=(Rr=Lt.current)==null?void 0:Rr.getMessages().find(dr=>dr.id===pt);pn!=null&&pn.approval&&(pn.approval.toolType==="webmcp"?(un=Lt.current)==null||un.resolveWebMcpApproval(pn.id,ut):(In=Lt.current)==null||In.resolveApproval(pn.approval,ut,On))};sn=st.renderApproval({message:L,defaultRenderer:()=>hi(L,r),config:r,approve:ut=>bt("approved",ut),deny:ut=>bt("denied",ut)})}if(Pn&&sn===null){let pt=c.querySelector(`#wrapper-${L.id}`);pt==null||pt.removeAttribute("data-preserve-runtime"),hr.delete(L.id),Ct=hi(L,r)}else{let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-${L.id}`,pt.setAttribute("data-wrapper-id",L.id),pt.setAttribute("data-approval-plugin-stub","true"),pt.setAttribute("data-preserve-runtime","true"),y.appendChild(pt),Ae.push({messageId:L.id,fingerprint:Nt,bubble:sn});return}}else if(zt)if(L.variant==="reasoning"&&L.reasoning&&zt.renderReasoning){if(!qe)return;Ct=zt.renderReasoning({message:L,defaultRenderer:()=>il(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&zt.renderToolCall){if(!we)return;Ct=zt.renderToolCall({message:L,defaultRenderer:()=>ll(L,r),config:r})}else zt.renderMessage&&(Ct=zt.renderMessage({message:L,defaultRenderer:()=>{let st=ia(L,b,Xn,r.messageActions,Z,{loadingIndicatorRenderer:B,widgetConfig:r});return L.role!=="user"&&yl(st,L,r,$),st},config:r}));if(!Ct&&fe){let st=Tl(L);if(st){let xn=Lr.get(L.id),Pn=xn!==Nt,sn=r.wrapComponentDirectiveInBubble!==!1,pt=null;if(Pn){let bt=Al(st,{config:r,message:L,transform:b});if(bt)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-${L.id}`,ut.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let On=document.createElement("div");On.className="persona-mb-3 persona-text-sm persona-leading-relaxed",On.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),ut.appendChild(On)}ut.appendChild(bt),pt=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-${L.id}`,ut.setAttribute("data-message-id",L.id),ut.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let On=document.createElement("div");On.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",On.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),ut.appendChild(On)}ut.appendChild(bt),pt=ut}}if(pt||xn!=null){let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${L.id}`,bt.setAttribute("data-wrapper-id",L.id),bt.setAttribute("data-component-directive-stub","true"),bt.setAttribute("data-preserve-runtime","true"),sn||bt.classList.add("persona-w-full"),y.appendChild(bt),te.push({messageId:L.id,fingerprint:Nt,bubble:pt});return}}}if(!Ct)if(L.variant==="reasoning"&&L.reasoning){if(!qe)return;Ct=il(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!we)return;Ct=ll(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;Ct=hi(L,r)}else{let st=(zr=r.layout)==null?void 0:zr.messages;st!=null&&st.renderUserMessage&&L.role==="user"?Ct=st.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):st!=null&&st.renderAssistantMessage&&L.role==="assistant"?Ct=st.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):Ct=ia(L,b,st,r.messageActions,Z,{loadingIndicatorRenderer:B,widgetConfig:r}),L.role!=="user"&&Ct&&yl(Ct,L,r,$)}let on=document.createElement("div");on.className="persona-flex",on.id=`wrapper-${L.id}`,on.setAttribute("data-wrapper-id",L.id),L.role==="user"&&on.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&on.classList.add("persona-w-full"),on.appendChild(Ct),Lu($r,L.id,Nt,on),y.appendChild(on)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let Ne=He.getAttribute("data-persona-ask-sheet-for");Ne&&!H.has(Ne)&&jo(Be.composerOverlay,Ne)}),(Pe=(dt=r.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let L=[],He=[];g.forEach(Ne=>{if(Ne.variant==="tool"&&Ne.toolCall&&we){He.push(Ne);return}He.length>1&&L.push(He),He=[]}),He.length>1&&L.push(He),L.forEach((Ne,fe)=>{var Qe,It;let Ft=Ne.map(dn=>Array.from(y.children).find(cr=>cr instanceof HTMLElement&&cr.getAttribute("data-wrapper-id")===dn.id)).filter(dn=>!!dn);if(Ft.length<2)return;let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id=`wrapper-tool-group-${fe}-${Ne[0].id}`,Nt.setAttribute("data-wrapper-id",`tool-group-${fe}-${Ne[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Ne.length} tools`,Xn=(It=(Qe=r.toolCall)==null?void 0:Qe.renderGroupedSummary)==null?void 0:It.call(Qe,{messages:Ne,toolCalls:Ne.map(dn=>dn.toolCall).filter(dn=>!!dn),defaultSummary:zt,config:r});O(Ct,Xn)||(Ct.textContent=zt);let on=document.createElement("div");on.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(Ct,on),Nt.appendChild(Jt),Ft[0].before(Nt),Ft.forEach((dn,cr)=>{let Qn=document.createElement("div");Qn.className="persona-tool-group-item persona-relative",Qn.setAttribute("data-persona-tool-group-item","true"),cr<Ft.length-1&&Qn.setAttribute("data-persona-tool-group-connector","true"),Qn.appendChild(dn),on.appendChild(Qn)})})}Pu($r,U);let rt=g.some(L=>L.role==="assistant"&&L.streaming),Ve=g[g.length-1],ct=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(kr&&g.some(L=>L.role==="user")&&!rt&&!ct){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:us},He=s.find(fe=>fe.renderLoadingIndicator),Ne=null;if(He!=null&&He.renderLoadingIndicator&&(Ne=He.renderLoadingIndicator(L)),Ne===null&&((ke=r.loadingIndicator)!=null&&ke.render)&&(Ne=r.loadingIndicator.render(L)),Ne===null&&(Ne=us()),Ne){let fe=document.createElement("div"),Ft=((Ue=r.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;fe.className=Ft?["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(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Ne);let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id="wrapper-typing-indicator",Nt.setAttribute("data-wrapper-id","typing-indicator"),Nt.appendChild(fe),y.appendChild(Nt)}}if(!kr&&g.length>0){let L=g[g.length-1],He={config:r,lastMessage:L,messageCount:g.length},Ne=s.find(Ft=>Ft.renderIdleIndicator),fe=null;if(Ne!=null&&Ne.renderIdleIndicator&&(fe=Ne.renderIdleIndicator(He)),fe===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(fe=r.loadingIndicator.renderIdle(He)),fe){let Ft=document.createElement("div"),Nt=((wt=r.loadingIndicator)==null?void 0:wt.showBubble)!==!1;Ft.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(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(fe);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(Ft),y.appendChild(Jt)}}if(Ka(c,y),ue.length>0)for(let{messageId:L,fingerprint:He,bubble:Ne}of ue){let fe=c.querySelector(`#wrapper-${L}`);fe&&Ne!==null&&(fe.replaceChildren(Ne),fe.setAttribute("data-bubble-fp",He),_r.set(L,He))}if(_r.size>0)for(let L of _r.keys())U.has(L)||_r.delete(L);if(te.length>0)for(let{messageId:L,fingerprint:He,bubble:Ne}of te){let fe=c.querySelector(`#wrapper-${L}`);fe&&Ne!==null&&(fe.replaceChildren(Ne),fe.setAttribute("data-bubble-fp",He),Lr.set(L,He))}if(Lr.size>0)for(let L of Lr.keys())U.has(L)||Lr.delete(L);if(Ae.length>0)for(let{messageId:L,fingerprint:He,bubble:Ne}of Ae){let fe=c.querySelector(`#wrapper-${L}`);fe&&Ne!==null&&(fe.replaceChildren(Ne),fe.setAttribute("data-bubble-fp",He),hr.set(L,He))}if(hr.size>0)for(let L of hr.keys())U.has(L)||hr.delete(L)},no=null,Aa=()=>{var b;if(no)return;let c=y=>{let T=y.composedPath();T.includes(xe)||Ke&&T.includes(Ke)||Dt(!1,"user")};no=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Is=()=>{var g;if(!no)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",no,!0),no=null};ht.push(()=>Is());let ro=null,Sa=()=>{var b;if(ro)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Dt(!1,"user"))};ro=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Ws=()=>{var g;if(!ro)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",ro,!0),ro=null};ht.push(()=>Ws());let oo=!1,Rs=new Set,Ta=()=>{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)},qr=()=>{var ct,dt,Pe,ke;if(!F())return;let c=Be.peekBanner,g=Be.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let b=(ct=$==null?void 0:$.getMessages())!=null?ct:[],y;for(let Ue=b.length-1;Ue>=0;Ue--){let Xe=b[Ue];if(Xe.role==="assistant"&&Xe.content){y=Xe;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let T=y.content,B=!!y.streaming,O=Ta(),U=Ya(O),H=U.type!=="none"?ea(U.type,O==null?void 0:O.plugins):null,ye=((dt=H==null?void 0:H.isAnimating)==null?void 0:dt.call(H,y))===!0,ue=H!==null&&(B||ye);ue&&H&&!Rs.has(H.name)&&(el(H,e),Rs.add(H.name));let te=ue&&(H!=null&&H.containerClass)?H.containerClass:null,Te=(Pe=g.dataset.personaPeekStreamClass)!=null?Pe:null;Te&&Te!==te&&(g.classList.remove(Te),delete g.dataset.personaPeekStreamClass),te&&Te!==te&&(g.classList.add(te),g.dataset.personaPeekStreamClass=te),ue?(g.style.setProperty("--persona-stream-step",`${U.speed}ms`),g.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let $e=ue?Za(T,U.buffer,H,y,B):T;if(ue&&U.placeholder==="skeleton"&&B&&(!$e||!$e.trim())){let Ue=document.createElement("div"),Xe=na();Xe.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(Xe),Ka(g,Ue)}else{let Ue=Math.max(0,$e.length-100),Xe=$e.length>100?$e.slice(-100):$e,wt=os(Xe);if(!ue||!H){let L=$e.length>100?`\u2026${Xe}`:Xe;g.textContent!==L&&(g.textContent=L)}else{let L=wt;(H.wrap==="char"||H.wrap==="word")&&(L=ta(wt,H.wrap,`peek-${y.id}`,{skipTags:H.skipTags,startIndex:Ue}));let He=document.createElement("div");if(He.innerHTML=L,H.useCaret&&Xe.length>0){let Ne=ei(),fe=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=fe[fe.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(Ne,Ft.nextSibling):He.appendChild(Ne)}Ka(g,He),(ke=H.onAfterRender)==null||ke.call(H,{container:g,bubble:c,messageId:y.id,message:y,speed:U.speed,duration:U.duration})}}let Ve=kr||oo;c.classList.toggle("persona-pill-peek--visible",Ve)};if(F()){let c=Be.peekBanner;if(c){let y=T=>{T.preventDefault(),T.stopPropagation(),Dt(!0,"user")};c.addEventListener("pointerdown",y),ht.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{oo||(oo=!0,qr())},b=()=>{oo&&(oo=!1,qr())};ge.addEventListener("pointerenter",g),ge.addEventListener("pointerleave",b),ht.push(()=>{ge.removeEventListener("pointerenter",g),ge.removeEventListener("pointerleave",b)}),Ke&&(Ke.addEventListener("pointerenter",g),Ke.addEventListener("pointerleave",b),ht.push(()=>{Ke.removeEventListener("pointerenter",g),Ke.removeEventListener("pointerleave",b)}))}let Ea=c=>{var Te,$e,Ae,rt,Ve,ct,dt,Pe;let g=($e=(Te=r.launcher)==null?void 0:Te.composerBar)!=null?$e:{},b=(Ae=g.expandedSize)!=null?Ae:"anchored",y=(rt=g.bottomOffset)!=null?rt:"16px",T=g.collapsedMaxWidth,B=(Ve=g.expandedMaxWidth)!=null?Ve:"880px",O=(ct=g.expandedTopOffset)!=null?ct:"5vh",U=(dt=g.modalMaxWidth)!=null?dt:"880px",H=(Pe=g.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",ye="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",te=xe.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Ke){let ke=Ke.style;ke.bottom=y,ke.width=T!=null?T:""}if(c&&b!=="fullscreen"){if(b==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=U,te.maxWidth=ye,te.maxHeight=H,te.height=H;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${y} + ${ue})`,te.top=O,te.width=B,te.maxWidth=ye}},so=()=>{var H,ye,ue,te,Te,$e,Ae,rt;if(!N())return;if(F()){let ct=(ue=((ye=(H=r.launcher)==null?void 0:H.composerBar)!=null?ye:{}).expandedSize)!=null?ue:"anchored",dt=R?"expanded":"collapsed";xe.dataset.state=dt,xe.dataset.expandedSize=ct,Ke&&(Ke.dataset.state=dt,Ke.dataset.expandedSize=ct),xe.style.removeProperty("display"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ea(R),q.style.display=R?"flex":"none",fr(),R?(Aa(),Sa()):(Is(),Ws()),qr();return}let c=hn(r),g=(te=e.ownerDocument.defaultView)!=null?te:window,b=($e=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?$e:640,y=(rt=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?rt:!0,T=g.innerWidth<=b,B=y&&T&&S,O=Cr(r).reveal;R?(xe.style.removeProperty("display"),xe.style.display=c?"flex":"",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0"),ge.classList.add("persona-scale-100","persona-opacity-100"),tn?tn.element.style.display="none":nn&&(nn.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!B?(xe.style.removeProperty("display"),xe.style.display="flex",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.setProperty("display","none","important"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.display="",xe.classList.add("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100"),ge.classList.add("persona-scale-95","persona-opacity-0")),tn?tn.element.style.display=c?"none":"":nn&&(nn.style.display=c?"none":""))},Dt=(c,g="user")=>{var B,O;if(!N()||R===c)return;let b=R;R=c,so();let y=(()=>{var Ae,rt,Ve,ct,dt,Pe,ke,Ue,Xe,wt;let U=(rt=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?rt:!1,H=(Ve=e.ownerDocument.defaultView)!=null?Ve:window,ye=(dt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?dt:!0,ue=(ke=(Pe=r.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?ke:640,te=H.innerWidth<=ue,Te=hn(r)&&ye&&te,$e=F()&&((wt=(Xe=(Ue=r.launcher)==null?void 0:Ue.composerBar)==null?void 0:Xe.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return U||ye&&te&&S||Te||$e})();if(R&&y){if(!Zt){let U=e.getRootNode(),H=U instanceof ShadowRoot?U.host:e.closest(".persona-host");H&&(Zt=tl(H,(O=(B=r.launcher)==null?void 0:B.zIndex)!=null?O:En))}en||(en=nl(e.ownerDocument))}else R||(Zt==null||Zt(),Zt=null,en==null||en(),en=null);R&&(Ds(),gt()==="follow"?Wr(!0):Ls());let T={open:R,source:g,timestamp:Date.now()};R&&!b?o.emit("widget:opened",T):!R&&b&&o.emit("widget:closed",T),o.emit("widget:state",{open:R,launcherEnabled:S,voiceActive:yt.active,streaming:$.isStreaming()})},Qo=c=>{Qt(c?"stop":"send"),V&&(V.disabled=c),or.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)})},Yo=()=>{yt.active||ee&&ee.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Yo(),200)});let Hs=()=>{var b,y,T,B,O,U,H,ye,ue,te,Te;er.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"Hello \u{1F44B}",Sr.textContent=(B=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",ee.placeholder=(U=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?U:"How can I help...";let c=pe.querySelector("[data-persona-intro-card]");if(c){let $e=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;c.style.display=$e?"":"none",$e?(pe.classList.remove("persona-gap-3"),pe.classList.add("persona-gap-6")):(pe.classList.remove("persona-gap-6"),pe.classList.add("persona-gap-3"))}!((ue=(ye=r.sendButton)==null?void 0:ye.useIcon)!=null&&ue)&&!($!=null&&$.isStreaming())&&(ze.textContent=(Te=(te=r.copy)==null?void 0:te.sendButtonLabel)!=null?Te:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.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 ir=null,Ge=()=>{ir==null&&(ir=setInterval(()=>{let c=nt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(ir),ir=null;return}let g=Date.now();c.forEach(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=Ha(g-y))})},100))};if($=new Js(r,{onMessagesChanged(c){var y;Mo(nt,c,Ee),Ge(),$&&(c.some(B=>B.role==="user")?or.render([],$,ee,c):or.render(r.suggestionChips,$,ee,c,r.suggestionChipsConfig)),Wr(!kr),Ca(c);let g=[...c].reverse().find(T=>T.role==="user");c.length===0&&Eo(),!zo||To?(zo=!0,Vo=(y=g==null?void 0:g.id)!=null?y:null):g&&g.id!==Vo&&(Vo=g.id,wa(g.id));let b=yt.lastUserMessageId;g&&g.id!==b&&(yt.lastUserMessageId=g.id,o.emit("user:message",g)),yt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Go(c),qr()},onStatusChanged(c){var y;let g=(y=r.statusIndicator)!=null?y:{};Ye(an,(T=>{var B,O,U,H;return T==="idle"?(B=g.idleText)!=null?B:Tn.idle:T==="connecting"?(O=g.connectingText)!=null?O:Tn.connecting:T==="connected"?(U=g.connectedText)!=null?U:Tn.connected:T==="error"?(H=g.errorText)!=null?H:Tn.error:Tn[T]})(c),g,c)},onStreamingChanged(c){kr=c,Qo(c),$&&Mo(nt,$.getMessages(),Ee),c||Wr(!0),qr()},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":ao(),gg();break;case"speaking":ao(),fg();break;default:c==="idle"&&$.isBargeInActive()?(ao(),Bs(),V==null||V.setAttribute("aria-label","End voice session")):(yt.active=!1,ao(),ar("system"),Dn());break}},onArtifactsState(c){Un=c,Vn(),Go()}}),Lt.current=$,zo=!0,((jc=(_c=r.voiceRecognition)==null?void 0:_c.provider)==null?void 0:jc.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)}),(ie||r.onSSEEvent)&&$.setSSEEventCallback((c,g)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,g),me==null||me.processEvent(c,g),ie==null||ie.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;if(c){if(c.metadata&&(d=kl(c.metadata),w.syncFromMetadata()),(g=c.messages)!=null&&g.length){To=!0;try{$.hydrateMessages(c.messages)}finally{To=!1}}(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 C=()=>{var g,b,y;!F()||R||!((y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||Dt(!0,"auto")},_=c=>{var T;if(c.preventDefault(),$.isStreaming()){$.cancel(),me==null||me.reset(),z==null||z.update();return}let g=ee.value.trim(),b=(T=At==null?void 0:At.hasAttachments())!=null?T:!1;if(!g&&!b)return;C();let y;b&&(y=[],y.push(...At.getContentParts()),g&&y.push($a(g))),ee.value="",ee.style.height="auto",J(),$.sendMessage(g,{contentParts:y}),b&&At.clearAttachments()},k=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Q={...Ja},re=!1,J=()=>{Q={...Ja}},Le=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),Oe=c=>{if(!ee)return;re=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),re=!1;let g=ee.value.length;ee.setSelectionRange(g,g)},it=()=>{re||J()},et=c=>{if(ee){if(k()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ee.selectionStart===0&&ee.selectionEnd===0,b=Tu({direction:c.key==="ArrowUp"?"up":"down",history:Le(),currentValue:ee.value,atStart:g,state:Q});if(Q=b.state,b.handled){c.preventDefault(),b.value!==void 0&&Oe(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}J(),c.preventDefault(),ze.click()}}},Rt=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(q)&&($.cancel(),me==null||me.reset(),z==null||z.update(),J(),c.preventDefault(),c.stopImmediatePropagation())},_t=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!At)return;let g=hx(c.clipboardData);g.length!==0&&(c.preventDefault(),await At.handleFiles(g))},Ot=null,lt=!1,Tt=null,je=null,An=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,mn=(c="user")=>{var B,O,U,H,ye,ue,te;if(lt||$.isStreaming())return;let g=An();if(!g)return;Ot=new g;let y=(O=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?O:2e3;Ot.continuous=!0,Ot.interimResults=!0,Ot.lang="en-US";let T=ee.value;Ot.onresult=Te=>{let $e="",Ae="";for(let Ve=0;Ve<Te.results.length;Ve++){let ct=Te.results[Ve],dt=ct[0].transcript;ct.isFinal?$e+=dt+" ":Ae=dt}let rt=T+$e+Ae;ee.value=rt,Tt&&clearTimeout(Tt),($e||Ae)&&(Tt=window.setTimeout(()=>{let Ve=ee.value.trim();Ve&&Ot&<&&(jt(),ee.value="",ee.style.height="auto",$.sendMessage(Ve,{viaVoice:!0}))},y))},Ot.onerror=Te=>{Te.error!=="no-speech"&&jt()},Ot.onend=()=>{if(lt){let Te=ee.value.trim();Te&&Te!==T.trim()&&(ee.value="",ee.style.height="auto",$.sendMessage(Te,{viaVoice:!0})),jt()}};try{if(Ot.start(),lt=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),ar(c),Dn(),V){let Te=(U=r.voiceRecognition)!=null?U:{};je={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(H=Te.iconName)!=null?H:"mic",iconSize:parseFloat((te=(ue=Te.iconSize)!=null?ue:(ye=r.sendButton)==null?void 0:ye.size)!=null?te:"40")||24};let $e=Te.recordingBackgroundColor,Ae=Te.recordingIconColor,rt=Te.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=$e!=null?$e:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let Ve=V.querySelector("svg");Ve&&Ve.setAttribute("stroke",Ae)}rt&&(V.style.borderColor=rt),V.setAttribute("aria-label","Stop voice recognition")}}catch{jt("system")}},jt=(c="user")=>{if(lt){if(lt=!1,Tt&&(clearTimeout(Tt),Tt=null),Ot){try{Ot.stop()}catch{}Ot=null}if(yt.active=!1,ar(c),Dn(),V){if(V.classList.remove("persona-voice-recording"),je){V.style.backgroundColor=je.backgroundColor,V.style.color=je.color,V.style.borderColor=je.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",je.color||"currentColor"),je=null}V.setAttribute("aria-label","Start voice recognition")}}},xr=(c,g)=>{var ct,dt,Pe,ke,Ue,Xe,wt,L;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((ct=c==null?void 0:c.provider)==null?void 0:ct.type)==="runtype";if(!(b||y))return null;let B=h("div","persona-send-button-wrapper"),O=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let U=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",H=(Pe=g==null?void 0:g.size)!=null?Pe:"40px",ye=(ke=c==null?void 0:c.iconSize)!=null?ke:H,ue=parseFloat(ye)||24,te=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:g==null?void 0:g.backgroundColor,Te=(Xe=c==null?void 0:c.iconColor)!=null?Xe:g==null?void 0:g.textColor;O.style.width=ye,O.style.height=ye,O.style.minWidth=ye,O.style.minHeight=ye,O.style.fontSize="18px",O.style.lineHeight="1",Te?O.style.color=Te:O.style.color="var(--persona-text, #111827)";let Ae=Se(U,ue,Te||"currentColor",1.5);Ae?O.appendChild(Ae):O.textContent="\u{1F3A4}",te?O.style.backgroundColor=te:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),B.appendChild(O);let rt=(wt=c==null?void 0:c.tooltipText)!=null?wt:"Start voice recognition";if(((L=c==null?void 0:c.showTooltip)!=null?L:!1)&&rt){let He=h("div","persona-send-button-tooltip");He.textContent=rt,B.appendChild(He)}return{micButton:O,micButtonWrapper:B}},Ri=()=>{var g,b,y,T,B;if(!V||je)return;let c=(g=r.voiceRecognition)!=null?g:{};je={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((B=(T=c.iconSize)!=null?T:(y=r.sendButton)==null?void 0:y.size)!=null?B:"40")||24}},Hi=(c,g)=>{var B,O,U,H,ye;if(!V)return;let b=V.querySelector("svg");b&&b.remove();let y=(ye=je==null?void 0:je.iconSize)!=null?ye:parseFloat((H=(U=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?U:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,T=Se(c,y,g,1.5);T&&V.appendChild(T)},Ma=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Bs=()=>{var T;if(!V)return;Ri();let c=(T=r.voiceRecognition)!=null?T:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,y=c.recordingBorderColor;if(Ma(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let B=V.querySelector("svg");B&&B.setAttribute("stroke",b)}y&&(V.style.borderColor=y),V.setAttribute("aria-label","Stop voice recognition")},gg=()=>{var U,H,ye,ue,te,Te,$e,Ae;if(!V)return;Ri();let c=(U=r.voiceRecognition)!=null?U:{},g=$.getVoiceInterruptionMode(),b=(H=c.processingIconName)!=null?H:"loader",y=(ue=(ye=c.processingIconColor)!=null?ye:je==null?void 0:je.color)!=null?ue:"",T=(Te=(te=c.processingBackgroundColor)!=null?te:je==null?void 0:je.backgroundColor)!=null?Te:"",B=(Ae=($e=c.processingBorderColor)!=null?$e:je==null?void 0:je.borderColor)!=null?Ae:"";Ma(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=T,V.style.borderColor=B;let O=y||"currentColor";V.style.color=O,Hi(b,O),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},fg=()=>{var ye,ue,te,Te,$e,Ae,rt,Ve,ct,dt,Pe,ke;if(!V)return;Ri();let c=(ye=r.voiceRecognition)!=null?ye:{},g=$.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:b,T=(Ae=c.speakingIconColor)!=null?Ae:g==="barge-in"?(Te=(te=c.recordingIconColor)!=null?te:je==null?void 0:je.color)!=null?Te:"":($e=je==null?void 0:je.color)!=null?$e:"",B=(ct=c.speakingBackgroundColor)!=null?ct:g==="barge-in"?(rt=c.recordingBackgroundColor)!=null?rt:"var(--persona-voice-recording-bg, #ef4444)":(Ve=je==null?void 0:je.backgroundColor)!=null?Ve:"",O=(ke=c.speakingBorderColor)!=null?ke:g==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=je==null?void 0:je.borderColor)!=null?Pe:"";Ma(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=B,V.style.borderColor=O;let U=T||"currentColor";V.style.color=U,Hi(y,U);let H=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",H),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},ao=()=>{var c,g,b;V&&(Ma(),je&&(V.style.backgroundColor=(c=je.backgroundColor)!=null?c:"",V.style.color=(g=je.color)!=null?g:"",V.style.borderColor=(b=je.borderColor)!=null?b:"",Hi(je.iconName,je.color||"currentColor"),je=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},ka=()=>{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(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Dn(),ar("user"),ao()});return}$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),yt.manuallyDeactivated=!$.isVoiceActive(),Dn(),ar("user"),$.isVoiceActive()?Bs():ao()});return}if(lt){let b=ee.value.trim();yt.manuallyDeactivated=!0,Dn(),jt("user"),b&&(ee.value="",ee.style.height="auto",$.sendMessage(b))}else yt.manuallyDeactivated=!1,Dn(),mn("user")};$n=ka,V&&(V.addEventListener("click",ka),ht.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),ao()):jt("system"),V&&V.removeEventListener("click",ka)}));let hg=o.on("assistant:complete",()=>{Cs&&(yt.active||yt.manuallyDeactivated||Cs==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!yt.active&&!yt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),ar("auto"),$.isVoiceActive()&&Bs()}):mn("auto"))},600))});ht.push(hg);let bg=o.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});ht.push(bg);let Zo=()=>{Dt(!R,"user")},tn=null,nn=null;if(S&&!F()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>oa(r,Zo).element,onToggle:Zo});g&&(nn=g)}nn||(tn=oa(r,Zo))}tn?e.appendChild(tn.element):nn&&e.appendChild(nn),so(),or.render(r.suggestionChips,$,ee,void 0,r.suggestionChipsConfig),Hs(),Qo($.isStreaming()),gt()==="follow"?Wr(!0):Ls(),ha(),E&&(!S||F()?setTimeout(()=>Yo(),0):R&&setTimeout(()=>Yo(),200));let Ds=()=>{var H,ye,ue,te,Te,$e,Ae,rt,Ve,ct,dt,Pe,ke,Ue,Xe,wt,L,He,Ne,fe,Ft,Nt;if(F()){bn(),so();return}let c=hn(r),g=(ye=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?ye:!1,b=c||g||((te=(ue=r.launcher)==null?void 0:ue.fullHeight)!=null?te:!1),y=(Te=e.ownerDocument.defaultView)!=null?Te:window,T=(Ae=($e=r.launcher)==null?void 0:$e.mobileFullscreen)!=null?Ae:!0,B=(Ve=(rt=r.launcher)==null?void 0:rt.mobileBreakpoint)!=null?Ve:640,O=y.innerWidth<=B,U=T&&O&&S;try{if(U){fr(),Oo(e,r);return}if(M&&(M=!1,fr(),Oo(e,r)),!S&&!c){ge.style.height="",ge.style.width="";return}if(!g&&!c){let Jt=(dt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?dt:r==null?void 0:r.launcherWidth,Ct=Jt!=null?Jt:pr;ge.style.width=Ct,ge.style.maxWidth=Ct}if(Mr(),!b){let Jt=y.innerHeight,Ct=64,zt=(ke=(Pe=r.launcher)==null?void 0:Pe.heightOffset)!=null?ke:0,Xn=Math.max(200,Jt-Ct),on=Math.min(640,Xn),Qe=Math.max(200,on-zt);ge.style.height=`${Qe}px`}}finally{if(bn(),so(),R&&S){let Ct=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((wt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?wt:640),zt=(He=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?He:!1,Xn=(fe=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?fe:!0,on=hn(r)&&Xn&&Ct,Qe=zt||Xn&&Ct&&S||on;if(Qe&&!en){let It=e.getRootNode(),dn=It instanceof ShadowRoot?It.host:e.closest(".persona-host");dn&&!Zt&&(Zt=tl(dn,(Nt=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Nt:En)),en=nl(e.ownerDocument)}else Qe||(Zt==null||Zt(),Zt=null,en==null||en(),en=null)}}};Ds();let $l=(Uc=e.ownerDocument.defaultView)!=null?Uc:window;if($l.addEventListener("resize",Ds),ht.push(()=>$l.removeEventListener("resize",Ds)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bn()});c.observe(_e),ht.push(()=>c.disconnect())}Gn=pe.scrollTop;let _l=Kr(pe),yg=()=>{let c=pe.getRootNode(),g=typeof c.getSelection=="function"?c.getSelection():null;return g!=null?g:pe.ownerDocument.getSelection()},Bi=()=>Iu(yg(),pe),jl=()=>{let c=pe.scrollTop,g=Kr(pe),b=g<_l;if(_l=g,gt()!=="follow"){Gn=c,Nn();return}let{action:y,nextLastScrollTop:T}=Xa({following:Jn.isFollowing(),currentScrollTop:c,lastScrollTop:Gn,nearBottom:Fo(pe,Ko),userScrollThreshold:ga,isAutoScrolling:yr||So||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Gn=T,y==="resume"){Bi()||Ir();return}y==="pause"&&Xo()};if(pe.addEventListener("scroll",jl,{passive:!0}),ht.push(()=>pe.removeEventListener("scroll",jl)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{va()});c.observe(nt),c.observe(pe),ht.push(()=>c.disconnect())}let Ul=()=>{gt()==="follow"&&Jn.isFollowing()&&Bi()&&Xo()},ql=pe.ownerDocument;ql.addEventListener("selectionchange",Ul),ht.push(()=>{ql.removeEventListener("selectionchange",Ul)});let zl=c=>{if(gt()!=="follow")return;let g=Qa({following:Jn.isFollowing(),deltaY:c.deltaY,nearBottom:Fo(pe,Ko),resumeWhenNearBottom:!0});g==="pause"?Xo():g==="resume"&&!Bi()&&Ir()};pe.addEventListener("wheel",zl,{passive:!0}),ht.push(()=>pe.removeEventListener("wheel",zl)),Ze.addEventListener("click",()=>{Eo(),pe.scrollTop=pe.scrollHeight,Gn=pe.scrollTop,Ir(),Wr(!0),Nn()}),ht.push(()=>Ze.remove()),ht.push(()=>{Ss(),Eo()});let Vl=()=>{W&&(sr&&(W.removeEventListener("click",sr),sr=null),N()?(W.style.display="",sr=()=>{Dt(!1,"user")},W.addEventListener("click",sr)):W.style.display="none")};Vl(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{$.clearMessages(),$r.clear(),Ir(),jo(Be.composerOverlay);try{localStorage.removeItem(xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xs}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==xs)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(),ie==null||ie.clear(),me==null||me.reset(),z==null||z.update()})})(),Ht&&Ht.addEventListener("submit",_),ee==null||ee.addEventListener("keydown",et),ee==null||ee.addEventListener("input",it),ee==null||ee.addEventListener("paste",_t);let Kl=(qc=e.ownerDocument)!=null?qc:document;Kl.addEventListener("keydown",Rt,!0);let Jl="persona-attachment-drop-active",Ns=0,Di=()=>{Ns=0,q.classList.remove(Jl)},es=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&At!==null},Gl=c=>{!Ai(c.dataTransfer)||!es()||(Ns++,Ns===1&&q.classList.add(Jl))},Xl=c=>{!Ai(c.dataTransfer)||!es()||(Ns--,Ns<=0&&Di())},Ql=c=>{!Ai(c.dataTransfer)||!es()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Yl=c=>{var b;if(!Ai(c.dataTransfer)||!es())return;c.preventDefault(),c.stopPropagation(),Di();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&At.handleFiles(g)},io=!0;q.addEventListener("dragenter",Gl,io),q.addEventListener("dragleave",Xl,io),e.addEventListener("dragover",Ql,io),e.addEventListener("drop",Yl,io);let La=e.ownerDocument,Zl=c=>{es()&&c.preventDefault()},ec=c=>{es()&&c.preventDefault()};La.addEventListener("dragover",Zl),La.addEventListener("drop",ec),ht.push(()=>{Ht&&Ht.removeEventListener("submit",_),ee==null||ee.removeEventListener("keydown",et),ee==null||ee.removeEventListener("input",it),ee==null||ee.removeEventListener("paste",_t),Kl.removeEventListener("keydown",Rt,!0)}),ht.push(()=>{q.removeEventListener("dragenter",Gl,io),q.removeEventListener("dragleave",Xl,io),e.removeEventListener("dragover",Ql,io),e.removeEventListener("drop",Yl,io),La.removeEventListener("dragover",Zl),La.removeEventListener("drop",ec),Di()}),ht.push(()=>{$.cancel()}),tn?ht.push(()=>{tn==null||tn.destroy()}):nn&&ht.push(()=>{nn==null||nn.remove()});let cn={update(c){var Rr,un,In,dr,Io,Wo,Pa,Os,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,Ep,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Op,Fp,$p,_p,jp,Up,qp,zp,Vp,Kp,Jp,Gp;let g=r.toolCall,b=r.messageActions,y=(Rr=r.layout)==null?void 0:Rr.messages,T=r.colorScheme,B=r.loadingIndicator,O=r.iterationDisplay,U=(un=r.features)==null?void 0:un.showReasoning,H=(In=r.features)==null?void 0:In.showToolCalls,ye=(dr=r.features)==null?void 0:dr.toolCallDisplay,ue=(Io=r.features)==null?void 0:Io.reasoningDisplay;r={...r,...c},fr(),Oo(e,r),yi(e,r),xi(e,r),Vn(),r.colorScheme!==T&&eo();let te=vi.getForInstance(r.plugins);s.length=0,s.push(...te),S=(Pa=(Wo=r.launcher)==null?void 0:Wo.enabled)!=null?Pa:!0,D=(Qc=(Os=r.launcher)==null?void 0:Os.autoExpand)!=null?Qc:!1,qe=(Zc=(Yc=r.features)==null?void 0:Yc.showReasoning)!=null?Zc:!0,we=(td=(ed=r.features)==null?void 0:ed.showToolCalls)!=null?td:!0,he=(rd=(nd=r.features)==null?void 0:nd.scrollToBottom)!=null?rd:{};let Te=gt();Me=(sd=(od=r.features)==null?void 0:od.scrollBehavior)!=null?sd:{},Te!==gt()&&(Eo(),Ir()),Tr(),Nn();let $e=Ie;if(Ie=(id=(ad=r.features)==null?void 0:ad.showEventStreamToggle)!=null?id:!1,Ie&&!$e){if(ie||(X=new pa(ce),ie=new da(ne,X),me=me!=null?me:new ua,X.open().then(()=>ie==null?void 0:ie.restore()).catch(()=>{}),$.setSSEEventCallback((G,Et)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,G,Et),me==null||me.processEvent(G,Et),ie.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:G,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!vt&&Fe){let G=(cd=(ld=r.features)==null?void 0:ld.eventStream)==null?void 0:cd.classNames,Et="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:"");vt=h("button",Et),vt.style.width="28px",vt.style.height="28px",vt.style.color=Rn.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let Ut=Se("activity","18px","currentColor",1.5);Ut&&vt.appendChild(Ut);let mt=Be.clearChatButtonWrapper,Wt=Be.closeButtonWrapper,gn=mt||Wt;gn&&gn.parentNode===Fe?Fe.insertBefore(vt,gn):Fe.appendChild(vt),vt.addEventListener("click",()=>{oe?gr():Dr()})}}else!Ie&&$e&&(gr(),vt&&(vt.remove(),vt=null),ie==null||ie.clear(),X==null||X.destroy(),ie=null,X=null,me==null||me.reset(),me=null);if(((dd=r.launcher)==null?void 0:dd.enabled)===!1&&tn&&(tn.destroy(),tn=null),((pd=r.launcher)==null?void 0:pd.enabled)===!1&&nn&&(nn.remove(),nn=null),((ud=r.launcher)==null?void 0:ud.enabled)!==!1&&!tn&&!nn){let G=s.find(Et=>Et.renderLauncher);if(G!=null&&G.renderLauncher){let Et=G.renderLauncher({config:r,defaultRenderer:()=>oa(r,Zo).element,onToggle:Zo});Et&&(nn=Et,e.appendChild(nn))}nn||(tn=oa(r,Zo),e.appendChild(tn.element))}tn&&tn.update(r),De&&((md=r.launcher)==null?void 0:md.title)!==void 0&&(De.textContent=r.launcher.title),Je&&((gd=r.launcher)==null?void 0:gd.subtitle)!==void 0&&(Je.textContent=r.launcher.subtitle);let Ae=(fd=r.layout)==null?void 0:fd.header;if((Ae==null?void 0:Ae.layout)!==A&&Fe){let G=Ae?sa(r,Ae,{showClose:N(),onClose:()=>Dt(!1,"user")}):fo({config:r,showClose:N(),onClose:()=>Dt(!1,"user")});Fe.replaceWith(G.header),Fe=G.header,de=G.iconHolder,De=G.headerTitle,Je=G.headerSubtitle,W=G.closeButton,A=Ae==null?void 0:Ae.layout}else if(Ae&&(de&&(de.style.display=Ae.showIcon===!1?"none":""),De&&(De.style.display=Ae.showTitle===!1?"none":""),Je&&(Je.style.display=Ae.showSubtitle===!1?"none":""),W&&(W.style.display=Ae.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let G=Ae.showClearChat;if(G!==void 0){Be.clearChatButtonWrapper.style.display=G?"":"none";let{closeButtonWrapper:Et}=Be;Et&&!Et.classList.contains("persona-absolute")&&(G?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let Ve=((hd=r.layout)==null?void 0:hd.showHeader)!==!1;Fe&&(Fe.style.display=Ve?"":"none");let ct=((bd=r.layout)==null?void 0:bd.showFooter)!==!1;_e&&(_e.style.display=ct?"":"none"),bn(),Nn(),S!==I?S?Dt(D,"auto"):(R=!0,so()):D!==P&&Dt(D,"auto"),P=D,I=S,Ds(),Vl();let ke=JSON.stringify(c.toolCall)!==JSON.stringify(g),Ue=JSON.stringify(r.messageActions)!==JSON.stringify(b),Xe=JSON.stringify((yd=r.layout)==null?void 0:yd.messages)!==JSON.stringify(y),wt=((xd=r.loadingIndicator)==null?void 0:xd.render)!==(B==null?void 0:B.render)||((vd=r.loadingIndicator)==null?void 0:vd.renderIdle)!==(B==null?void 0:B.renderIdle)||((wd=r.loadingIndicator)==null?void 0:wd.showBubble)!==(B==null?void 0:B.showBubble),L=r.iterationDisplay!==O,He=((Ad=(Cd=r.features)==null?void 0:Cd.showReasoning)!=null?Ad:!0)!==(U!=null?U:!0)||((Td=(Sd=r.features)==null?void 0:Sd.showToolCalls)!=null?Td:!0)!==(H!=null?H:!0)||JSON.stringify((Ed=r.features)==null?void 0:Ed.toolCallDisplay)!==JSON.stringify(ye)||JSON.stringify((Md=r.features)==null?void 0:Md.reasoningDisplay)!==JSON.stringify(ue);(ke||Ue||Xe||wt||L||He)&&$&&(ws++,Mo(nt,$.getMessages(),Ee));let fe=(kd=r.launcher)!=null?kd:{},Ft=(Ld=fe.headerIconHidden)!=null?Ld:!1,Nt=(Id=(Pd=r.layout)==null?void 0:Pd.header)==null?void 0:Id.showIcon,Jt=Ft||Nt===!1,Ct=fe.headerIconName,zt=(Wd=fe.headerIconSize)!=null?Wd:"48px";if(de){let G=q.querySelector(".persona-border-b-persona-divider"),Et=G==null?void 0:G.querySelector(".persona-flex-col");if(Jt)de.style.display="none",G&&Et&&!G.contains(Et)&&G.insertBefore(Et,G.firstChild);else{if(de.style.display="",de.style.height=zt,de.style.width=zt,G&&Et&&(G.contains(de)?de.nextSibling!==Et&&(de.remove(),G.insertBefore(de,Et)):G.insertBefore(de,Et)),Ct){let mt=parseFloat(zt)||24,Wt=Se(Ct,mt*.6,"#ffffff",2);Wt?de.replaceChildren(Wt):de.textContent=(Rd=fe.agentIconText)!=null?Rd:"\u{1F4AC}"}else if(fe.iconUrl){let mt=de.querySelector("img");if(mt)mt.src=fe.iconUrl,mt.style.height=zt,mt.style.width=zt;else{let Wt=document.createElement("img");Wt.src=fe.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=zt,Wt.style.width=zt,de.replaceChildren(Wt)}}else{let mt=de.querySelector("svg"),Wt=de.querySelector("img");(mt||Wt)&&de.replaceChildren(),de.textContent=(Hd=fe.agentIconText)!=null?Hd:"\u{1F4AC}"}let Ut=de.querySelector("img");Ut&&(Ut.style.height=zt,Ut.style.width=zt)}}let Xn=(Dd=(Bd=r.layout)==null?void 0:Bd.header)==null?void 0:Dd.showTitle,on=(Od=(Nd=r.layout)==null?void 0:Nd.header)==null?void 0:Od.showSubtitle;if(De&&(De.style.display=Xn===!1?"none":""),Je&&(Je.style.display=on===!1?"none":""),W){(($d=(Fd=r.layout)==null?void 0:Fd.header)==null?void 0:$d.showCloseButton)===!1?W.style.display="none":W.style.display="";let Et=(_d=fe.closeButtonSize)!=null?_d:"32px",Ut=(jd=fe.closeButtonPlacement)!=null?jd:"inline";W.style.height=Et,W.style.width=Et;let{closeButtonWrapper:mt}=Be,Wt=Ut==="top-right",gn=mt==null?void 0:mt.classList.contains("persona-absolute");if(mt&&Wt!==gn)if(mt.remove(),Wt)mt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",q.style.position="relative",q.appendChild(mt);else{let ft=(qd=(Ud=fe.clearChat)==null?void 0:Ud.placement)!=null?qd:"inline",fn=(Vd=(zd=fe.clearChat)==null?void 0:zd.enabled)!=null?Vd:!0;mt.className=fn&&ft==="inline"?"":"persona-ml-auto";let Fn=q.querySelector(".persona-border-b-persona-divider");Fn&&Fn.appendChild(mt)}if(W.style.color=fe.closeButtonColor||Rn.actionIconColor,fe.closeButtonBackgroundColor?(W.style.backgroundColor=fe.closeButtonBackgroundColor,W.classList.remove("hover:persona-bg-gray-100")):(W.style.backgroundColor="",W.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let ft=fe.closeButtonBorderWidth||"0px",fn=fe.closeButtonBorderColor||"transparent";W.style.border=`${ft} solid ${fn}`,W.classList.remove("persona-border-none")}else W.style.border="",W.classList.add("persona-border-none");fe.closeButtonBorderRadius?(W.style.borderRadius=fe.closeButtonBorderRadius,W.classList.remove("persona-rounded-full")):(W.style.borderRadius="",W.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(W.style.paddingLeft=fe.closeButtonPaddingX,W.style.paddingRight=fe.closeButtonPaddingX):(W.style.paddingLeft="",W.style.paddingRight=""),fe.closeButtonPaddingY?(W.style.paddingTop=fe.closeButtonPaddingY,W.style.paddingBottom=fe.closeButtonPaddingY):(W.style.paddingTop="",W.style.paddingBottom="");let Sn=(Kd=fe.closeButtonIconName)!=null?Kd:"x",vr=(Jd=fe.closeButtonIconText)!=null?Jd:"\xD7";W.innerHTML="";let Wn=Se(Sn,"28px","currentColor",1);Wn?W.appendChild(Wn):W.textContent=vr;let rn=(Gd=fe.closeButtonTooltipText)!=null?Gd:"Close chat",Yn=(Xd=fe.closeButtonShowTooltip)!=null?Xd:!0;if(W.setAttribute("aria-label",rn),mt&&(mt._cleanupTooltip&&(mt._cleanupTooltip(),delete mt._cleanupTooltip),Yn&&rn)){let ft=null,fn=()=>{if(ft||!W)return;let Ro=W.ownerDocument,Fs=Ro.body;if(!Fs)return;ft=Hr(Ro,"div","persona-clear-chat-tooltip"),ft.textContent=rn;let $s=Hr(Ro,"div");$s.className="persona-clear-chat-tooltip-arrow",ft.appendChild($s);let Ho=W.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(uo),ft.style.left=`${Ho.left+Ho.width/2}px`,ft.style.top=`${Ho.top-8}px`,ft.style.transform="translate(-50%, -100%)",Fs.appendChild(ft)},Fn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};mt.addEventListener("mouseenter",fn),mt.addEventListener("mouseleave",Fn),W.addEventListener("focus",fn),W.addEventListener("blur",Fn),mt._cleanupTooltip=()=>{Fn(),mt&&(mt.removeEventListener("mouseenter",fn),mt.removeEventListener("mouseleave",Fn)),W&&(W.removeEventListener("focus",fn),W.removeEventListener("blur",Fn))}}}let{clearChatButton:Qe,clearChatButtonWrapper:It}=Be;if(Qe){let G=(Qd=fe.clearChat)!=null?Qd:{},Et=(Yd=G.enabled)!=null?Yd:!0,Ut=(ep=(Zd=r.layout)==null?void 0:Zd.header)==null?void 0:ep.showClearChat,mt=Ut!==void 0?Ut:Et,Wt=(tp=G.placement)!=null?tp:"inline";if(It){It.style.display=mt?"":"none";let{closeButtonWrapper:gn}=Be;!F()&&gn&&!gn.classList.contains("persona-absolute")&&(mt?gn.classList.remove("persona-ml-auto"):gn.classList.add("persona-ml-auto"));let Sn=Wt==="top-right",vr=It.classList.contains("persona-absolute");if(!F()&&Sn!==vr&&mt){if(It.remove(),Sn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",q.style.position="relative",q.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let rn=q.querySelector(".persona-border-b-persona-divider"),Yn=Be.closeButtonWrapper;rn&&Yn&&Yn.parentElement===rn?rn.insertBefore(It,Yn):rn&&rn.appendChild(It)}let Wn=Be.closeButtonWrapper;Wn&&!Wn.classList.contains("persona-absolute")&&(Sn?Wn.classList.add("persona-ml-auto"):Wn.classList.remove("persona-ml-auto"))}}if(mt){if(!F()){let ft=(np=G.size)!=null?np:"32px";Qe.style.height=ft,Qe.style.width=ft}let gn=(rp=G.iconName)!=null?rp:"refresh-cw",Sn=(op=G.iconColor)!=null?op:"";Qe.style.color=Sn||Rn.actionIconColor,Qe.innerHTML="";let vr=F()?"14px":"20px",Wn=Se(gn,vr,"currentColor",2);if(Wn&&Qe.appendChild(Wn),G.backgroundColor?(Qe.style.backgroundColor=G.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),G.borderWidth||G.borderColor){let ft=G.borderWidth||"0px",fn=G.borderColor||"transparent";Qe.style.border=`${ft} solid ${fn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");G.borderRadius?(Qe.style.borderRadius=G.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),G.paddingX?(Qe.style.paddingLeft=G.paddingX,Qe.style.paddingRight=G.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),G.paddingY?(Qe.style.paddingTop=G.paddingY,Qe.style.paddingBottom=G.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let rn=(sp=G.tooltipText)!=null?sp:"Clear chat",Yn=(ap=G.showTooltip)!=null?ap:!0;if(Qe.setAttribute("aria-label",rn),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),Yn&&rn)){let ft=null,fn=()=>{if(ft||!Qe)return;let Ro=Qe.ownerDocument,Fs=Ro.body;if(!Fs)return;ft=Hr(Ro,"div","persona-clear-chat-tooltip"),ft.textContent=rn;let $s=Hr(Ro,"div");$s.className="persona-clear-chat-tooltip-arrow",ft.appendChild($s);let Ho=Qe.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(uo),ft.style.left=`${Ho.left+Ho.width/2}px`,ft.style.top=`${Ho.top-8}px`,ft.style.transform="translate(-50%, -100%)",Fs.appendChild(ft)},Fn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};It.addEventListener("mouseenter",fn),It.addEventListener("mouseleave",Fn),Qe.addEventListener("focus",fn),Qe.addEventListener("blur",Fn),It._cleanupTooltip=()=>{Fn(),It&&(It.removeEventListener("mouseenter",fn),It.removeEventListener("mouseleave",Fn)),Qe&&(Qe.removeEventListener("focus",fn),Qe.removeEventListener("blur",Fn))}}}}let dn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[wi],cr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ys.message,ys.messageAndClick];w=Ci({parsers:dn,handlers:cr,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Ee=Im(r,w,le),$.updateConfig(r),Mo(nt,$.getMessages(),Ee),or.render(r.suggestionChips,$,ee,void 0,r.suggestionChipsConfig),Hs(),Qo($.isStreaming());let Qn=((ip=r.voiceRecognition)==null?void 0:ip.enabled)===!0,ko=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Lo=((cp=(lp=r.voiceRecognition)==null?void 0:lp.provider)==null?void 0:cp.type)==="runtype";if(Qn&&(ko||Lo))if(!V||!xt){let G=xr(r.voiceRecognition,r.sendButton);G&&(V=G.micButton,xt=G.micButtonWrapper,Vt.insertBefore(xt,Hn),V.addEventListener("click",ka),V.disabled=$.isStreaming())}else{let G=(dp=r.voiceRecognition)!=null?dp:{},Et=(pp=r.sendButton)!=null?pp:{},Ut=(up=G.iconName)!=null?up:"mic",mt=(mp=Et.size)!=null?mp:"40px",Wt=(gp=G.iconSize)!=null?gp:mt,gn=parseFloat(Wt)||24;V.style.width=Wt,V.style.height=Wt,V.style.minWidth=Wt,V.style.minHeight=Wt;let Sn=(hp=(fp=G.iconColor)!=null?fp:Et.textColor)!=null?hp:"currentColor";V.innerHTML="";let vr=Se(Ut,gn,Sn,2);vr?V.appendChild(vr):V.textContent="\u{1F3A4}";let Wn=(bp=G.backgroundColor)!=null?bp:Et.backgroundColor;Wn?V.style.backgroundColor=Wn:V.style.backgroundColor="",Sn?V.style.color=Sn:V.style.color="var(--persona-text, #111827)",G.borderWidth?(V.style.borderWidth=G.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),G.borderColor?V.style.borderColor=G.borderColor:V.style.borderColor="",G.paddingX?(V.style.paddingLeft=G.paddingX,V.style.paddingRight=G.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),G.paddingY?(V.style.paddingTop=G.paddingY,V.style.paddingBottom=G.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let rn=xt==null?void 0:xt.querySelector(".persona-send-button-tooltip"),Yn=(yp=G.tooltipText)!=null?yp:"Start voice recognition";if(((xp=G.showTooltip)!=null?xp:!1)&&Yn)if(rn)rn.textContent=Yn,rn.style.display="";else{let fn=document.createElement("div");fn.className="persona-send-button-tooltip",fn.textContent=Yn,xt==null||xt.insertBefore(fn,V)}else rn&&(rn.style.display="none");xt.style.display="",V.disabled=$.isStreaming()}else V&&xt&&(xt.style.display="none",((wp=(vp=r.voiceRecognition)==null?void 0:vp.provider)==null?void 0:wp.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():lt&&jt());if(((Cp=r.attachments)==null?void 0:Cp.enabled)===!0)if(!ve||!at){let G=(Ap=r.attachments)!=null?Ap:{},Ut=(Tp=((Sp=r.sendButton)!=null?Sp:{}).size)!=null?Tp:"40px";tt||(tt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),tt.style.display="none",Ht.insertBefore(tt,ee)),ae||(ae=document.createElement("input"),ae.type="file",ae.accept=((Ep=G.allowedTypes)!=null?Ep:Vr).join(","),ae.multiple=((Mp=G.maxFiles)!=null?Mp:4)>1,ae.style.display="none",ae.setAttribute("aria-label","Attach files"),Ht.insertBefore(ae,ee)),ve=h("div","persona-send-button-wrapper"),at=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),at.type="button",at.setAttribute("aria-label",(kp=G.buttonTooltipText)!=null?kp:"Attach file");let mt=(Lp=G.buttonIconName)!=null?Lp:"paperclip",Wt=Ut,gn=parseFloat(Wt)||40,Sn=Math.round(gn*.6);at.style.width=Wt,at.style.height=Wt,at.style.minWidth=Wt,at.style.minHeight=Wt,at.style.fontSize="18px",at.style.lineHeight="1",at.style.backgroundColor="transparent",at.style.color="var(--persona-primary, #111827)",at.style.border="none",at.style.borderRadius="6px",at.style.transition="background-color 0.15s ease",at.addEventListener("mouseenter",()=>{at.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),at.addEventListener("mouseleave",()=>{at.style.backgroundColor="transparent"});let vr=Se(mt,Sn,"currentColor",1.5);vr?at.appendChild(vr):at.textContent="\u{1F4CE}",at.addEventListener("click",Yn=>{Yn.preventDefault(),ae==null||ae.click()}),ve.appendChild(at);let Wn=(Pp=G.buttonTooltipText)!=null?Pp:"Attach file",rn=h("div","persona-send-button-tooltip");rn.textContent=Wn,ve.appendChild(rn),Pt.append(ve),!At&&ae&&tt&&(At=cs.fromConfig(G),At.setPreviewsContainer(tt),ae.addEventListener("change",async()=>{At&&(ae!=null&&ae.files)&&(await At.handleFileSelect(ae.files),ae.value="")})),q.querySelector(".persona-attachment-drop-overlay")||q.appendChild(Wm(G.dropOverlay))}else{ve.style.display="";let G=(Ip=r.attachments)!=null?Ip:{};ae&&(ae.accept=((Wp=G.allowedTypes)!=null?Wp:Vr).join(","),ae.multiple=((Rp=G.maxFiles)!=null?Rp:4)>1),At&&At.updateConfig({allowedTypes:G.allowedTypes,maxFileSize:G.maxFileSize,maxFiles:G.maxFiles})}else ve&&(ve.style.display="none"),At&&At.clearAttachments(),(Hp=q.querySelector(".persona-attachment-drop-overlay"))==null||Hp.remove();let Xt=(Bp=r.sendButton)!=null?Bp:{},Po=(Dp=Xt.useIcon)!=null?Dp:!1,lo=(Np=Xt.iconText)!=null?Np:"\u2191",co=Xt.iconName,zr=(Op=Xt.tooltipText)!=null?Op:"Send message",st=(Fp=Xt.showTooltip)!=null?Fp:!1,xn=($p=Xt.size)!=null?$p:"40px",Pn=Xt.backgroundColor,sn=Xt.textColor;if(Po){if(ze.style.width=xn,ze.style.height=xn,ze.style.minWidth=xn,ze.style.minHeight=xn,ze.style.fontSize="18px",ze.style.lineHeight="1",ze.innerHTML="",sn?ze.style.color=sn:ze.style.color="var(--persona-button-primary-fg, #ffffff)",co){let G=parseFloat(xn)||24,Et=(sn==null?void 0:sn.trim())||"currentColor",Ut=Se(co,G,Et,2);Ut?ze.appendChild(Ut):ze.textContent=lo}else ze.textContent=lo;ze.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Pn?(ze.style.backgroundColor=Pn,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=(jp=(_p=r.copy)==null?void 0:_p.sendButtonLabel)!=null?jp:"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.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",Pn?(ze.style.backgroundColor=Pn,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),sn?ze.style.color=sn:ze.classList.add("persona-text-white");Xt.borderWidth?(ze.style.borderWidth=Xt.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),Xt.borderColor?ze.style.borderColor=Xt.borderColor:ze.style.borderColor="",Xt.paddingX?(ze.style.paddingLeft=Xt.paddingX,ze.style.paddingRight=Xt.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Xt.paddingY?(ze.style.paddingTop=Xt.paddingY,ze.style.paddingBottom=Xt.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let pt=Hn==null?void 0:Hn.querySelector(".persona-send-button-tooltip");if(st&&zr)if(pt)pt.textContent=zr,pt.style.display="";else{let G=document.createElement("div");G.className="persona-send-button-tooltip",G.textContent=zr,Hn==null||Hn.insertBefore(G,ze)}else pt&&(pt.style.display="none");let bt=(Kp=(Up=r.layout)==null?void 0:Up.contentMaxWidth)!=null?Kp:F()?(Vp=(zp=(qp=r.launcher)==null?void 0:qp.composerBar)==null?void 0:zp.contentMaxWidth)!=null?Vp:"720px":void 0;bt?(nt.style.maxWidth=bt,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",Ht&&(Ht.style.maxWidth=bt,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=bt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let ut=(Jp=r.statusIndicator)!=null?Jp:{},On=(Gp=ut.visible)!=null?Gp:!0;if(an.style.display=On?"":"none",$){let G=$.getStatus();Ye(an,(Ut=>{var mt,Wt,gn,Sn;return Ut==="idle"?(mt=ut.idleText)!=null?mt:Tn.idle:Ut==="connecting"?(Wt=ut.connectingText)!=null?Wt:Tn.connecting:Ut==="connected"?(gn=ut.connectedText)!=null?gn:Tn.connected:Ut==="error"?(Sn=ut.errorText)!=null?Sn:Tn.error:Tn[Ut]})(G),ut,G)}an.classList.remove("persona-text-left","persona-text-center","persona-text-right");let pn=ut.align==="left"?"persona-text-left":ut.align==="center"?"persona-text-center":"persona-text-right";an.classList.add(pn)},open(){N()&&Dt(!0,"api")},close(){N()&&Dt(!1,"api")},toggle(){N()&&Dt(!R,"api")},clearChat(){kn=!1,$.clearMessages(),$r.clear(),Ir();try{localStorage.removeItem(xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==xs)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(),ie==null||ie.clear(),me==null||me.reset(),z==null||z.update()},setMessage(c){return!ee||$.isStreaming()?!1:(!R&&N()&&Dt(!0,"system"),ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ee.value.trim();return g?(!R&&N()&&Dt(!0,"system"),ee.value="",ee.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()||(!R&&N()&&Dt(!0,"system"),yt.manuallyDeactivated=!1,Dn(),$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),ar("user"),$.isVoiceActive()&&Bs()})),!0):lt?!0:An()?(!R&&N()&&Dt(!0,"system"),yt.manuallyDeactivated=!1,Dn(),mn("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(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Dn(),ar("user"),ao()}),!0):!1:lt?(yt.manuallyDeactivated=!0,Dn(),jt("user"),!0):!1},injectMessage(c){return!R&&N()&&Dt(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!R&&N()&&Dt(!0,"system");let g=$.injectAssistantMessage(c);return j&&(j=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),g},injectUserMessage(c){return!R&&N()&&Dt(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!R&&N()&&Dt(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!R&&N()&&Dt(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!R&&N()&&Dt(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!R&&N()&&Dt(!0,"system"),$.injectTestEvent(c)},async connectStream(c,g){return $.connectStream(c,g)},__pushEventStreamEvent(c){ie&&(me==null||me.processEvent(c.type,c.payload),ie.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Ie||!ie||Dr()},hideEventStream(){oe&&gr()},isEventStreamVisible(){return oe},showArtifacts(){mr(r)&&(kn=!1,Vn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){mr(r)&&(kn=!0,Vn())},upsertArtifact(c){return mr(r)?(kn=!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&&!R&&!F()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,g,b){let T=$.getMessages().find(B=>{var O;return B.variant==="approval"&&((O=B.approval)==null?void 0:O.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 N()&&R},isVoiceActive(){return yt.active},getState(){return{open:N()&&R,launcherEnabled:S,voiceActive:yt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!R&&N()&&Dt(!0,"system");let g=nt.querySelector(".persona-feedback-container");g&&g.remove();let b=El({onSubmit:async(y,T)=>{var B;$.isClientTokenMode()&&await $.submitCSATFeedback(y,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,y,T)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&N()&&Dt(!0,"system");let g=nt.querySelector(".persona-feedback-container");g&&g.remove();let b=Ml({onSubmit:async(y,T)=>{var B;$.isClientTokenMode()&&await $.submitNPSFeedback(y,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,y,T)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.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(){ir!=null&&(clearInterval(ir),ir=null),ht.forEach(c=>c()),xe.remove(),Ke==null||Ke.remove(),tn==null||tn.destroy(),nn==null||nn.remove(),sr&&W.removeEventListener("click",sr)}};if((((zc=n==null?void 0:n.debugTools)!=null?zc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:cn,getMessages:cn.getMessages,getStatus:cn.getStatus,getMetadata:cn.getPersistentMetadata,updateMetadata:cn.updatePersistentMetadata,clearHistory:()=>cn.clearChat(),setVoiceActive:b=>b?cn.startVoiceRecognition():cn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ht.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=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&cn.focusInput()};if(window.addEventListener("persona:focusInput",g),ht.push(()=>{window.removeEventListener("persona:focusInput",g)}),Ie){let U=ye=>{let ue=ye.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&cn.showEventStream()},H=ye=>{let ue=ye.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&cn.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",H),ht.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",H)})}let b=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&cn.showArtifacts()},y=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&cn.hideArtifacts()},T=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&cn.upsertArtifact(H.artifact)},B=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&cn.selectArtifact(H.id)},O=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&cn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",O),ht.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",O)})}let lr=bx(r.persistState);if(lr&&N()){let c=yx(lr.storage),g=`${lr.keyPrefix}widget-open`,b=`${lr.keyPrefix}widget-voice`,y=`${lr.keyPrefix}widget-voice-mode`;if(c){let T=((Vc=lr.persist)==null?void 0:Vc.openState)&&c.getItem(g)==="true",B=((Kc=lr.persist)==null?void 0:Kc.voiceState)&&c.getItem(b)==="true",O=((Jc=lr.persist)==null?void 0:Jc.voiceState)&&c.getItem(y)==="true";if(T&&setTimeout(()=>{cn.open(),setTimeout(()=>{var U;if(B||O)cn.startVoiceRecognition();else if((U=lr.persist)!=null&&U.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(Gc=lr.persist)!=null&&Gc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(Xc=lr.persist)!=null&&Xc.voiceState&&(o.on("voice:state",U=>{c.setItem(b,U.active?"true":"false")}),o.on("user:message",U=>{c.setItem(y,U.viaVoice?"true":"false")})),lr.clearOnChatClear){let U=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(y)},H=()=>U();window.addEventListener("persona:clear-chat",H),ht.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&N()&&setTimeout(()=>{cn.open()},0),qr(),cn};var xx=(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},Rm=(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"},Rl=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=""},Hm=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Rl(e)},Pl=e=>{e.style.transition=""},Il=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"},Si=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},vx=(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))},wx=(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)},Bm=(e,t,n,r,s,o,a)=>{var v,x,w,S,D,E;let i=Cr(o),d=i.reveal==="push";vx(e,t,n,r,d),wx(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"),Il(t),Pl(r),Hm(r),Wl(n),Si(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((E=(D=o==null?void 0:o.launcher)==null?void 0:D.zIndex)!=null?E:En),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"),Hm(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Il(t),Pl(r),Wl(n),Si(s,r);let P=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=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",Pl(r),Rl(r),Si(s,r);let P=xx(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),A=i.animate?"transform 180ms ease":"none",M=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=`${I+P}px`,t.style.transition=A,t.style.transform=M,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="",Il(t),Rl(r),Wl(n),Si(s,r);let P=i.reveal==="emerge";P?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",M=!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=P||M?"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")}},Cx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Rm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Rm(n,r)},destroy(){n.remove()}}},Ax=(e,t)=>{var D,E,P,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=(E=(D=t==null?void 0:t.launcher)==null?void 0:D.enabled)==null||E?(I=(P=t==null?void 0:t.launcher)==null?void 0:P.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(),Cr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Bm(a,i,d,l,p,t,u)}),f.observe(a))},x=()=>{Bm(a,i,d,l,p,t,u),v()},w=a.ownerDocument.defaultView,S=()=>{x()};return w==null||w.addEventListener("resize",S),Cr(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 M=A.launcherEnabled?A.open:!0;u!==M&&(u=M,x())},updateConfig(A){var M,F;t=A,((F=(M=t==null?void 0:t.launcher)==null?void 0:M.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()}}},Ti=(e,t)=>hn(t)?Ax(e,t):Cx(e,t);var Hl={},Dm=!1,Sx=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},Tx=()=>{try{if(typeof Hl!="undefined"&&Hl.url)return new URL("../widget.css",Hl.url).href}catch{}return null},Nm=(e,t)=>{let n=Tx(),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)}},Om=e=>{let t=Sx(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=Ti(t,s),a,i=[],d=(w,S)=>{var I,A;let E=!((A=(I=S==null?void 0:S.launcher)==null?void 0:I.enabled)!=null?A:!0)||hn(S),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),E&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let M=w.attachShadow({mode:"open"});M.appendChild(P),Nm(M,r)}else w.appendChild(P),Nm(w,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},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=Ll(w,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(Dm||(Dm=!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=Ti(t,w),s=w,u()},v={update(w){var A,M,F,N,R,j;let S={...s,...w,launcher:{...(A=s==null?void 0:s.launcher)!=null?A:{},...(M=w==null?void 0:w.launcher)!=null?M:{},dock:{...(N=(F=s==null?void 0:s.launcher)==null?void 0:F.dock)!=null?N:{},...(j=(R=w==null?void 0:w.launcher)==null?void 0:R.dock)!=null?j:{}}}},D=hn(s),E=hn(S),P=go(s),I=go(S);if(D!==E||P!==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,D){if(S==="host")return o.host;if(S in w)return Reflect.get(w,S,D);let E=a[S];return typeof E=="function"?E.bind(a):E}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Um=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Ex=new Set(["button","a","input","select","textarea","details","summary"]),Mx=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Bl=/\b(product|card|item|listing|result)\b/i,Nl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,kx=3e3,Lx=100;function qm(e){let t=typeof e.className=="string"?e.className:"";if(Bl.test(t)||e.id&&Bl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Bl.test(r.value))return!0}return!1}function zm(e){var t;return Nl.test(((t=e.textContent)!=null?t:"").trim())}function Vm(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 Px(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Fm(e){let t=e.match(Nl);return t?t[0]:null}function $m(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 Ix(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 Wx="commerce-card",Rx="result-card";function _m(e){return!qm(e)||!zm(e)||!Vm(e)&&!Px(e)?0:5200}function jm(e){var r;return!qm(e)||zm(e)||!Vm(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 Km=[{id:Wx,scoreElement(e){return _m(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||Nl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(_m(e)===0)return null;let{title:n,href:r}=$m(e),s=(p=(l=Fm(((d=e.textContent)!=null?d:"").trim()))!=null?l:Fm(t.text))!=null?p:"",o=Ix(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:Rx,scoreElement(e){return jm(e)},formatSummary(e,t){if(jm(e)===0)return null;let{title:n,href:r}=$m(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
109
|
+
`)}}];function Hx(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Bx(e){var p,u,f,m,v,x,w,S,D,E,P,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=(D=(S=t.visibleOnly)!=null?S:e.visibleOnly)!=null?D:!0,a=(E=t.root)!=null?E:e.root,i=(P=t.mode)!=null?P:"structured",d=(I=t.maxCandidates)!=null?I:Math.max(500,n*10),l=(A=e.rules)!=null?A:Km;return i==="simple"&&e.rules&&e.rules.length>0?(Hx(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function Dl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Dx=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Nx(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"||Ex.has(t)||n&&Mx.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Jm(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 Ox(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 Gm(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Dl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Dx){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${Dl(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=>Dl(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 Fx(e){return e==="static"?Lx:kx}function Xm(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:Gm(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Nx(e),attributes:Ox(e)}}function $x(e,t,n,r){let s=Fx(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 _x(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 jx(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(Um.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Jm(l)){i=a.nextNode();continue}let u=Xm(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}=$x(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;_x(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 Ux(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(Um.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Jm(d)){o=s.nextNode();continue}let p=Xm(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 qx(e={}){var r;let t=Bx(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Ux(t,n):jx(t,n):[]}var Ei=100;function zx(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,
|
|
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,Ei)}" (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,
|
|
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,Ei)}" (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,
|
|
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,Ei)}" (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,
|
|
119
|
+
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Ei)}"`);r.push(`Content:
|
|
120
120
|
${a.join(`
|
|
121
121
|
`)}`)}return r.join(`
|
|
122
122
|
|
|
123
|
-
`)}var
|
|
123
|
+
`)}var Qm={name:"@runtypelabs/persona",version:"3.31.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 vs=Qm.version;function Kx(){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 Jx(){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 Gx(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:Br(e.colors.primary,.95),100:Br(e.colors.primary,.9),200:Br(e.colors.primary,.8),300:Br(e.colors.primary,.7),400:Br(e.colors.primary,.6),500:e.colors.primary,600:Br(e.colors.primary,.8),700:Br(e.colors.primary,.7),800:Br(e.colors.primary,.6),900:Br(e.colors.primary,.5),950:Br(e.colors.primary,.45)}}),{...t,palette:n}}}}function Xx(){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 Qx(){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 Br(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 Yx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Zx={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"}}},Ym={components:{panel:{borderRadius:"0",shadow:"none"}}},Zm={id:"shop",label:"Shopping Assistant",config:{theme:Zx,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?"]}},eg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ym}},tg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ym}},ng={shop:Zm,minimal:eg,fullscreen:tg};function ev(e){return ng[e]}var tv=Om;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function nv(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var rg=`({ 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
|
-
}`,
|
|
136
|
+
}`,og=`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
|
-
}`,
|
|
149
|
+
}`,sg=`(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
|
-
}`,
|
|
166
|
+
}`,ag=`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
|
-
}`,
|
|
183
|
+
}`,rv=`(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
|
-
}`,
|
|
189
|
+
}`,ov=`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
|
|
196
|
-
`)}function
|
|
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
|
|
199
|
-
`)}function
|
|
195
|
+
}`;function sv(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 Mi(e){var t,n;return(n=(t=e.parserType)!=null?t:sv(e.streamParser))!=null?n:"plain"}function ki(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 Li(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 Pi(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 Ii(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 Ol(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 ig(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}: {`),ig(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function wo(e,t,n,r){n&&(e.push(`${r}${t}: {`),ig(e,n,`${r} `),e.push(`${r}},`))}function ma(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function av(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:nv(n.hooks)}:void 0;return t==="esm"?iv(r,s):t==="script-installer"?dv(r,s):t==="script-advanced"?uv(r,s):t==="react-component"?lv(r,s):t==="react-advanced"?cv(r,s):pv(r,s)}function iv(e,t){let n=t==null?void 0:t.hooks,r=Mi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ma(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&&wo(o,"theme",e.theme," "),e.launcher&&wo(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(...ki(e," ")),o.push(...Li(e," ",n)),o.push(...Pi(e," ")),o.push(...Ii(e," ")),o.push(...Ol(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 lv(e,t){let n=t==null?void 0:t.hooks,r=Mi(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: '${ma(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&&wo(o,"theme",e.theme," "),e.launcher&&wo(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(...ki(e," ")),o.push(...Li(e," ",n)),o.push(...Pi(e," ")),o.push(...Ii(e," ")),o.push(...Ol(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 cv(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: '${ma(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&&wo(r,"theme",e.theme," "),e.launcher&&wo(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(...ki(e," ")),r.push(...Li(e," ",n)),r.push(...Pi(e," ")),r.push(...Ii(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(${rv}),`)),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(` ${rg}`),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(` ${rg}`),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(` ${sg}`),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(` ${sg}`),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 lg(e){var s;let t=Mi(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 dv(e,t){let n=lg(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,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${vs}/dist/install.global.js" data-config='${o}'></script>`}function pv(e,t){let n=t==null?void 0:t.hooks,r=Mi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${vs}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${vs}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${ma(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&&wo(o,"theme",e.theme," "),e.launcher&&wo(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(...ki(e," ")),o.push(...Li(e," ",n)),o.push(...Pi(e," ")),o.push(...Ii(e," ")),o.push(...Ol(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 uv(e,t){let n=t==null?void 0:t.hooks,r=lg(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@${
|
|
202
|
-
`)}var
|
|
201
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${vs}/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(${ov});`),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(` ${og}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${og}`),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(` ${ag}`),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(` ${ag}`),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: '${ma(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 cg={desktop:{w:1280,h:800},mobile:{w:390,h:844}},dg=.1,pg=.15,ug=1.5,Fl=24,mg=40,mv=`
|
|
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: ${
|
|
353
|
+
padding: ${Fl}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
|
|
443
|
+
`;function gv(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=mv,document.head.appendChild(e)}function fv(e,t){let n=e.clientWidth-Fl*2-mg,r=e.clientHeight-Fl*2-mg;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function hv(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 bv(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");gv();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"),D=h("div","persona-dc-toolbar-lead"),E=h("div","persona-dc-toolbar-trail"),P=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>oe(-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 M=h("span","persona-dc-title-text"),F=h("span","persona-dc-title-chevron"),N=Se("chevron-down",12,"currentColor",2);N&&F.appendChild(N),A.append(M,F);let R=h("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let j=!1;function K(){R.innerHTML="";for(let Ce=0;Ce<n.length;Ce++){let Ye=n[Ce],xe=h("button","persona-dc-dropdown-item");xe.type="button",xe.setAttribute("role","option"),xe.setAttribute("aria-current",Ce===p?"true":"false");let ge=h("span");if(ge.textContent=Ye.title,xe.appendChild(ge),Ye.description){let Ke=h("span","persona-dc-dropdown-desc");Ke.textContent=Ye.description,xe.appendChild(Ke)}xe.addEventListener("click",()=>{Ee(),Re(Ce)}),R.appendChild(xe)}}function le(){j=!j,R.style.display=j?"":"none",A.setAttribute("aria-expanded",j?"true":"false"),j&&K()}function Ee(){j&&(j=!1,R.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",Ce=>{Ce.stopPropagation(),le()});let qe=()=>Ee();document.addEventListener("click",qe),I.append(A,R);let we=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>oe(1)}),Ie=h("span","persona-dc-counter");D.append(P,I,we,Ie);let he=null;i&&(he=si({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:Ce=>{u=Ce,ne.dataset.device=u,m=null,Y()}}),E.appendChild(he.element));let Me=null;if(a){let Ce=h("div","persona-dc-zoom-controls"),Ye=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ke=m!=null?m:v;m=Math.max(pg,Ke-dg),Y()}});Me=h("span","persona-dc-zoom-level"),Me.title="Reset to 100%",Me.style.cursor="pointer",Me.addEventListener("click",()=>{m=1,Y()});let xe=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ke=m!=null?m:v;m=Math.min(ug,Ke+dg),Y()}}),ge=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,Y()}});Ce.append(Ye,Me,xe,ge),E.appendChild(Ce)}if(d){let Ce=h("div","persona-dc-separator");E.appendChild(Ce);let Ye=si({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:xe=>{f=xe,ne.dataset.colorScheme=f,me()}});E.appendChild(Ye.element)}let We=h("div","persona-dc-separator");E.appendChild(We);let ce=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});E.appendChild(ce),S.append(D,E);let X=h("div","persona-dc-stage"),ne=h("div","persona-dc-iframe-wrapper");ne.dataset.device=u,ne.dataset.colorScheme=f;let ie=h("iframe","persona-dc-iframe");ie.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ie.setAttribute("loading","lazy"),ie.title=n[p].title,ne.appendChild(ie),X.appendChild(ne),w.append(S,X),e.appendChild(w);function me(){var Ce;try{let Ye=(Ce=ie.contentDocument)==null?void 0:Ce.body;if(!Ye)return;f==="dark"?Ye.classList.add("theme-dark"):Ye.classList.remove("theme-dark")}catch{}}ie.addEventListener("load",()=>me());function z(){let Ce=n[p];M.textContent=Ce.title,Ie.textContent=`${p+1} / ${n.length}`,ie.title=Ce.title}function oe(Ce){let Ye=((p+Ce)%n.length+n.length)%n.length;Re(Ye)}function Re(Ce){Ce<0||Ce>=n.length||(p=Ce,ie.src=n[p].url,z(),l==null||l(p,n[p]))}function Y(){var xe;if(x)return;let Ce=(xe=cg[u])!=null?xe:cg.desktop;v=fv(X,Ce);let Ye=Math.max(pg,Math.min(ug,m!=null?m:v));hv(ne,ie,Ce,Ye,u),Me&&(Me.textContent=`${Math.round(Ye*100)}%`)}let Z=new ResizeObserver(()=>Y());Z.observe(X),z(),ie.src=n[p].url,requestAnimationFrame(()=>Y());function se(){x||(x=!0,Z.disconnect(),document.removeEventListener("click",qe),w.remove())}return{element:w,goTo:Re,next:()=>oe(1),prev:()=>oe(-1),getIndex:()=>p,setDevice(Ce){u=Ce,ne.dataset.device=Ce,he==null||he.setSelected(Ce),m=null,Y()},setColorScheme(Ce){f=Ce,ne.dataset.colorScheme=Ce},setZoom(Ce){m=Ce,Y()},destroy:se}}export{Qu as ASK_USER_QUESTION_TOOL_NAME,as as AgentWidgetClient,Js as AgentWidgetSession,cs as AttachmentManager,vu as DEFAULT_COMPONENTS,Ki as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,pr as DEFAULT_FLOATING_LAUNCHER_WIDTH,yu as DEFAULT_PALETTE,xu as DEFAULT_SEMANTIC,$t as DEFAULT_WIDGET_CONFIG,ng as PRESETS,tg as PRESET_FULLSCREEN,eg as PRESET_MINIMAL,Zm as PRESET_SHOP,pb as THEME_ZONES,vs as VERSION,po as WEBMCP_TOOL_PREFIX,js as WebMcpBridge,Kx as accessibilityPlugin,Jx as animationsPlugin,Oo as applyThemeVariables,ps as attachHeaderToContainer,Gx as brandPlugin,aa as buildComposer,Nu as buildDefaultHeader,fo as buildHeader,sa as buildHeaderWithLayout,Ou as buildMinimalHeader,qx as collectEnrichedPageContext,vo as componentRegistry,Ci as createActionManager,Ll as createAgentExperience,Sy as createAskUserQuestionBubble,Vi as createBestAvailableVoiceProvider,Kb as createBubbleWithLayout,El as createCSATFeedback,rl as createComboButton,ux as createComponentMiddleware,Cl as createComponentStreamParser,eu as createDefaultSanitizer,bv as createDemoCarousel,Cg as createDirectivePostprocessor,$o as createDropdownMenu,Og as createFlexibleJsonStreamParser,Gt as createIconButton,Jg as createImagePart,Ui as createJsonStreamParser,oi as createLabelButton,wl as createLocalStorageAdapter,Ia as createMarkdownProcessor,rs as createMarkdownProcessorFromConfig,Ku as createMessageActions,Ml as createNPSFeedback,_i as createPlainTextParser,Yx as createPlugin,ji as createRegexJsonParser,ia as createStandardBubble,$a as createTextPart,Xs as createTheme,Qi as createThemeObserver,si as createToggleGroup,us as createTypingIndicator,ls as createVoiceProvider,Ti as createWidgetHostLayout,qi as createXmlParser,tv as default,ys as defaultActionHandlers,wi as defaultJsonActionParser,Km as defaultParseRules,Va as detectColorScheme,Ag as directivePostprocessor,ca as ensureAskUserQuestionSheet,os as escapeHtml,Tl as extractComponentDirectiveFromMessage,Gg as fileToImagePart,zx as formatEnrichedContext,is as generateAssistantMessageId,av as generateCodeSnippet,Ug as generateMessageId,Gm as generateStableSelector,zs as generateUserMessageId,Qs as getActiveTheme,Su as getColorScheme,zg as getDisplayText,Fu as getHeaderLayout,Kg as getImageParts,ev as getPreset,Sl as hasComponentDirective,Vg as hasImages,ol as headerLayouts,Qx as highContrastPlugin,Om as initAgentWidget,ho as isAskUserQuestionMessage,px as isComponentDirectiveType,hn as isDockedMountMode,qa as isVoiceSupported,Bo as isWebMcpToolName,wb as listRegisteredStreamAnimations,Qp as markdownPostprocessor,Ji as mergeWithDefaults,qg as normalizeContent,bo as parseAskUserQuestionPayload,vi as pluginRegistry,Xx as reducedMotionPlugin,xb as registerStreamAnimationPlugin,jo as removeAskUserQuestionSheet,Al as renderComponentDirective,Vu as renderLoadingIndicatorWithFallback,Se as renderLucideIcon,Cr as resolveDockConfig,_s as resolveSanitizer,Gi as resolveTokens,Fi as stripWebMcpPrefix,Xi as themeToCssVariables,vb as unregisterStreamAnimationPlugin,Xg as validateImageFile,wu as validateTheme};
|
|
444
444
|
//# sourceMappingURL=index.js.map
|