@runtypelabs/persona 3.29.0 → 3.29.1
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/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-CxvHw0X6.d.cts → types-B_Qazlm4.d.cts} +6 -0
- package/dist/animations/{types-CxvHw0X6.d.ts → types-B_Qazlm4.d.ts} +6 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +39 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.global.js +47 -47
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +39 -39
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +6 -0
- package/dist/smart-dom-reader.d.ts +6 -0
- package/dist/theme-editor.cjs +30 -30
- package/dist/theme-editor.d.cts +6 -0
- package/dist/theme-editor.d.ts +6 -0
- package/dist/theme-editor.js +30 -30
- package/package.json +1 -1
- package/src/client.test.ts +40 -0
- package/src/client.ts +18 -4
- package/src/generated/runtype-openapi-contract.ts +12 -0
- package/src/session.ts +190 -29
- package/src/session.webmcp.test.ts +326 -6
package/dist/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{Marked as
|
|
1
|
+
import{Marked as Wm}from"marked";var Rm=e=>{if(e)return e},wa=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new Wm({gfm:(s=t==null?void 0:t.gfm)!=null?s:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=Rm(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},jo=e=>e?wa({markedOptions:e.options,renderer:e.renderer}):wa(),Hm=wa(),wp=e=>Hm(e),Uo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Ap=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Cp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Sp=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Cp(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Cp(t.length);return t.push({token:o,type:s}),o}),n},Bm=e=>{let t=jo(e);return n=>{let r=[],s=Sp(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Ap(i)}"></div>`;o=o.replace(d,p)}),o}},Dm=e=>{let t=[],n=Sp(e,t),r=wp(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Ap(o)}"></div>`;r=r.replace(a,d)}),r};import Nm from"dompurify";var Fm={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Om=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Tp=()=>{let e=Nm(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let r=n.attrValue;r.toLowerCase().startsWith("data:")&&!Om.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Fm)},Es=e=>e===!1?null:typeof e=="function"?e:Tp();var Sa="webmcp:",Aa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Mp(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${$m(t.join(""))}`}function Ep(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function $m(e){let t=Ep(e,0).toString(36),n=Ep(e,2654435761).toString(36);return`${t}.${n}`}var Ms=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return Aa.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=jm(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return hr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let u=typeof document!="undefined"&&!!document.modelContext;return hr(u?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=kp(t),a;try{a=await s.getTools()}catch(u){let v=u instanceof Error?u.message:String(u);return hr(`Failed to read WebMCP registry: ${v}`)}let i=a.find(u=>u.name===o);if(!i)return hr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return hr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let d={toolName:o,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),g=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",g,{once:!0}));try{let u=await s.executeTool(i,Vm(n),{signal:l.signal});return Um(u)}catch(u){if(p)return hr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let v=u instanceof Error?u.message:String(u);return hr(v)}finally{clearTimeout(m),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Aa.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Aa.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:qm;try{return await n(t)}catch(s){return Aa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>_m(t,r))}},kp=e=>e.startsWith(Sa)?e.slice(Sa.length):e,So=e=>e.startsWith(Sa),_m=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},jm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Um=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Km(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),qm=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=zm(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
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)},zm=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Vm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Km=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Lp,STR as Pp,OBJ as Ip}from"partial-json";var Ta=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),qo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Jm=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Wp=e=>e.status==="complete"?Jm(e):e.status==="pending"?"Waiting":"",Gm=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Rp=e=>e.status==="complete"?Gm(e):"Using tool...",Ea=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ls=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ea(t)},Ma=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ea(t)},Si=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Ls(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},ka=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&ks(r,n.slice(o,a.index),[]),a[1]!==void 0?ks(r,a[1],["bold"]):a[2]!==void 0?ks(r,a[2],["italic"]):a[3]!==void 0&&ks(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&ks(r,n.slice(o),[]),r},ks=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Xm=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
8
8
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},So=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Si=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ti=()=>{var t;let e=Jm();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Ei=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=kp(n,Lp|Pp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Sa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Sa(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Gm=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Sa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Sa(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=kp(o,Lp|Pp),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Mi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ka=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Xm="https://api.runtype.com/v1/dispatch",La="https://api.runtype.com";function Qm(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ki=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Ym(e){switch(e){case"json":return Ei;case"regex-json":return Ti;case"xml":return Mi;default:return Si}}var Rp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Zm(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Rp(n);if(!Rp(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=So(e);return So(t)!==null&&a===null?t:e}var qo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Xm,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Ym(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new Es(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||La}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||La}/v1/client/feedback`}async sendFeedback(t){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let P=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:P}),P}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(ki).map(P=>{var W,w,I;return{id:P.id,role:P.role,content:(I=(w=(W=P.contentParts)!=null?W:P.llmContent)!=null?w:P.rawContent)!=null?I:P.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,u=!!(g&&g.length>0),v=u?Ep(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,C=u&&x&&this.lastSentClientToolsFingerprint===v,T=!1,H=null,L;for(let P=0;;P++){let w={...m,...u&&(T||!C)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:r.signal}),L.status===409&&P===0&&u){let I=await L.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}H=I!=null?I:{error:"Chat request failed"}}break}if(!L.ok){let P=H!=null?H:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:w}),w}if(L.status===429){let w=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let W=new Error(P.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!L.body){let P=new Error("No response body received");throw n({type:"error",error:P}),P}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(L.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||La}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||La}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(ki).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(t){var o;let r={messages:t.slice().filter(ki).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var ln,Hn,Xn,Ue;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=N=>{let Ae=N.reasoning?{...N.reasoning,chunks:[...N.reasoning.chunks]}:void 0,Be=N.toolCall?{...N.toolCall,chunks:N.toolCall.chunks?[...N.toolCall.chunks]:void 0}:void 0,De=N.tools?N.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...N,reasoning:Ae,toolCall:Be,tools:De}},m=N=>{if(N.role!=="assistant"||N.variant)return!0;let Ae=Array.isArray(N.contentParts)&&N.contentParts.length>0,Be=typeof N.rawContent=="string"&&N.rawContent.trim()!=="";return typeof N.content=="string"&&N.content.trim()!==""||Ae||Be||!!N.stopReason},g=N=>{m(N)&&n({type:"message",message:p(N)})},u=null,v=null,x={current:null},C={current:null},T=!1,H=new Map,L=new Map,P=new Map,W=new Map,w={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},O=(N,Ae,Be="")=>`${N}::${Ae}::${Be}`,$=(N,Ae)=>`${N}::${Ae}::`,B=(N,Ae,Be,De)=>{let _e=O(N,Ae,Be),dt=P.get(_e);if(dt)return dt;let rt=Be?`-${Be}`:"",At={id:`nested-${N}-${Ae}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:De,parentToolId:N,parentStepId:Ae}};return P.set(_e,At),g(At),At},j=N=>{if(N==null)return null;try{return String(N)}catch{return null}},z=N=>{var Ae,Be,De,_e,dt;return j((dt=(_e=(De=(Be=(Ae=N.stepId)!=null?Ae:N.step_id)!=null?Be:N.step)!=null?De:N.parentId)!=null?_e:N.flowStepId)!=null?dt:N.flow_step_id)},oe=N=>{var Ae,Be,De,_e,dt,rt,At;return j((At=(rt=(dt=(_e=(De=(Be=(Ae=N.callId)!=null?Ae:N.call_id)!=null?Be:N.requestId)!=null?De:N.request_id)!=null?_e:N.toolCallId)!=null?dt:N.tool_call_id)!=null?rt:N.stepId)!=null?At:N.step_id)},We=r,je=!1,Ne=()=>{if(u)return u;let N;return!je&&We?(N=We,je=!0):We&&C.current?N=`${We}_${C.current}`:N=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:N,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(u),u},ge=(N,Ae)=>{w.lastId=Ae,N&&w.byStep.set(N,Ae)},ye=(N,Ae)=>{var dt;let Be=(dt=N.reasoningId)!=null?dt:N.id,De=z(N);if(Be){let rt=String(Be);return ge(De,rt),rt}if(De){let rt=w.byStep.get(De);if(rt)return w.lastId=rt,rt}if(w.lastId&&!Ae)return w.lastId;if(!Ae)return null;let _e=`reason-${l()}`;return ge(De,_e),_e},Le=N=>{let Ae=H.get(N);if(Ae)return Ae;let Be={id:`reason-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:N,status:"streaming",chunks:[]}};return H.set(N,Be),g(Be),Be},He=(N,Ae)=>{I.lastId=Ae,N&&I.byCall.set(N,Ae)},ee=new Set,Pe=new Map,V=new Set,le=new Map,ve=N=>{if(!N)return!1;let Ae=N.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ae==="emit_artifact_markdown"||Ae==="emit_artifact_component"},fe=(N,Ae)=>{var dt;let Be=(dt=N.toolId)!=null?dt:N.id,De=oe(N);if(Be){let rt=String(Be);return He(De,rt),rt}if(De){let rt=I.byCall.get(De);if(rt)return I.lastId=rt,rt}if(I.lastId&&!Ae)return I.lastId;if(!Ae)return null;let _e=`tool-${l()}`;return He(De,_e),_e},we=N=>{let Ae=L.get(N);if(Ae)return Ae;let Be={id:`tool-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:N,status:"pending"}};return L.set(N,Be),g(Be),Be},ze=N=>{if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){let Ae=Number(N);if(!Number.isNaN(Ae)&&Number.isFinite(Ae))return Ae;let Be=Date.parse(N);if(!Number.isNaN(Be))return Be}return Date.now()},Q=N=>{if(typeof N=="string")return N;if(N==null)return"";try{return JSON.stringify(N)}catch{return String(N)}},te=new Map,se=new Map,ue=new Map,ie=new Map,re=null,Qe=(N,Ae,Be)=>{var At;let De=ue.get(N);De||(De=[],ue.set(N,De));let _e=0,dt=De.length;for(;_e<dt;){let _t=_e+dt>>>1;De[_t].seq<Ae?_e=_t+1:dt=_t}((At=De[_e])==null?void 0:At.seq)===Ae?De[_e]={seq:Ae,text:Be}:De.splice(_e,0,{seq:Ae,text:Be});let rt="";for(let _t=0;_t<De.length;_t++)rt+=De[_t].text;return rt},Ie=(N,Ae)=>{let Be=Q(Ae),De=se.get(N.id),_e=Zm(De,Be);N.rawContent=_e;let dt=te.get(N.id),rt=Ye=>{var ne;let Dt=(ne=N.content)!=null?ne:"";Ye.trim()!==""&&(Dt.trim().length===0||Ye.startsWith(Dt)||Ye.trimStart().startsWith(Dt.trim()))&&(N.content=Ye)},At=()=>{var Ye;if(dt){let Dt=(Ye=dt.close)==null?void 0:Ye.call(dt);Dt instanceof Promise&&Dt.catch(()=>{})}te.delete(N.id),se.delete(N.id),N.streaming=!1,g(N)};if(!dt){rt(Be),At();return}let _t=So(_e);if(_t!==null&&_t.trim()!==""){rt(_t),At();return}let q=Ye=>{var me;let Dt=typeof Ye=="string"?Ye:(me=Ye==null?void 0:Ye.text)!=null?me:null;if(Dt!==null&&Dt.trim()!=="")return Dt;let ne=dt.getExtractedText();return ne!==null&&ne.trim()!==""?ne:Be},$t;try{$t=dt.processChunk(_e)}catch{rt(Be),At();return}if($t instanceof Promise){$t.then(Ye=>{rt(q(Ye)),At()}).catch(()=>{rt(Be),At()});return}rt(q($t)),At()},ce=[],G=!1,$e,Et=()=>{G||(G=!0,queueMicrotask(()=>{G=!1,$e()}))},de=new ka((N,Ae)=>{ce.push({payloadType:N,payload:Ae}),Et()}),ae=null,Mn=new Map,Ot=(ln=this.config.iterationDisplay)!=null?ln:"separate";for($e=()=>{var N,Ae,Be,De,_e,dt,rt,At,_t,q,$t,Ye,Dt,ne,me,vt,jt,Zt,hn,St,wt,ft,yt,zt,tt,Bn,Qn,yn,Dn,ut,xr,Nn,po,kn,Io,Or,Er,bt,Fn,On,bn,Lt,Yn,Zn,$n,$r,Mr,_r,_n,Wt,xn,er,jr,kr,Ur,vr,jn,lr,gt,Jt,Gt,Un,qr,tr,cr,qn,S,zn,dr,Lr,wr,ss,pr,ur,mr,Pr,uo,Zs,as,ea,Wo,mt,is,nr,Ln,ta,na,Ro,Ir,ra,mo,ls,Wr,cs,zr,Vr,oa,sa,wi,go,Kr,aa,ds,Jr,ia,ps,Gr,us,la,Rr,ca,Xr,Rt,Ho,Bo,ms,Cr,da,gs,fs,pa,Do,No,fo,ua,ma,hs,ys,bs,xs,vn,Vn,Hr,ot,vs,ho,gr,ga;for(let Qr=0;Qr<ce.length;Qr++){let Ve=ce[Qr].payloadType,A=ce[Qr].payload;if(Ve==="reason_start"){let _=(N=ye(A,!0))!=null?N:`reason-${l()}`,k=Le(_);k.reasoning=(Ae=k.reasoning)!=null?Ae:{id:_,status:"streaming",chunks:[]},k.reasoning.startedAt=(De=k.reasoning.startedAt)!=null?De:ze((Be=A.startedAt)!=null?Be:A.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",g(k)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let _=(dt=(_e=ye(A,!1))!=null?_e:ye(A,!0))!=null?dt:`reason-${l()}`,k=Le(_);k.reasoning=(rt=k.reasoning)!=null?rt:{id:_,status:"streaming",chunks:[]},k.reasoning.startedAt=(_t=k.reasoning.startedAt)!=null?_t:ze((At=A.startedAt)!=null?At:A.timestamp);let Y=(Ye=($t=(q=A.reasoningText)!=null?q:A.text)!=null?$t:A.delta)!=null?Ye:"";if(Y&&A.hidden!==!0){let K=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(K!==void 0){let J=Qe(_,K,String(Y));k.reasoning.chunks=[J]}else k.reasoning.chunks.push(String(Y))}if(k.reasoning.status=A.done?"complete":"streaming",A.done){k.reasoning.completedAt=ze((Dt=A.completedAt)!=null?Dt:A.timestamp);let K=(ne=k.reasoning.startedAt)!=null?ne:Date.now();k.reasoning.durationMs=Math.max(0,((me=k.reasoning.completedAt)!=null?me:Date.now())-K)}k.streaming=k.reasoning.status!=="complete",g(k)}else if(Ve==="reason_complete"){let _=(jt=(vt=ye(A,!1))!=null?vt:ye(A,!0))!=null?jt:`reason-${l()}`,k=H.get(_);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=ze((Zt=A.completedAt)!=null?Zt:A.timestamp);let K=(hn=k.reasoning.startedAt)!=null?hn:Date.now();k.reasoning.durationMs=Math.max(0,((St=k.reasoning.completedAt)!=null?St:Date.now())-K),k.streaming=!1,g(k)}let Y=z(A);Y&&w.byStep.delete(Y)}else if(Ve==="tool_start"){let _=(wt=fe(A,!0))!=null?wt:`tool-${l()}`,k=(ft=A.toolName)!=null?ft:A.name;if(ve(k)){ee.add(_);continue}let Y=we(_),K=(yt=Y.toolCall)!=null?yt:{id:_,status:"pending"};K.name=k!=null?k:K.name,K.status="running",A.args!==void 0?K.args=A.args:A.parameters!==void 0&&(K.args=A.parameters),K.startedAt=(tt=K.startedAt)!=null?tt:ze((zt=A.startedAt)!=null?zt:A.timestamp),K.completedAt=void 0,K.durationMs=void 0,Y.toolCall=K,Y.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(Y.agentMetadata={executionId:(Bn=J==null?void 0:J.executionId)!=null?Bn:A.executionId,iteration:(Qn=J==null?void 0:J.iteration)!=null?Qn:A.iteration}),g(Y)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let _=(Dn=(yn=fe(A,!1))!=null?yn:fe(A,!0))!=null?Dn:`tool-${l()}`;if(ee.has(_))continue;let k=we(_),Y=(ut=k.toolCall)!=null?ut:{id:_,status:"running"};Y.startedAt=(Nn=Y.startedAt)!=null?Nn:ze((xr=A.startedAt)!=null?xr:A.timestamp);let K=(Io=(kn=(po=A.text)!=null?po:A.delta)!=null?kn:A.message)!=null?Io:"";K&&(Y.chunks=(Or=Y.chunks)!=null?Or:[],Y.chunks.push(String(K))),Y.status="running",k.toolCall=Y,k.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(k.agentMetadata=(Fn=k.agentMetadata)!=null?Fn:{executionId:(Er=J==null?void 0:J.executionId)!=null?Er:A.executionId,iteration:(bt=J==null?void 0:J.iteration)!=null?bt:A.iteration}),g(k)}else if(Ve==="tool_complete"){let _=(bn=(On=fe(A,!1))!=null?On:fe(A,!0))!=null?bn:`tool-${l()}`;if(ee.has(_)){ee.delete(_);continue}let k=we(_),Y=(Lt=k.toolCall)!=null?Lt:{id:_,status:"running"};Y.status="complete",A.result!==void 0&&(Y.result=A.result),typeof A.duration=="number"&&(Y.duration=A.duration),Y.completedAt=ze((Yn=A.completedAt)!=null?Yn:A.timestamp);let K=(Zn=A.duration)!=null?Zn:A.executionTime;if(typeof K=="number")Y.durationMs=K;else{let Oe=($n=Y.startedAt)!=null?$n:Date.now();Y.durationMs=Math.max(0,(($r=Y.completedAt)!=null?$r:Date.now())-Oe)}k.toolCall=Y,k.streaming=!1;let J=A.agentContext;(J||A.executionId)&&(k.agentMetadata=(_n=k.agentMetadata)!=null?_n:{executionId:(Mr=J==null?void 0:J.executionId)!=null?Mr:A.executionId,iteration:(_r=J==null?void 0:J.iteration)!=null?_r:A.iteration}),g(k);let Xe=oe(A);Xe&&I.byCall.delete(Xe)}else if(Ve==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let _=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,k=(Wt=_!=null?_:A.toolId)!=null?Wt:`local-${l()}`,Y=we(k),K=(xn=Y.toolCall)!=null?xn:{id:k,status:"pending"};K.name=A.toolName,K.args=A.parameters,K.status="complete",K.chunks=(er=K.chunks)!=null?er:[],K.startedAt=(kr=K.startedAt)!=null?kr:ze((jr=A.startedAt)!=null?jr:A.timestamp),K.completedAt=(Ur=K.completedAt)!=null?Ur:K.startedAt,Y.toolCall=K,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(jn=A.executionId)!=null?jn:(vr=Y.agentMetadata)==null?void 0:vr.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},g(Y)}else if(Ve==="text_start"){if((lr=A.toolContext)!=null&&lr.toolId)continue;let _=A.partId;if(_!==void 0&&C.current!==null&&_!==C.current){let k=u;k&&(k.streaming=!1,g(k),re=k,u=null,T=!0)}_!==void 0&&(C.current=_)}else if(Ve==="text_end"){if((gt=A.toolContext)!=null&>.toolId)continue;let _=u;_&&(_.streaming=!1,g(_),re=_,u=null,T=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let _=A.stepType,k=A.executionType;if(_==="tool"||k==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let Oe=String((Gt=(Jt=A.id)!=null?Jt:Y.stepId)!=null?Gt:`step-${l()}`),et=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ee=`${Y.toolId}::${Oe}`,Je=W.get(Ee);if(et!==""&&Je!==void 0&&Je!==""&&Je!==et){let Ct=P.get(O(Y.toolId,Oe,Je));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,g(Ct))}et!==""&&W.set(Ee,et);let Pt=B(Y.toolId,Oe,et,Y.executionId),nn=(cr=(tr=(qr=(Un=A.text)!=null?Un:A.delta)!=null?qr:A.content)!=null?tr:A.chunk)!=null?cr:"";nn&&(Pt.content+=String(nn),Pt.streaming=!0,g(Pt)),A.isComplete&&(Pt.streaming=!1,g(Pt));continue}let K=A.partId;if(K!==void 0&&C.current!==null&&K!==C.current){let Oe=u;Oe&&(Oe.streaming=!1,g(Oe),re=Oe,u=null,T=!0)}K!==void 0&&(C.current=K);let J=K!==void 0&&(qn=ie.get(K))!=null?qn:Ne();K!==void 0&&(J.partId||(J.partId=K),ie.set(K,J));let Xe=(Lr=(dr=(zn=(S=A.text)!=null?S:A.delta)!=null?zn:A.content)!=null?dr:A.chunk)!=null?Lr:"";if(Xe){let Oe=typeof A.seq=="number"?A.seq:void 0,et=K!=null?K:J.id,Ee=Oe!==void 0?Qe(et,Oe,String(Xe)):((wr=se.get(J.id))!=null?wr:"")+Xe;J.rawContent=Ee,te.has(J.id)||te.set(J.id,this.createStreamParser());let Je=te.get(J.id),Pt=Ee.trim().startsWith("{")||Ee.trim().startsWith("[");if(Pt&&se.set(J.id,Ee),Je.__isPlainTextParser===!0){J.content=Oe!==void 0?Ee:J.content+Xe,se.delete(J.id),te.delete(J.id),J.rawContent=void 0,g(J);continue}let Ct=Je.processChunk(Ee);if(Ct instanceof Promise)Ct.then(Mt=>{var pn;let rn=typeof Mt=="string"?Mt:(pn=Mt==null?void 0:Mt.text)!=null?pn:null;if(rn!==null&&rn.trim()!=="")J.content=rn,g(J);else if(!Pt&&!Ee.trim().startsWith("<")){let wn=u,Xt=wn&&wn.id===J.id?wn:J;Xt.id===J.id&&(Xt.content=Oe!==void 0?Ee:Xt.content+Xe,se.delete(Xt.id),te.delete(Xt.id),Xt.rawContent=void 0,g(Xt))}}).catch(()=>{J.content=Oe!==void 0?Ee:J.content+Xe,se.delete(J.id),te.delete(J.id),J.rawContent=void 0,g(J)});else{let Mt=typeof Ct=="string"?Ct:(ss=Ct==null?void 0:Ct.text)!=null?ss:null;Mt!==null&&Mt.trim()!==""?(J.content=Mt,g(J)):!Pt&&!Ee.trim().startsWith("<")&&(J.content=Oe!==void 0?Ee:J.content+Xe,se.delete(J.id),te.delete(J.id),J.rawContent=void 0,g(J))}}if(A.isComplete){let Oe=(ur=(pr=A.result)==null?void 0:pr.response)!=null?ur:J.content;if(Oe){let et=se.get(J.id),Ee=et!=null?et:Q(Oe);J.rawContent=Ee;let Je=te.get(J.id),Pt=null,nn=!1;if(Je&&(Pt=Je.getExtractedText(),Pt===null&&(Pt=So(Ee)),Pt===null)){let Ct=Je.processChunk(Ee);Ct instanceof Promise?(nn=!0,Ct.then(Mt=>{var pn;let rn=typeof Mt=="string"?Mt:(pn=Mt==null?void 0:Mt.text)!=null?pn:null;if(rn!==null){let wn=u;wn&&wn.id===J.id&&(wn.content=rn,wn.streaming=!1,te.delete(wn.id),se.delete(wn.id),g(wn))}})):Pt=typeof Ct=="string"?Ct:(mr=Ct==null?void 0:Ct.text)!=null?mr:null}if(!nn){Pt!==null&&Pt.trim()!==""?J.content=Pt:se.has(J.id)||(J.content=Q(Oe));let Ct=te.get(J.id);if(Ct){let Mt=(Pr=Ct.close)==null?void 0:Pr.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),te.delete(J.id)}se.delete(J.id),J.streaming=!1,g(J)}}}}else if(Ve==="step_complete"){let _=A.stepType,k=A.executionType;if(_==="tool"||k==="context")continue;let Y=A.toolContext;if(Y!=null&&Y.toolId){let Oe=String((Zs=(uo=A.id)!=null?uo:Y.stepId)!=null?Zs:"");if(Oe){let et=$(Y.toolId,Oe);for(let[Ee,Je]of P)Ee.startsWith(et)&&Je.streaming!==!1&&(Je.streaming=!1,g(Je));W.delete(`${Y.toolId}::${Oe}`)}continue}let K=A.stopReason;if(T){if(u!==null){let Ee=u;K&&(Ee.stopReason=K),te.delete(Ee.id),se.delete(Ee.id),Ee.streaming!==!1&&(Ee.streaming=!1,g(Ee))}let Oe=(as=A.result)==null?void 0:as.response,et=re;et&&(K&&(et.stopReason=K),Oe!=null?Ie(et,Oe):(te.delete(et.id),se.delete(et.id))),re=null;continue}let J=(ea=A.result)==null?void 0:ea.response,Xe=Ne();if(K&&(Xe.stopReason=K),J!=null){let Oe=te.get(Xe.id),et=!1,Ee=!1;if(Oe){let Je=Oe.getExtractedText(),Pt=se.get(Xe.id),nn=Pt!=null?Pt:Q(J);if(Xe.rawContent=nn,Je!==null&&Je.trim()!=="")Xe.content=Je,et=!0;else{let Ct=So(nn);if(Ct!==null)Xe.content=Ct,et=!0;else{let Mt=Oe.processChunk(nn);if(Mt instanceof Promise)Ee=!0,Mt.then(rn=>{var wn;let pn=typeof rn=="string"?rn:(wn=rn==null?void 0:rn.text)!=null?wn:null;if(pn!==null&&pn.trim()!==""){let Xt=u;Xt&&Xt.id===Xe.id&&(Xt.content=pn,Xt.streaming=!1,te.delete(Xt.id),se.delete(Xt.id),g(Xt))}else{let Xt=Oe.getExtractedText(),rr=u;rr&&rr.id===Xe.id&&(Xt!==null&&Xt.trim()!==""?rr.content=Xt:se.has(rr.id)||(rr.content=Q(J)),rr.streaming=!1,te.delete(rr.id),se.delete(rr.id),g(rr))}});else{let rn=typeof Mt=="string"?Mt:(Wo=Mt==null?void 0:Mt.text)!=null?Wo:null;if(rn!==null&&rn.trim()!=="")Xe.content=rn,et=!0;else{let pn=Oe.getExtractedText();pn!==null&&pn.trim()!==""&&(Xe.content=pn,et=!0)}}}}}if(!Ee){if(!Xe.rawContent){let Je=se.get(Xe.id);Xe.rawContent=Je!=null?Je:Q(J)}if(!et&&!se.has(Xe.id)&&(Xe.content=Q(J)),Oe){let Je=(mt=Oe.close)==null?void 0:mt.call(Oe);Je instanceof Promise&&Je.catch(()=>{})}te.delete(Xe.id),se.delete(Xe.id),Xe.streaming=!1,g(Xe)}}else te.delete(Xe.id),se.delete(Xe.id),Xe.streaming=!1,g(Xe)}else if(Ve==="flow_complete"){let _=(is=A.result)==null?void 0:is.response;if(T){if(u!==null){let k=u;te.delete(k.id),se.delete(k.id),k.streaming!==!1&&(k.streaming=!1,g(k))}}else if(_!=null){let k=Ne(),Y=se.get(k.id),K=Y!=null?Y:Q(_);k.rawContent=K;let J=Q(_),Xe=te.get(k.id);if(Xe){let Ee=So(K);if(Ee!==null)J=Ee;else{let Je=Xe.processChunk(K);Je instanceof Promise&&Je.then(nn=>{var Mt;let Ct=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;Ct!==null&&(k.content=Ct,k.streaming=!1,g(k))});let Pt=Xe.getExtractedText();Pt!==null&&(J=Pt)}}te.delete(k.id),se.delete(k.id);let Oe=J!==k.content,et=k.streaming!==!1;Oe&&(k.content=J),k.streaming=!1,(Oe||et)&&g(k)}else if(u!==null){let k=u;te.delete(k.id),se.delete(k.id),k.streaming!==!1&&(k.streaming=!1,g(k))}n({type:"status",status:"idle"})}else if(Ve==="agent_start")ae={executionId:A.executionId,agentId:(nr=A.agentId)!=null?nr:"virtual",agentName:(Ln=A.agentName)!=null?Ln:"",status:"running",currentIteration:0,maxTurns:(ta=A.maxTurns)!=null?ta:1,startedAt:ze(A.startedAt)};else if(Ve==="agent_iteration_start"){if(ae&&(ae.currentIteration=A.iteration),Ot==="separate"&&A.iteration>1){let _=u;_&&(_.streaming=!1,g(_),Mn.set(A.iteration-1,_),u=null)}}else if(Ve==="agent_turn_start")v=null;else if(Ve==="agent_turn_delta"){if(A.contentType==="text"){let _=Ne();_.content+=(na=A.delta)!=null?na:"",_.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ae==null?void 0:ae.agentName},v=_,g(_)}else if(A.contentType==="thinking"){let _=(Ro=A.turnId)!=null?Ro:`agent-think-${A.iteration}`,k=Le(_);k.reasoning=(Ir=k.reasoning)!=null?Ir:{id:_,status:"streaming",chunks:[]},k.reasoning.chunks.push((ra=A.delta)!=null?ra:""),k.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},g(k)}else if(A.contentType==="tool_input"){let _=(mo=A.toolCallId)!=null?mo:I.lastId;if(_){let k=L.get(_);k!=null&&k.toolCall&&(k.toolCall.chunks=(ls=k.toolCall.chunks)!=null?ls:[],k.toolCall.chunks.push((Wr=A.delta)!=null?Wr:""),g(k))}}}else if(Ve==="agent_turn_complete"){let _=A.turnId;if(_){let K=H.get(_);if(K!=null&&K.reasoning){K.reasoning.status="complete",K.reasoning.completedAt=ze(A.completedAt);let J=(cs=K.reasoning.startedAt)!=null?cs:Date.now();K.reasoning.durationMs=Math.max(0,((zr=K.reasoning.completedAt)!=null?zr:Date.now())-J),K.streaming=!1,g(K)}}let k=A.stopReason,Y=u!=null?u:v;if(k&&Y!==null){let K=A.turnId;(!K||((Vr=Y.agentMetadata)==null?void 0:Vr.turnId)===K)&&(Y.stopReason=k,g(Y))}}else if(Ve==="agent_tool_start"){u&&(u.streaming=!1,g(u),u=null);let _=(oa=A.toolCallId)!=null?oa:`agent-tool-${l()}`;He(oe(A),_);let k=we(_),Y=(sa=k.toolCall)!=null?sa:{id:_,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(go=(wi=A.toolName)!=null?wi:A.name)!=null?go:Y.name,Y.status="running",A.parameters!==void 0&&(Y.args=A.parameters),Y.startedAt=ze((Kr=A.startedAt)!=null?Kr:A.timestamp),k.toolCall=Y,k.streaming=!0,k.agentMetadata={executionId:A.executionId,iteration:A.iteration},g(k)}else if(Ve==="agent_tool_delta"){let _=(aa=A.toolCallId)!=null?aa:I.lastId;if(_){let k=(ds=L.get(_))!=null?ds:we(_);k.toolCall&&(k.toolCall.chunks=(Jr=k.toolCall.chunks)!=null?Jr:[],k.toolCall.chunks.push((ia=A.delta)!=null?ia:""),k.toolCall.status="running",k.streaming=!0,g(k))}}else if(Ve==="agent_tool_complete"){let _=(ps=A.toolCallId)!=null?ps:I.lastId;if(_){let k=(Gr=L.get(_))!=null?Gr:we(_);if(k.toolCall){k.toolCall.status="complete",A.result!==void 0&&(k.toolCall.result=A.result),typeof A.executionTime=="number"&&(k.toolCall.durationMs=A.executionTime),k.toolCall.completedAt=ze((us=A.completedAt)!=null?us:A.timestamp),k.streaming=!1,g(k);let Y=oe(A);Y&&I.byCall.delete(Y)}}}else if(Ve==="agent_media"){let _=Array.isArray(A.media)?A.media:[],k=[];for(let Y of _){if(!Y||typeof Y!="object")continue;let K=Y,J=typeof K.type=="string"?K.type:void 0,Xe=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",Oe=null,et="";if(J==="media"){let Ee=typeof K.data=="string"?K.data:void 0;if(!Ee)continue;et=Xe.length>0?Xe:"application/octet-stream",Oe=`data:${et};base64,${Ee}`}else if(J==="image-url"){let Ee=typeof K.url=="string"?K.url:void 0;if(!Ee)continue;et=Xe,Oe=Ee}else if(J==="file-url"){let Ee=typeof K.url=="string"?K.url:void 0;if(!Ee)continue;et=Xe,Oe=Ee}else continue;if(Oe)if(J==="image-url"||et.startsWith("image/"))k.push({type:"image",image:Oe,...et?{mimeType:et}:{}});else if(et.startsWith("audio/"))k.push({type:"audio",audio:Oe,mimeType:et});else if(et.startsWith("video/"))k.push({type:"video",video:Oe,mimeType:et});else{let Ee=et||"application/octet-stream";k.push({type:"file",data:Oe,mimeType:Ee,filename:Qm(Ee)})}}if(k.length>0){let Y=l(),K=A.toolCallId,Xe={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(Xe);let Oe=u;Oe&&(Oe.streaming=!1,g(Oe)),u=null,x.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let _=`agent-reflection-${A.executionId}-${A.iteration}`,k={id:_,role:"assistant",content:(la=A.reflection)!=null?la:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"complete",chunks:[(Rr=A.reflection)!=null?Rr:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(k)}else if(Ve==="agent_complete"){ae&&(ae.status=A.success?"complete":"error",ae.completedAt=ze(A.completedAt),ae.stopReason=A.stopReason);let _=u;_&&(_.streaming=!1,g(_)),n({type:"status",status:"idle"})}else if(Ve==="agent_error"){let _=typeof A.error=="string"?A.error:(Xr=(ca=A.error)==null?void 0:ca.message)!=null?Xr:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",_):n({type:"error",error:new Error(_)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let _=(Rt=A.approvalId)!=null?Rt:`approval-${l()}`,k={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:"pending",agentId:(Ho=ae==null?void 0:ae.agentId)!=null?Ho:"virtual",executionId:(ms=(Bo=A.executionId)!=null?Bo:ae==null?void 0:ae.executionId)!=null?ms:"",toolName:(Cr=A.toolName)!=null?Cr:"",toolType:A.toolType,description:(gs=A.description)!=null?gs:`Execute ${(da=A.toolName)!=null?da:"tool"}`,parameters:A.parameters}};g(k)}else if(Ve==="step_await"&&A.awaitReason==="approval_required"){let _=(fs=A.approvalId)!=null?fs:`approval-${l()}`,k={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:"pending",agentId:(pa=ae==null?void 0:ae.agentId)!=null?pa:"virtual",executionId:(No=(Do=A.executionId)!=null?Do:ae==null?void 0:ae.executionId)!=null?No:"",toolName:(fo=A.toolName)!=null?fo:"",toolType:A.toolType,description:(ma=A.description)!=null?ma:`Execute ${(ua=A.toolName)!=null?ua:"tool"}`,parameters:A.parameters}};g(k)}else if(Ve==="agent_approval_complete"){let _=A.approvalId;if(_){let Y={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:_,status:(hs=A.decision)!=null?hs:"approved",agentId:(ys=ae==null?void 0:ae.agentId)!=null?ys:"virtual",executionId:(xs=(bs=A.executionId)!=null?bs:ae==null?void 0:ae.executionId)!=null?xs:"",toolName:(vn=A.toolName)!=null?vn:"",description:(Vn=A.description)!=null?Vn:"",resolvedAt:Date.now()}};g(Y)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let _=A.artifactType,k=String(A.id),Y=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:k,artifactType:_,title:Y,component:typeof A.component=="string"?A.component:void 0}),le.set(k,{markdown:"",title:Y}),!V.has(k)){V.add(k);let K={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Y,artifactType:_,status:"streaming"}})};Pe.set(k,K),g(K)}}else if(Ve==="artifact_delta"){let _=String(A.id),k=typeof A.delta=="string"?A.delta:String((Hr=A.delta)!=null?Hr:"");n({type:"artifact_delta",id:_,artDelta:k});let Y=le.get(_);Y&&(Y.markdown+=k)}else if(Ve==="artifact_update"){let _=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:_,component:typeof A.component=="string"?A.component:void 0})}else if(Ve==="artifact_complete"){let _=String(A.id);n({type:"artifact_complete",id:_});let k=Pe.get(_);if(k){k.streaming=!1;try{let Y=JSON.parse((ot=k.rawContent)!=null?ot:"{}");if(Y.props){Y.props.status="complete";let K=le.get(_);K!=null&&K.markdown&&(Y.props.markdown=K.markdown)}k.rawContent=JSON.stringify(Y)}catch{}le.delete(_),g(k),Pe.delete(_)}}}else if(Ve==="transcript_insert"){let _=A.message;if(!_||typeof _!="object")continue;let k=String((vs=_.id)!=null?vs:`msg-${l()}`),Y=_.role,J={id:k,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof _.content=="string"?_.content:"",rawContent:typeof _.rawContent=="string"?_.rawContent:void 0,createdAt:typeof _.createdAt=="string"?_.createdAt:new Date().toISOString(),streaming:_.streaming===!0,...typeof _.variant=="string"?{variant:_.variant}:{},sequence:l()};if(g(J),J.rawContent)try{let Xe=JSON.parse(J.rawContent),Oe=(ho=Xe==null?void 0:Xe.props)==null?void 0:ho.artifactId;typeof Oe=="string"&&V.add(Oe)}catch{}u=null,x.current=null,te.delete(k),se.delete(k)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let _=null;if(A.error instanceof Error)_=A.error;else if(Ve==="dispatch_error"){let k=(gr=A.message)!=null?gr:A.error;k!=null&&k!==""&&(_=new Error(String(k)))}else if(Ve==="step_error"||Ve==="flow_error"){let k=A.error;typeof k=="string"&&k!==""?_=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&(_=new Error(String((ga=k.message)!=null?ga:k)))}else Ve==="error"&&A.error!=null&&A.error!==""&&(_=new Error(String(A.error)));if(_){n({type:"error",error:_});let k=u;k&&k.streaming&&(k.streaming=!1,g(k)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:N,value:Ae}=await s.read();if(N)break;a+=o.decode(Ae,{stream:!0});let Be=a.split(`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},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(`
|
|
10
10
|
|
|
11
|
-
`);a=(Hn=
|
|
12
|
-
`),dt="message",rt="";for(let q of _e)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(rt+=q.replace("data:","").trim());if(!rt)continue;let At;try{At=JSON.parse(rt)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let _t=dt!=="message"?dt:(Xn=At.type)!=null?Xn:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,_t,At),this.parseSSEEvent){x.current=u;let q=await this.handleCustomSSEEvent(At,n,x,g,l,C);if(x.current&&x.current!==u&&(u=x.current),q)continue}de.push(_t,At),$e()}}de.flushPending(),$e(),de.destroy()}};function eg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ls(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function zo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Pa="[Image]";function tg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ng(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function rg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function og(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ia(e){return{type:"text",text:e}}function sg(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function ag(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function ig(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Hp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],lg=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Nr=[...Hp,...lg];function cg(e){return Hp.includes(e)||e.startsWith("image/")}function Wa(e){return cg(e.type)}async function Bp(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Wa(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Dp(e,t=Nr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function dg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Np(e,t){let n=dg(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ra=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ha=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ha;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let v=!1,x=T=>{v||(v=!0,clearTimeout(C),u(new Error(T)))},C=setTimeout(()=>x("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(C),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!v){let H=T.code!==1006?` (code ${T.code})`:"";x("WebSocket connection failed"+H+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ra(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var To=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ps(e.runtype);case"browser":if(!To.isSupported())throw new Error("Browser speech recognition not supported");return new To(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Li(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Vo({type:"runtype",runtype:e.runtype});if(To.isSupported())return Vo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ba(e){try{return Li(e),!0}catch{return!1}}function Fp(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
|
|
11
|
+
`);a=(Hn=De.pop())!=null?Hn:"";for(let Ne of De){let je=Ne.split(`
|
|
12
|
+
`),dt="message",rt="";for(let q of je)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(rt+=q.replace("data:","").trim());if(!rt)continue;let At;try{At=JSON.parse(rt)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let _t=dt!=="message"?dt:(Xn=At.type)!=null?Xn:"message";if((qe=this.onSSEEvent)==null||qe.call(this,_t,At),this.parseSSEEvent){x.current=u;let q=await this.handleCustomSSEEvent(At,n,x,g,l,C);if(x.current&&x.current!==u&&(u=x.current),q)continue}de.push(_t,At),_e()}}de.flushPending(),_e(),de.destroy()}};function ng(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ps(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Vo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ia="[Image]";function rg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function og(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function sg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ag(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Wa(e){return{type:"text",text:e}}function ig(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function lg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function cg(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Bp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],dg=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Nr=[...Bp,...dg];function pg(e){return Bp.includes(e)||e.startsWith("image/")}function Ra(e){return pg(e.type)}async function Dp(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ra(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Np(e,t=Nr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function ug(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Fp(e,t){let n=ug(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ha=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ba=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Is=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ba;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let v=!1,x=T=>{v||(v=!0,clearTimeout(C),u(new Error(T)))},C=setTimeout(()=>x("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(C),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!v){let H=T.code!==1006?` (code ${T.code})`:"";x("WebSocket connection failed"+H+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ha(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Eo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ko(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Is(e.runtype);case"browser":if(!Eo.isSupported())throw new Error("Browser speech recognition not supported");return new Eo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Pi(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ko({type:"runtype",runtype:e.runtype});if(Eo.isSupported())return Ko({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Da(e){try{return Pi(e),!0}catch{return!1}}function Op(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
|
|
13
13
|
|
|
14
|
-
_Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,r,s,o,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Aa(p.name)&&this.enqueueWebMcpAwait(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new qo(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ba((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,s;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Vo(o);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,g,u,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let C=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:v.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,l,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((s=t.runtype)==null?void 0:s.clientToken)||"",host:(o=t.runtype)==null?void 0:o.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new qo(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=t,u={id:a!=null?a:n==="user"?Ls():n==="assistant"?zo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:s==="user"?Ls():s==="assistant"?zo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,l={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,m,g,u;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=Ls(),o=zo(),a={id:s,role:"user",content:r||Pa,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let C=Fp(v,this.config.errorMessage);if(C){let T={id:o,role:"assistant",createdAt:new Date().toISOString(),content:C,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=zo();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Fp(l,this.config.errorMessage);if(m){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n){var d,l,p,m;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let u=null;if(g instanceof Response){if(!g.ok){let v=await g.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${g.status}`)}u=g.body}else g instanceof ReadableStream&&(u=g);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let u=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,g,u,v,x,C,T,H,L,P,W;let r=this.messages.find(w=>w.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(g=t.toolCall)==null?void 0:g.name;if(!s||!o){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let w=(x=t.toolCall)==null?void 0:x.args,I=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(I.length===1){let O=typeof((C=I[0])==null?void 0:C.question)=="string"?I[0].question:"";O&&(a={[O]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(H=t.toolCall)==null?void 0:H.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof n=="string"?n:Object.entries(n).map(([I,O])=>`${I}: ${Array.isArray(O)?O.join(", "):O}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((I,O)=>{let $=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!$)return;let B=w[$],j=Array.isArray(B)?B.join(", "):typeof B=="string"?B:"";this.appendMessage({id:`ask-user-q-${i}-${O}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${O}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:n});if(!w.ok){let I=await w.json().catch(()=>null);throw new Error((L=I==null?void 0:I.error)!=null?L:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let I=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(W=(P=this.callbacks).onError)==null||W.call(P,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{var H,L,P,W,w,I,O;let m=(H=p.toolCall)==null?void 0:H.name,g=(L=p.toolCall)==null?void 0:L.id;if(!m||!g)return null;let u=`${t}:${g}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u))return null;this.webMcpInflightKeys.add(u),r.push(u),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let v=new AbortController;this.webMcpResolveControllers.add(v),s.push(v);let x=(W=(P=p.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?W:m,C=this.client.executeWebMcpToolCall(m,(w=p.toolCall)==null?void 0:w.args,v.signal),T;if(!C)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await C}catch($){return $ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"))||(O=(I=this.callbacks).onError)==null||O.call(I,$ instanceof Error?$:new Error(String($))),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:x,output:T}}));try{let p=a.filter(u=>u!==null);if(p.length===0)return;let m={};for(let u of p)m[u.resumeKey]=u.output;let g=await this.client.resumeFlow(t,m,{signal:o.signal});if(!g.ok){let u=await g.json().catch(()=>null);throw new Error((i=u==null?void 0:u.error)!=null?i:`Resume failed: ${g.status}`)}for(let u of p)this.webMcpResolvedKeys.add(u.dedupeKey);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of r)this.webMcpInflightKeys.delete(p);for(let p of s)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,m,g,u,v,x,C,T,H,L,P,W;let n=(p=t.agentMetadata)==null?void 0:p.executionId,r=(m=t.toolCall)==null?void 0:m.name,s=(g=t.toolCall)==null?void 0:g.id;if(!n){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let w=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(w)}catch(I){(C=(x=this.callbacks).onError)==null||C.call(x,I instanceof Error?I:new Error(String(I)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(T=t.toolCall)==null?void 0:T.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let w;if(l?w=await l:w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let I=(L=(H=t.agentMetadata)==null?void 0:H.webMcpToolCallId)!=null?L:r;await this.resumeWithToolOutput(n,I,w,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(w){w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"))||(W=(P=this.callbacks).onError)==null||W.call(P,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t),o=r.getVoices();if(n.voice){let a=o.find(i=>i.name===n.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=n.pickVoice?n.pickVoice(o):e.pickBestVoice(o));n.rate!==void 0&&(s.rate=n.rate),n.pitch!==void 0&&(s.pitch=n.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(t){var r;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of n){let o=t.find(a=>a.name===s);if(o)return o}return(r=t.find(s=>s.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,g,u,v,x;if(o!==r)return s;let a={...s,...n};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=n.toolCall)==null?void 0:m.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&Aa(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let C=`${d}:${l}`;(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Sr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import{Activity as pg,ArrowDown as ug,ArrowUp as mg,ArrowUpRight as gg,Bot as fg,ChevronDown as hg,ChevronUp as yg,ChevronRight as bg,ChevronLeft as xg,Check as vg,Clipboard as wg,ClipboardCopy as Cg,Copy as Ag,File as Sg,FileCode as Tg,FileSpreadsheet as Eg,FileText as Mg,ImagePlus as kg,Loader as Lg,LoaderCircle as Pg,Mic as Ig,Paperclip as Wg,RefreshCw as Rg,Search as Hg,Send as Bg,ShieldAlert as Dg,ShieldCheck as Ng,ShieldX as Fg,Square as Og,ThumbsDown as $g,ThumbsUp as _g,Upload as jg,Volume2 as Ug,X as qg,User as zg,Mail as Vg,Phone as Kg,Calendar as Jg,Clock as Gg,Building as Xg,MapPin as Qg,Lock as Yg,Key as Zg,CreditCard as ef,AtSign as tf,Hash as nf,Globe as rf,Link as of,CircleCheck as sf,CircleX as af,TriangleAlert as lf,Info as cf,Ban as df,Shield as pf,ArrowLeft as uf,ArrowRight as mf,ExternalLink as gf,Ellipsis as ff,EllipsisVertical as hf,Menu as yf,House as bf,Plus as xf,Minus as vf,Pencil as wf,Trash as Cf,Trash2 as Af,Save as Sf,Download as Tf,Share as Ef,Funnel as Mf,Settings as kf,RotateCw as Lf,Maximize as Pf,Minimize as If,ShoppingCart as Wf,ShoppingBag as Rf,Package as Hf,Truck as Bf,Tag as Df,Gift as Nf,Receipt as Ff,Wallet as Of,Store as $f,DollarSign as _f,Percent as jf,Play as Uf,Pause as qf,VolumeX as zf,Camera as Vf,Image as Kf,Film as Jf,Headphones as Gf,MessageCircle as Xf,MessageSquare as Qf,Bell as Yf,Heart as Zf,Star as eh,Eye as th,EyeOff as nh,Bookmark as rh,CalendarDays as oh,History as sh,Timer as ah,Folder as ih,FolderOpen as lh,Files as ch,Sparkles as dh,Zap as ph,Sun as uh,Moon as mh,Flag as gh,Monitor as fh,Smartphone as hh}from"lucide";var yh={activity:pg,"arrow-down":ug,"arrow-up":mg,"arrow-up-right":gg,bot:fg,"chevron-down":hg,"chevron-up":yg,"chevron-right":bg,"chevron-left":xg,check:vg,clipboard:wg,"clipboard-copy":Cg,copy:Ag,file:Sg,"file-code":Tg,"file-spreadsheet":Eg,"file-text":Mg,"image-plus":kg,loader:Lg,"loader-circle":Pg,mic:Ig,paperclip:Wg,"refresh-cw":Rg,search:Hg,send:Bg,"shield-alert":Dg,"shield-check":Ng,"shield-x":Fg,square:Og,"thumbs-down":$g,"thumbs-up":_g,upload:jg,"volume-2":Ug,x:qg,user:zg,mail:Vg,phone:Kg,calendar:Jg,clock:Gg,building:Xg,"map-pin":Qg,lock:Yg,key:Zg,"credit-card":ef,"at-sign":tf,hash:nf,globe:rf,link:of,"circle-check":sf,"circle-x":af,"triangle-alert":lf,info:cf,ban:df,shield:pf,"arrow-left":uf,"arrow-right":mf,"external-link":gf,ellipsis:ff,"ellipsis-vertical":hf,menu:yf,house:bf,plus:xf,minus:vf,pencil:wf,trash:Cf,"trash-2":Af,save:Sf,download:Tf,share:Ef,funnel:Mf,settings:kf,"rotate-cw":Lf,maximize:Pf,minimize:If,"shopping-cart":Wf,"shopping-bag":Rf,package:Hf,truck:Bf,tag:Df,gift:Nf,receipt:Ff,wallet:Of,store:$f,"dollar-sign":_f,percent:jf,play:Uf,pause:qf,"volume-x":zf,camera:Vf,image:Kf,film:Jf,headphones:Gf,"message-circle":Xf,"message-square":Qf,bell:Yf,heart:Zf,star:eh,eye:th,"eye-off":nh,bookmark:rh,"calendar-days":oh,history:sh,timer:ah,folder:ih,"folder-open":lh,files:ch,sparkles:dh,zap:ph,sun:uh,moon:mh,flag:gh,monitor:fh,smartphone:hh},be=(e,t=24,n="currentColor",r=2)=>{let s=yh[e];return s?bh(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function bh(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var Da={allowedTypes:Nr,maxFileSize:10*1024*1024,maxFiles:4};function xh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vh(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Ko=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Da.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Da.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Da.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Da.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=Dp(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,m);continue}try{let m=await Bp(l),g=Wa(l)?URL.createObjectURL(l):null,u={id:xh(),file:l,previewUrl:g,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Wa(t.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=h("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=vh(t.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Np(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=be("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Op=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ws(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];Op(o)&&Op(s)?n[r]=Ws(o,s):n[r]=s}return n}var sr="min(440px, calc(100vw - 24px))",Pi="440px",Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:sr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function $p(e,t){if(!(!e&&!t))return e?t?Ws(e,t):e:t}function Ii(e){var t,n,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,L,P,W;return e?{...Ft,...e,theme:$p(Ft.theme,e.theme),darkTheme:$p(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(t=Ft.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var ye,Le,He,ee,Pe,V,le,ve;let w=(ye=Ft.features)==null?void 0:ye.artifacts,I=(Le=e.features)==null?void 0:Le.artifacts,O=(He=Ft.features)==null?void 0:He.scrollToBottom,$=(ee=e.features)==null?void 0:ee.scrollToBottom,B=(Pe=Ft.features)==null?void 0:Pe.streamAnimation,j=(V=e.features)==null?void 0:V.streamAnimation,z=(le=Ft.features)==null?void 0:le.askUserQuestion,oe=(ve=e.features)==null?void 0:ve.askUserQuestion,We=w===void 0&&I===void 0?void 0:{...w,...I,layout:{...w==null?void 0:w.layout,...I==null?void 0:I.layout}},je=O===void 0&&$===void 0?void 0:{...O,...$},Ne=B===void 0&&j===void 0?void 0:{...B,...j},ge=z===void 0&&oe===void 0?void 0:{...z,...oe,styles:{...z==null?void 0:z.styles,...oe==null?void 0:oe.styles}};return{...Ft.features,...e.features,...je!==void 0?{scrollToBottom:je}:{},...We!==void 0?{artifacts:We}:{},...Ne!==void 0?{streamAnimation:Ne}:{},...ge!==void 0?{askUserQuestion:ge}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=Ft.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(g=e.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Ft.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(C=e.layout)==null?void 0:C.messages)==null?void 0:T.timestamp}},slots:{...(H=Ft.layout)==null?void 0:H.slots,...(L=e.layout)==null?void 0:L.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(P=Ft.markdown)==null?void 0:P.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}var _p={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},jp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Up={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:sr,maxWidth:Pi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Jo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Jo(e,r):r}function Wi(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Jo(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function qp(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function zp(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=zp(o,s):n[r]=s}return n}function wh(e,t){return t?zp(e,t):e}function Rs(e,t={}){var s,o,a,i,d,l,p,m,g,u,v,x,C;let n={palette:_p,semantic:jp,components:Up},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:wh(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=qp(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(H=>H.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function Ri(e){var x,C,T,H,L,P,W,w,I,O,$,B,j,z,oe,We,je,Ne,ge,ye,Le,He,ee,Pe,V,le,ve,fe,we,ze,Q,te,se,ue,ie,re,Qe,Ie,ce,G,$e,Et,de,ae,Mn,Ot,ln,Hn,Xn,Ue,N,Ae,Be,De,_e,dt,rt,At,_t,q,$t,Ye,Dt,ne,me,vt,jt,Zt,hn,St,wt,ft,yt,zt,tt,Bn,Qn,yn,Dn,ut,xr,Nn,po,kn,Io,Or,Er,bt,Fn,On,bn,Lt,Yn,Zn,$n,$r,Mr,_r,_n,Wt,xn,er,jr,kr,Ur,vr,jn,lr,gt,Jt,Gt,Un,qr,tr,cr,qn;let t=Wi(e),n={};for(let[S,zn]of Object.entries(t)){let dr=S.replace(/\./g,"-");n[`--persona-${dr}`]=zn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(C=n["--persona-semantic-colors-secondary"])!=null?C:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(H=n["--persona-semantic-colors-surface"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(L=n["--persona-semantic-colors-background"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(P=n["--persona-semantic-colors-container"])!=null?P:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(w=n["--persona-semantic-colors-text-muted"])!=null?w:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(O=n["--persona-semantic-colors-border"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=($=n["--persona-semantic-colors-divider"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(B=n["--persona-components-voice-recording-indicator"])!=null?B:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(oe=n["--persona-components-voice-speaking-icon"])!=null?oe:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(We=n["--persona-components-approval-requested-background"])!=null?We:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(je=n["--persona-components-approval-requested-border"])!=null?je:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ne=n["--persona-components-approval-requested-text"])!=null?Ne:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ge=n["--persona-components-approval-approve-background"])!=null?ge:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(ye=n["--persona-components-approval-deny-background"])!=null?ye:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Le=n["--persona-components-attachment-image-background"])!=null?Le:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(He=n["--persona-components-attachment-image-border"])!=null?He:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ee=n["--persona-semantic-typography-fontFamily"])!=null?ee:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Pe=n["--persona-semantic-typography-fontSize"])!=null?Pe:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(V=n["--persona-semantic-typography-fontWeight"])!=null?V:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(le=n["--persona-semantic-typography-lineHeight"])!=null?le:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(ve=n["--persona-palette-radius-sm"])!=null?ve:"0.125rem",n["--persona-radius-md"]=(fe=n["--persona-palette-radius-md"])!=null?fe:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(ze=n["--persona-palette-radius-xl"])!=null?ze:"0.75rem",n["--persona-radius-full"]=(Q=n["--persona-palette-radius-full"])!=null?Q:"9999px",n["--persona-launcher-radius"]=(se=(te=n["--persona-components-launcher-borderRadius"])!=null?te:n["--persona-palette-radius-full"])!=null?se:"9999px",n["--persona-launcher-bg"]=(ue=n["--persona-components-launcher-background"])!=null?ue:n["--persona-primary"],n["--persona-launcher-fg"]=(ie=n["--persona-components-launcher-foreground"])!=null?ie:n["--persona-text-inverse"],n["--persona-launcher-border"]=(re=n["--persona-components-launcher-border"])!=null?re:n["--persona-border"],n["--persona-button-primary-bg"]=(Qe=n["--persona-components-button-primary-background"])!=null?Qe:n["--persona-primary"],n["--persona-button-primary-fg"]=(Ie=n["--persona-components-button-primary-foreground"])!=null?Ie:n["--persona-text-inverse"],n["--persona-button-radius"]=(G=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?G:"9999px",n["--persona-panel-radius"]=(Et=($e=n["--persona-components-panel-borderRadius"])!=null?$e:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(de=n["--persona-components-panel-border"])!=null?de:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Mn=(ae=n["--persona-components-panel-shadow"])!=null?ae:n["--persona-palette-shadows-xl"])!=null?Mn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Ot=n["--persona-components-input-borderRadius"])!=null?Ot:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Xn=(Hn=n["--persona-components-message-user-borderRadius"])!=null?Hn:n["--persona-radius-lg"])!=null?Xn:"0.5rem",n["--persona-message-assistant-radius"]=(N=(Ue=n["--persona-components-message-assistant-borderRadius"])!=null?Ue:n["--persona-radius-lg"])!=null?N:"0.5rem",n["--persona-header-bg"]=(Ae=n["--persona-components-header-background"])!=null?Ae:n["--persona-surface"],n["--persona-header-border"]=(Be=n["--persona-components-header-border"])!=null?Be:n["--persona-divider"],n["--persona-header-icon-bg"]=(De=n["--persona-components-header-iconBackground"])!=null?De:n["--persona-primary"],n["--persona-header-icon-fg"]=(_e=n["--persona-components-header-iconForeground"])!=null?_e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(dt=n["--persona-components-header-titleForeground"])!=null?dt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(rt=n["--persona-components-header-subtitleForeground"])!=null?rt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(At=n["--persona-components-header-actionIconForeground"])!=null?At:n["--persona-muted"];let r=(_t=e.components)==null?void 0:_t.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=($t=n["--persona-components-introCard-background"])!=null?$t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ye=n["--persona-components-introCard-borderRadius"])!=null?Ye:"1rem",n["--persona-intro-card-padding"]=(Dt=n["--persona-components-introCard-padding"])!=null?Dt:"1.5rem",n["--persona-intro-card-shadow"]=(me=(ne=s==null?void 0:s.shadow)!=null?ne:n["--persona-components-introCard-shadow"])!=null?me:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(vt=n["--persona-components-input-background"])!=null?vt:n["--persona-surface"],n["--persona-input-placeholder"]=(jt=n["--persona-components-input-placeholder"])!=null?jt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Zt=n["--persona-components-message-user-background"])!=null?Zt:n["--persona-accent"],n["--persona-message-user-text"]=(hn=n["--persona-components-message-user-text"])!=null?hn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(St=n["--persona-components-message-user-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(wt=n["--persona-components-message-assistant-background"])!=null?wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(ft=n["--persona-components-message-assistant-text"])!=null?ft:n["--persona-text"],n["--persona-message-assistant-border"]=(yt=n["--persona-components-message-assistant-border"])!=null?yt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Bn=(tt=n["--persona-components-scrollToBottom-background"])!=null?tt:n["--persona-button-primary-bg"])!=null?Bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(yn=(Qn=n["--persona-components-scrollToBottom-foreground"])!=null?Qn:n["--persona-button-primary-fg"])!=null?yn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Dn=n["--persona-components-scrollToBottom-border"])!=null?Dn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(po=(Nn=(xr=n["--persona-components-scrollToBottom-borderRadius"])!=null?xr:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?po:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Io=(kn=n["--persona-components-scrollToBottom-shadow"])!=null?kn:n["--persona-palette-shadows-sm"])!=null?Io:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Or=n["--persona-components-scrollToBottom-padding"])!=null?Or:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Er=n["--persona-components-scrollToBottom-gap"])!=null?Er:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Fn=(bt=n["--persona-components-scrollToBottom-fontSize"])!=null?bt:n["--persona-palette-typography-fontSize-sm"])!=null?Fn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(On=n["--persona-components-scrollToBottom-iconSize"])!=null?On:"14px",n["--persona-tool-bubble-shadow"]=(bn=n["--persona-components-toolBubble-shadow"])!=null?bn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Lt=n["--persona-components-reasoningBubble-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Yn=n["--persona-components-composer-shadow"])!=null?Yn:"none",n["--persona-md-inline-code-bg"]=(Zn=n["--persona-components-markdown-inlineCode-background"])!=null?Zn:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Mr=($r=n["--persona-components-markdown-link-foreground"])!=null?$r:n["--persona-accent"])!=null?Mr:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(_r=n["--persona-components-markdown-codeBlock-background"])!=null?_r:n["--persona-container"],n["--persona-md-code-block-border-color"]=(_n=n["--persona-components-markdown-codeBlock-borderColor"])!=null?_n:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(xn=n["--persona-components-markdown-table-headerBackground"])!=null?xn:n["--persona-container"],n["--persona-md-table-border-color"]=(er=n["--persona-components-markdown-table-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-hr-color"]=(jr=n["--persona-components-markdown-hr-color"])!=null?jr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(kr=n["--persona-components-markdown-blockquote-borderColor"])!=null?kr:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Ur=n["--persona-components-markdown-blockquote-background"])!=null?Ur:"transparent",n["--persona-md-blockquote-text-color"]=(vr=n["--persona-components-markdown-blockquote-textColor"])!=null?vr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(jn=n["--persona-components-collapsibleWidget-container"])!=null?jn:n["--persona-surface"],n["--cw-surface"]=(lr=n["--persona-components-collapsibleWidget-surface"])!=null?lr:n["--persona-surface"],n["--cw-border"]=(gt=n["--persona-components-collapsibleWidget-border"])!=null?gt:n["--persona-border"],n["--persona-message-border"]=(Jt=n["--persona-components-message-border"])!=null?Jt:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let S=v.toolbar;S.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=S.iconHoverColor),S.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=S.iconHoverBackground),S.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=S.iconPadding),S.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=S.iconBorderRadius),S.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=S.iconBorder),S.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=S.toggleGroupGap),S.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=S.toggleBorderRadius),S.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=S.copyBackground),S.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=S.copyBorder),S.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=S.copyColor),S.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=S.copyBorderRadius),S.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=S.copyPadding),S.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=S.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:S.copyMenuBackground),S.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=S.copyMenuBorder,n["--persona-dropdown-border"]=(Un=n["--persona-dropdown-border"])!=null?Un:S.copyMenuBorder),S.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=S.copyMenuShadow,n["--persona-dropdown-shadow"]=(qr=n["--persona-dropdown-shadow"])!=null?qr:S.copyMenuShadow),S.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=S.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(tr=n["--persona-dropdown-radius"])!=null?tr:S.copyMenuBorderRadius),S.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=S.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(cr=n["--persona-dropdown-item-hover-bg"])!=null?cr:S.copyMenuItemHoverBackground),S.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=S.iconBackground),S.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=S.toolbarBorder)}if(v!=null&&v.tab){let S=v.tab;S.background&&(n["--persona-artifact-tab-bg"]=S.background),S.activeBackground&&(n["--persona-artifact-tab-active-bg"]=S.activeBackground),S.activeBorder&&(n["--persona-artifact-tab-active-border"]=S.activeBorder),S.borderRadius&&(n["--persona-artifact-tab-radius"]=S.borderRadius),S.textColor&&(n["--persona-artifact-tab-color"]=S.textColor),S.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=S.hoverBackground),S.listBackground&&(n["--persona-artifact-tab-list-bg"]=S.listBackground),S.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=S.listBorderColor),S.listPadding&&(n["--persona-artifact-tab-list-padding"]=S.listPadding)}if(v!=null&&v.pane){let S=v.pane;if(S.toolbarBackground){let zn=(qn=Jo(e,S.toolbarBackground))!=null?qn:S.toolbarBackground;n["--persona-artifact-toolbar-bg"]=zn}}return n}var Ch={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Ah={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Vp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Na=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Sh=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Na()},Kp=e=>Sh(e),Th=e=>Rs(e),Eh=e=>{var n;let t=Rs(void 0,{validate:!1});return Rs({...e,palette:{...t.palette,colors:{...Ah.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Hs=e=>{let t=Kp(e),n=Vp(e==null?void 0:e.theme),r=Vp(e==null?void 0:e.darkTheme);return t==="dark"?Eh(Ws(n!=null?n:{},r!=null?r:{})):Th(n)},Mh=e=>Ri(e),Eo=(e,t)=>{var o;let n=Hs(t),r=Mh(n);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=t==null?void 0:t.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Hi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Na())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Na());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as kh}from"idiomorph";var Fa=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;kh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Oa={index:-1,draft:""};function Jp(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...Oa}}}function Gp(e,t){var n,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,L,P,W,w,I,O,$,B,j,z,oe,We,je,Ne,ge,ye,Le,He,ee,Pe,V;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(v=(u=e.toolCall)==null?void 0:u.status)!=null?v:"",(C=(x=e.toolCall)==null?void 0:x.name)!=null?C:"",(L=(H=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:H.length)!=null?L:0,(I=(w=(W=(P=e.toolCall)==null?void 0:P.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?I:"",typeof((O=e.toolCall)==null?void 0:O.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(z=(j=(B=e.reasoning)==null?void 0:B.chunks)==null?void 0:j.length)!=null?z:0,(Ne=(je=(We=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:je.length)!=null?Ne:0,(He=(Le=(ye=(ge=e.reasoning)==null?void 0:ge.chunks)==null?void 0:ye[e.reasoning.chunks.length-1])==null?void 0:Le.slice(-32))!=null?He:"",(Pe=(ee=e.contentParts)==null?void 0:ee.length)!=null?Pe:0,(V=e.stopReason)!=null?V:"",t].join("\0")}function Xp(){return new Map}function Qp(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Yp(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Zp(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function $a(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Bs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ds(e,t){return Bs(e)-e.scrollTop<=t}function _a(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function ja(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var gn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},fn=1e5,eo=fn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Lh=["pre","code","a","script","style"],Ua=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ns.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ns.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ns.buffer}},tu=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Fs=new Map;for(let e of tu)Fs.set(e.name,e);var Ph=e=>{Fs.set(e.name,e)},Ih=e=>{tu.some(t=>t.name===e)||Fs.delete(e)},Wh=()=>Array.from(Fs.keys()),Os=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Fs.get(e))!=null?r:null},qa=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
|
|
15
|
-
`);return o<0?"":e.slice(0,o)}return e},
|
|
14
|
+
_Details: ${n.message}_`:r}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]}),$p=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Rs=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,r,s,o,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&So(p.name)&&this.enqueueWebMcpAwait(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new zo(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Da((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,s;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Ko(o);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,g,u,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let C=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:v.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,l,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((s=t.runtype)==null?void 0:s.clientToken)||"",host:(o=t.runtype)==null?void 0:o.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new zo(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=t,u={id:a!=null?a:n==="user"?Ps():n==="assistant"?Vo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:s==="user"?Ps():s==="assistant"?Vo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,l={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,m,g,u;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=Ps(),o=Vo(),a={id:s,role:"user",content:r||Ia,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let C=Op(v,this.config.errorMessage);if(C){let T={id:o,role:"assistant",createdAt:new Date().toISOString(),content:C,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=Vo();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Op(l,this.config.errorMessage);if(m){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n){var d,l,p,m;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let u=null;if(g instanceof Response){if(!g.ok){let v=await g.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${g.status}`)}u=g.body}else g instanceof ReadableStream&&(u=g);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let u=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,g,u,v,x,C,T,H,k,P,W;let r=this.messages.find(A=>A.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(g=t.toolCall)==null?void 0:g.name;if(!s||!o){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let A=(x=t.toolCall)==null?void 0:x.args,I=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(I.length===1){let O=typeof((C=I[0])==null?void 0:C.question)=="string"?I[0].question:"";O&&(a={[O]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(H=t.toolCall)==null?void 0:H.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let A=typeof n=="string"?n:Object.entries(n).map(([I,O])=>`${I}: ${Array.isArray(O)?O.join(", "):O}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};l.forEach((I,O)=>{let D=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!D)return;let R=A[D],_=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${O}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${O}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(s,{[o]:n});if(!A.ok){let I=await A.json().catch(()=>null);throw new Error((k=I==null?void 0:I.error)!=null?k:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let I=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(W=(P=this.callbacks).onError)==null||W.call(P,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,s=Date.now()){this.messages.some(o=>o.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async m=>{var P,W,A,I,O,D,R;let g=(P=m.toolCall)==null?void 0:P.name,u=(W=m.toolCall)==null?void 0:W.id;if(!g||!u)return null;let v=`${t}:${u}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return null;this.webMcpInflightKeys.add(v),r.push(v);let x=this.markWebMcpToolRunning(m),C=new AbortController;this.webMcpResolveControllers.add(C),s.push(C);let T=(I=(A=m.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?I:g,H=this.client.executeWebMcpToolCall(g,(O=m.toolCall)==null?void 0:O.args,C.signal),k;if(!H)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await H}catch(_){let z=_ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"));return z||(R=(D=this.callbacks).onError)==null||R.call(D,_ instanceof Error?_:new Error(String(_))),this.markWebMcpToolComplete(m,Ws(z?"Aborted by cancel()":$p(_)),x),this.webMcpInflightKeys.delete(v),null}return C.signal.aborted?(this.markWebMcpToolComplete(m,Ws("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:k,toolMessage:m,startedAt:x,completedAt:Date.now()}})),i=[];try{if(i=a.filter(u=>u!==null),i.length===0)return;let m={};for(let u of i)m[u.resumeKey]=u.output;let g=await this.client.resumeFlow(t,m,{signal:o.signal});if(!g.ok){let u=await g.json().catch(()=>null);throw new Error((d=u==null?void 0:u.error)!=null?d:`Resume failed: ${g.status}`)}for(let u of i)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(m){if(!(m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"))))(p=(l=this.callbacks).onError)==null||p.call(l,m instanceof Error?m:new Error(String(m)));else for(let u of i)this.markWebMcpToolComplete(u.toolMessage,Ws("Aborted by cancel()"),u.startedAt)}finally{for(let m of r)this.webMcpInflightKeys.delete(m);for(let m of s)this.webMcpResolveControllers.delete(m);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,v,x,C,T,H,k,P,W,A,I,O;let n=(u=t.agentMetadata)==null?void 0:u.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(x=t.toolCall)==null?void 0:x.id;if(!n){(T=(C=this.callbacks).onError)==null||T.call(C,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let D=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(D)||this.webMcpResolvedKeys.has(D))return;this.webMcpInflightKeys.add(D);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(D)}catch(R){(k=(H=this.callbacks).onError)==null||k.call(H,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(D)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(P=t.toolCall)==null?void 0:P.args,p=this.client.executeWebMcpToolCall(r,l,d),m="execute",g=a;try{let D;if(p?D=await p:D={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ws("Aborted by cancel()"),a);return}let R=(A=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?A:r;m="resume",await this.resumeWithToolOutput(n,R,D,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,D,a,g)},signal:d})}catch(D){let R=D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")||D.message.includes("abort"));(m==="execute"||R||d.aborted)&&this.markWebMcpToolComplete(t,Ws(R||d.aborted?"Aborted by cancel()":$p(D)),a),R||(O=(I=this.callbacks).onError)==null||O.call(I,D instanceof Error?D:new Error(String(D)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t),o=r.getVoices();if(n.voice){let a=o.find(i=>i.name===n.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=n.pickVoice?n.pickVoice(o):e.pickBestVoice(o));n.rate!==void 0&&(s.rate=n.rate),n.pitch!==void 0&&(s.pitch=n.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(t){var r;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of n){let o=t.find(a=>a.name===s);if(o)return o}return(r=t.find(s=>s.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,g,u,v,x,C,T,H,k;if(o!==r)return s;let a={...s,...n};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=n.toolCall)==null?void 0:m.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&So(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let P=`${d}:${l}`,W=this.webMcpInflightKeys.has(P),A=this.webMcpResolvedKeys.has(P),I=(x=s.toolCall)==null?void 0:x.name,O=((C=s.agentMetadata)==null?void 0:C.executionId)===d&&((T=s.toolCall)==null?void 0:T.id)===l&&I!==void 0&&So(I)&&((H=s.toolCall)==null?void 0:H.status)==="complete";(W||A||O)&&(a.agentMetadata={...(k=a.agentMetadata)!=null?k:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Sr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import{Activity as mg,ArrowDown as gg,ArrowUp as fg,ArrowUpRight as hg,Bot as yg,ChevronDown as bg,ChevronUp as xg,ChevronRight as vg,ChevronLeft as Cg,Check as wg,Clipboard as Ag,ClipboardCopy as Sg,Copy as Tg,File as Eg,FileCode as Mg,FileSpreadsheet as kg,FileText as Lg,ImagePlus as Pg,Loader as Ig,LoaderCircle as Wg,Mic as Rg,Paperclip as Hg,RefreshCw as Bg,Search as Dg,Send as Ng,ShieldAlert as Fg,ShieldCheck as Og,ShieldX as $g,Square as _g,ThumbsDown as jg,ThumbsUp as Ug,Upload as qg,Volume2 as zg,X as Vg,User as Kg,Mail as Jg,Phone as Gg,Calendar as Xg,Clock as Qg,Building as Yg,MapPin as Zg,Lock as ef,Key as tf,CreditCard as nf,AtSign as rf,Hash as of,Globe as sf,Link as af,CircleCheck as lf,CircleX as cf,TriangleAlert as df,Info as pf,Ban as uf,Shield as mf,ArrowLeft as gf,ArrowRight as ff,ExternalLink as hf,Ellipsis as yf,EllipsisVertical as bf,Menu as xf,House as vf,Plus as Cf,Minus as wf,Pencil as Af,Trash as Sf,Trash2 as Tf,Save as Ef,Download as Mf,Share as kf,Funnel as Lf,Settings as Pf,RotateCw as If,Maximize as Wf,Minimize as Rf,ShoppingCart as Hf,ShoppingBag as Bf,Package as Df,Truck as Nf,Tag as Ff,Gift as Of,Receipt as $f,Wallet as _f,Store as jf,DollarSign as Uf,Percent as qf,Play as zf,Pause as Vf,VolumeX as Kf,Camera as Jf,Image as Gf,Film as Xf,Headphones as Qf,MessageCircle as Yf,MessageSquare as Zf,Bell as eh,Heart as th,Star as nh,Eye as rh,EyeOff as oh,Bookmark as sh,CalendarDays as ah,History as ih,Timer as lh,Folder as ch,FolderOpen as dh,Files as ph,Sparkles as uh,Zap as mh,Sun as gh,Moon as fh,Flag as hh,Monitor as yh,Smartphone as bh}from"lucide";var xh={activity:mg,"arrow-down":gg,"arrow-up":fg,"arrow-up-right":hg,bot:yg,"chevron-down":bg,"chevron-up":xg,"chevron-right":vg,"chevron-left":Cg,check:wg,clipboard:Ag,"clipboard-copy":Sg,copy:Tg,file:Eg,"file-code":Mg,"file-spreadsheet":kg,"file-text":Lg,"image-plus":Pg,loader:Ig,"loader-circle":Wg,mic:Rg,paperclip:Hg,"refresh-cw":Bg,search:Dg,send:Ng,"shield-alert":Fg,"shield-check":Og,"shield-x":$g,square:_g,"thumbs-down":jg,"thumbs-up":Ug,upload:qg,"volume-2":zg,x:Vg,user:Kg,mail:Jg,phone:Gg,calendar:Xg,clock:Qg,building:Yg,"map-pin":Zg,lock:ef,key:tf,"credit-card":nf,"at-sign":rf,hash:of,globe:sf,link:af,"circle-check":lf,"circle-x":cf,"triangle-alert":df,info:pf,ban:uf,shield:mf,"arrow-left":gf,"arrow-right":ff,"external-link":hf,ellipsis:yf,"ellipsis-vertical":bf,menu:xf,house:vf,plus:Cf,minus:wf,pencil:Af,trash:Sf,"trash-2":Tf,save:Ef,download:Mf,share:kf,funnel:Lf,settings:Pf,"rotate-cw":If,maximize:Wf,minimize:Rf,"shopping-cart":Hf,"shopping-bag":Bf,package:Df,truck:Nf,tag:Ff,gift:Of,receipt:$f,wallet:_f,store:jf,"dollar-sign":Uf,percent:qf,play:zf,pause:Vf,"volume-x":Kf,camera:Jf,image:Gf,film:Xf,headphones:Qf,"message-circle":Yf,"message-square":Zf,bell:eh,heart:th,star:nh,eye:rh,"eye-off":oh,bookmark:sh,"calendar-days":ah,history:ih,timer:lh,folder:ch,"folder-open":dh,files:ph,sparkles:uh,zap:mh,sun:gh,moon:fh,flag:hh,monitor:yh,smartphone:bh},be=(e,t=24,n="currentColor",r=2)=>{let s=xh[e];return s?vh(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function vh(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var Na={allowedTypes:Nr,maxFileSize:10*1024*1024,maxFiles:4};function Ch(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function wh(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Jo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Na.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Na.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Na.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Na.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=Np(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,m);continue}try{let m=await Dp(l),g=Ra(l)?URL.createObjectURL(l):null,u={id:Ch(),file:l,previewUrl:g,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ra(t.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=h("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=wh(t.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Fp(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=be("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var _p=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Hs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];_p(o)&&_p(s)?n[r]=Hs(o,s):n[r]=s}return n}var sr="min(440px, calc(100vw - 24px))",Ii="440px",Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:sr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function jp(e,t){if(!(!e&&!t))return e?t?Hs(e,t):e:t}function Wi(e){var t,n,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,k,P,W;return e?{...Ft,...e,theme:jp(Ft.theme,e.theme),darkTheme:jp(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(t=Ft.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var ye,Le,Be,ee,Pe,V,le,ve;let A=(ye=Ft.features)==null?void 0:ye.artifacts,I=(Le=e.features)==null?void 0:Le.artifacts,O=(Be=Ft.features)==null?void 0:Be.scrollToBottom,D=(ee=e.features)==null?void 0:ee.scrollToBottom,R=(Pe=Ft.features)==null?void 0:Pe.streamAnimation,_=(V=e.features)==null?void 0:V.streamAnimation,z=(le=Ft.features)==null?void 0:le.askUserQuestion,oe=(ve=e.features)==null?void 0:ve.askUserQuestion,Re=A===void 0&&I===void 0?void 0:{...A,...I,layout:{...A==null?void 0:A.layout,...I==null?void 0:I.layout}},Ue=O===void 0&&D===void 0?void 0:{...O,...D},Fe=R===void 0&&_===void 0?void 0:{...R,..._},ge=z===void 0&&oe===void 0?void 0:{...z,...oe,styles:{...z==null?void 0:z.styles,...oe==null?void 0:oe.styles}};return{...Ft.features,...e.features,...Ue!==void 0?{scrollToBottom:Ue}:{},...Re!==void 0?{artifacts:Re}:{},...Fe!==void 0?{streamAnimation:Fe}:{},...ge!==void 0?{askUserQuestion:ge}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=Ft.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(g=e.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Ft.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(C=e.layout)==null?void 0:C.messages)==null?void 0:T.timestamp}},slots:{...(H=Ft.layout)==null?void 0:H.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(P=Ft.markdown)==null?void 0:P.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}var Up={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},qp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},zp={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:sr,maxWidth:Ii,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Go(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Go(e,r):r}function Ri(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Go(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Vp(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Kp(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=Kp(o,s):n[r]=s}return n}function Ah(e,t){return t?Kp(e,t):e}function Bs(e,t={}){var s,o,a,i,d,l,p,m,g,u,v,x,C;let n={palette:Up,semantic:qp,components:zp},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:Ah(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=Vp(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(H=>H.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function Hi(e){var x,C,T,H,k,P,W,A,I,O,D,R,_,z,oe,Re,Ue,Fe,ge,ye,Le,Be,ee,Pe,V,le,ve,fe,Ce,Ve,X,te,se,ue,ie,re,Qe,Ie,ce,J,_e,Et,de,ae,Mn,Ot,ln,Hn,Xn,qe,F,Ae,De,Ne,je,dt,rt,At,_t,q,$t,Ye,Dt,ne,me,vt,jt,Zt,hn,St,Ct,ft,yt,zt,tt,Bn,Qn,yn,Dn,ut,xr,Nn,po,kn,Wo,Or,Er,bt,Fn,On,bn,Lt,Yn,Zn,$n,$r,Mr,_r,_n,Wt,xn,er,jr,kr,Ur,vr,jn,lr,gt,Jt,Gt,Un,qr,tr,cr,qn;let t=Ri(e),n={};for(let[S,zn]of Object.entries(t)){let dr=S.replace(/\./g,"-");n[`--persona-${dr}`]=zn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(C=n["--persona-semantic-colors-secondary"])!=null?C:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(H=n["--persona-semantic-colors-surface"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(P=n["--persona-semantic-colors-container"])!=null?P:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(A=n["--persona-semantic-colors-text-muted"])!=null?A:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(O=n["--persona-semantic-colors-border"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(D=n["--persona-semantic-colors-divider"])!=null?D:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(_=n["--persona-components-voice-recording-background"])!=null?_:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(oe=n["--persona-components-voice-speaking-icon"])!=null?oe:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Re=n["--persona-components-approval-requested-background"])!=null?Re:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ue=n["--persona-components-approval-requested-border"])!=null?Ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Fe=n["--persona-components-approval-requested-text"])!=null?Fe:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ge=n["--persona-components-approval-approve-background"])!=null?ge:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(ye=n["--persona-components-approval-deny-background"])!=null?ye:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Le=n["--persona-components-attachment-image-background"])!=null?Le:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(Be=n["--persona-components-attachment-image-border"])!=null?Be:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ee=n["--persona-semantic-typography-fontFamily"])!=null?ee:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Pe=n["--persona-semantic-typography-fontSize"])!=null?Pe:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(V=n["--persona-semantic-typography-fontWeight"])!=null?V:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(le=n["--persona-semantic-typography-lineHeight"])!=null?le:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(ve=n["--persona-palette-radius-sm"])!=null?ve:"0.125rem",n["--persona-radius-md"]=(fe=n["--persona-palette-radius-md"])!=null?fe:"0.375rem",n["--persona-radius-lg"]=(Ce=n["--persona-palette-radius-lg"])!=null?Ce:"0.5rem",n["--persona-radius-xl"]=(Ve=n["--persona-palette-radius-xl"])!=null?Ve:"0.75rem",n["--persona-radius-full"]=(X=n["--persona-palette-radius-full"])!=null?X:"9999px",n["--persona-launcher-radius"]=(se=(te=n["--persona-components-launcher-borderRadius"])!=null?te:n["--persona-palette-radius-full"])!=null?se:"9999px",n["--persona-launcher-bg"]=(ue=n["--persona-components-launcher-background"])!=null?ue:n["--persona-primary"],n["--persona-launcher-fg"]=(ie=n["--persona-components-launcher-foreground"])!=null?ie:n["--persona-text-inverse"],n["--persona-launcher-border"]=(re=n["--persona-components-launcher-border"])!=null?re:n["--persona-border"],n["--persona-button-primary-bg"]=(Qe=n["--persona-components-button-primary-background"])!=null?Qe:n["--persona-primary"],n["--persona-button-primary-fg"]=(Ie=n["--persona-components-button-primary-foreground"])!=null?Ie:n["--persona-text-inverse"],n["--persona-button-radius"]=(J=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?J:"9999px",n["--persona-panel-radius"]=(Et=(_e=n["--persona-components-panel-borderRadius"])!=null?_e:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(de=n["--persona-components-panel-border"])!=null?de:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Mn=(ae=n["--persona-components-panel-shadow"])!=null?ae:n["--persona-palette-shadows-xl"])!=null?Mn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Ot=n["--persona-components-input-borderRadius"])!=null?Ot:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Xn=(Hn=n["--persona-components-message-user-borderRadius"])!=null?Hn:n["--persona-radius-lg"])!=null?Xn:"0.5rem",n["--persona-message-assistant-radius"]=(F=(qe=n["--persona-components-message-assistant-borderRadius"])!=null?qe:n["--persona-radius-lg"])!=null?F:"0.5rem",n["--persona-header-bg"]=(Ae=n["--persona-components-header-background"])!=null?Ae:n["--persona-surface"],n["--persona-header-border"]=(De=n["--persona-components-header-border"])!=null?De:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ne=n["--persona-components-header-iconBackground"])!=null?Ne:n["--persona-primary"],n["--persona-header-icon-fg"]=(je=n["--persona-components-header-iconForeground"])!=null?je:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(dt=n["--persona-components-header-titleForeground"])!=null?dt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(rt=n["--persona-components-header-subtitleForeground"])!=null?rt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(At=n["--persona-components-header-actionIconForeground"])!=null?At:n["--persona-muted"];let r=(_t=e.components)==null?void 0:_t.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=($t=n["--persona-components-introCard-background"])!=null?$t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ye=n["--persona-components-introCard-borderRadius"])!=null?Ye:"1rem",n["--persona-intro-card-padding"]=(Dt=n["--persona-components-introCard-padding"])!=null?Dt:"1.5rem",n["--persona-intro-card-shadow"]=(me=(ne=s==null?void 0:s.shadow)!=null?ne:n["--persona-components-introCard-shadow"])!=null?me:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(vt=n["--persona-components-input-background"])!=null?vt:n["--persona-surface"],n["--persona-input-placeholder"]=(jt=n["--persona-components-input-placeholder"])!=null?jt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Zt=n["--persona-components-message-user-background"])!=null?Zt:n["--persona-accent"],n["--persona-message-user-text"]=(hn=n["--persona-components-message-user-text"])!=null?hn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(St=n["--persona-components-message-user-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Ct=n["--persona-components-message-assistant-background"])!=null?Ct:n["--persona-surface"],n["--persona-message-assistant-text"]=(ft=n["--persona-components-message-assistant-text"])!=null?ft:n["--persona-text"],n["--persona-message-assistant-border"]=(yt=n["--persona-components-message-assistant-border"])!=null?yt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Bn=(tt=n["--persona-components-scrollToBottom-background"])!=null?tt:n["--persona-button-primary-bg"])!=null?Bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(yn=(Qn=n["--persona-components-scrollToBottom-foreground"])!=null?Qn:n["--persona-button-primary-fg"])!=null?yn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Dn=n["--persona-components-scrollToBottom-border"])!=null?Dn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(po=(Nn=(xr=n["--persona-components-scrollToBottom-borderRadius"])!=null?xr:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?po:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Wo=(kn=n["--persona-components-scrollToBottom-shadow"])!=null?kn:n["--persona-palette-shadows-sm"])!=null?Wo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Or=n["--persona-components-scrollToBottom-padding"])!=null?Or:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Er=n["--persona-components-scrollToBottom-gap"])!=null?Er:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Fn=(bt=n["--persona-components-scrollToBottom-fontSize"])!=null?bt:n["--persona-palette-typography-fontSize-sm"])!=null?Fn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(On=n["--persona-components-scrollToBottom-iconSize"])!=null?On:"14px",n["--persona-tool-bubble-shadow"]=(bn=n["--persona-components-toolBubble-shadow"])!=null?bn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Lt=n["--persona-components-reasoningBubble-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Yn=n["--persona-components-composer-shadow"])!=null?Yn:"none",n["--persona-md-inline-code-bg"]=(Zn=n["--persona-components-markdown-inlineCode-background"])!=null?Zn:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Mr=($r=n["--persona-components-markdown-link-foreground"])!=null?$r:n["--persona-accent"])!=null?Mr:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(_r=n["--persona-components-markdown-codeBlock-background"])!=null?_r:n["--persona-container"],n["--persona-md-code-block-border-color"]=(_n=n["--persona-components-markdown-codeBlock-borderColor"])!=null?_n:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(xn=n["--persona-components-markdown-table-headerBackground"])!=null?xn:n["--persona-container"],n["--persona-md-table-border-color"]=(er=n["--persona-components-markdown-table-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-hr-color"]=(jr=n["--persona-components-markdown-hr-color"])!=null?jr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(kr=n["--persona-components-markdown-blockquote-borderColor"])!=null?kr:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Ur=n["--persona-components-markdown-blockquote-background"])!=null?Ur:"transparent",n["--persona-md-blockquote-text-color"]=(vr=n["--persona-components-markdown-blockquote-textColor"])!=null?vr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(jn=n["--persona-components-collapsibleWidget-container"])!=null?jn:n["--persona-surface"],n["--cw-surface"]=(lr=n["--persona-components-collapsibleWidget-surface"])!=null?lr:n["--persona-surface"],n["--cw-border"]=(gt=n["--persona-components-collapsibleWidget-border"])!=null?gt:n["--persona-border"],n["--persona-message-border"]=(Jt=n["--persona-components-message-border"])!=null?Jt:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let S=v.toolbar;S.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=S.iconHoverColor),S.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=S.iconHoverBackground),S.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=S.iconPadding),S.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=S.iconBorderRadius),S.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=S.iconBorder),S.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=S.toggleGroupGap),S.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=S.toggleBorderRadius),S.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=S.copyBackground),S.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=S.copyBorder),S.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=S.copyColor),S.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=S.copyBorderRadius),S.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=S.copyPadding),S.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=S.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:S.copyMenuBackground),S.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=S.copyMenuBorder,n["--persona-dropdown-border"]=(Un=n["--persona-dropdown-border"])!=null?Un:S.copyMenuBorder),S.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=S.copyMenuShadow,n["--persona-dropdown-shadow"]=(qr=n["--persona-dropdown-shadow"])!=null?qr:S.copyMenuShadow),S.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=S.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(tr=n["--persona-dropdown-radius"])!=null?tr:S.copyMenuBorderRadius),S.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=S.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(cr=n["--persona-dropdown-item-hover-bg"])!=null?cr:S.copyMenuItemHoverBackground),S.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=S.iconBackground),S.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=S.toolbarBorder)}if(v!=null&&v.tab){let S=v.tab;S.background&&(n["--persona-artifact-tab-bg"]=S.background),S.activeBackground&&(n["--persona-artifact-tab-active-bg"]=S.activeBackground),S.activeBorder&&(n["--persona-artifact-tab-active-border"]=S.activeBorder),S.borderRadius&&(n["--persona-artifact-tab-radius"]=S.borderRadius),S.textColor&&(n["--persona-artifact-tab-color"]=S.textColor),S.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=S.hoverBackground),S.listBackground&&(n["--persona-artifact-tab-list-bg"]=S.listBackground),S.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=S.listBorderColor),S.listPadding&&(n["--persona-artifact-tab-list-padding"]=S.listPadding)}if(v!=null&&v.pane){let S=v.pane;if(S.toolbarBackground){let zn=(qn=Go(e,S.toolbarBackground))!=null?qn:S.toolbarBackground;n["--persona-artifact-toolbar-bg"]=zn}}return n}var Sh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Th={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Jp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Fa=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Eh=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Fa()},Gp=e=>Eh(e),Mh=e=>Bs(e),kh=e=>{var n;let t=Bs(void 0,{validate:!1});return Bs({...e,palette:{...t.palette,colors:{...Th.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ds=e=>{let t=Gp(e),n=Jp(e==null?void 0:e.theme),r=Jp(e==null?void 0:e.darkTheme);return t==="dark"?kh(Hs(n!=null?n:{},r!=null?r:{})):Mh(n)},Lh=e=>Hi(e),Mo=(e,t)=>{var o;let n=Ds(t),r=Lh(n);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=t==null?void 0:t.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Bi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Fa())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Fa());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Ph}from"idiomorph";var Oa=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Ph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var $a={index:-1,draft:""};function Xp(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...$a}}}function Qp(e,t){var n,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,k,P,W,A,I,O,D,R,_,z,oe,Re,Ue,Fe,ge,ye,Le,Be,ee,Pe,V;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(v=(u=e.toolCall)==null?void 0:u.status)!=null?v:"",(C=(x=e.toolCall)==null?void 0:x.name)!=null?C:"",(k=(H=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:H.length)!=null?k:0,(I=(A=(W=(P=e.toolCall)==null?void 0:P.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?I:"",typeof((O=e.toolCall)==null?void 0:O.args)=="string"?e.toolCall.args.length:(D=e.toolCall)!=null&&D.args?JSON.stringify(e.toolCall.args).length:0,(z=(_=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:_.length)!=null?z:0,(Fe=(Ue=(Re=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:Re[e.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?Fe:0,(Be=(Le=(ye=(ge=e.reasoning)==null?void 0:ge.chunks)==null?void 0:ye[e.reasoning.chunks.length-1])==null?void 0:Le.slice(-32))!=null?Be:"",(Pe=(ee=e.contentParts)==null?void 0:ee.length)!=null?Pe:0,(V=e.stopReason)!=null?V:"",t].join("\0")}function Yp(){return new Map}function Zp(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function eu(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function tu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function _a(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Ns(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Fs(e,t){return Ns(e)-e.scrollTop<=t}function ja(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Ua(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var gn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},fn=1e5,eo=fn+1;var Os={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ih=["pre","code","a","script","style"],qa=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Os.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Os.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Os.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Os.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Os.buffer}},ru=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],$s=new Map;for(let e of ru)$s.set(e.name,e);var Wh=e=>{$s.set(e.name,e)},Rh=e=>{ru.some(t=>t.name===e)||$s.delete(e)},Hh=()=>Array.from($s.keys()),_s=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=$s.get(e))!=null?r:null},za=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
|
|
15
|
+
`);return o<0?"":e.slice(0,o)}return e},Bh=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},Dh=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},Di=/\s/,Nh=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Fh=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(Di.test(o[i])){let l=i;for(;l<o.length&&Di.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<o.length&&!Di.test(o[p]);)l.appendChild(Bh(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},Oh=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Dh(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},js=(e,t,n,r)=>{var m,g;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:Ih).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Nh(d,o)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Fh:Oh;for(let u of i)p(u,n,l);return s.innerHTML},Va=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Us=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},nu=new WeakMap,$h=(e,t)=>{var o;if(!e.styles)return;let n=nu.get(t);if(n||(n=new Set,nu.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},Ni=new WeakMap,_h=(e,t)=>{if(!e.onAttach)return;let n=Ni.get(t);if(n||(n=new Map,Ni.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},ou=e=>{let t=Ni.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Fi=(e,t)=>{$h(e,t),_h(e,t)};function Oi(e,t=fn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var qs=0,to=null;function $i(e=document){var n;if(qs++,qs===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;to={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,qs=Math.max(0,qs-1),qs===0&&to)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=to.originalOverflow,s.style.position=to.originalPosition,s.style.top=to.originalTop,s.style.width=to.originalWidth,o.scrollTo(0,to.scrollY),to=null}}}var Ka={side:"right",width:"420px",animate:!0,reveal:"resize"},an=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},no=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},yr=e=>{var n,r,s,o,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Ka.side,width:(s=t==null?void 0:t.width)!=null?s:Ka.width,animate:(o=t==null?void 0:t.animate)!=null?o:Ka.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ka.reveal}};var br={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var zs=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
|
|
16
16
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
17
17
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
18
18
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -20,14 +20,14 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
|
|
|
20
20
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
21
21
|
</span>
|
|
22
22
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
23
|
-
`,n.addEventListener("click",t);let r=o=>{var L,P,W,w,I,O,$,B,j,z,oe,We,je,Ne;let a=(L=o.launcher)!=null?L:{},i=an(o),d=n.querySelector("[data-role='launcher-title']");if(d){let ge=(P=a.title)!=null?P:"Chat Assistant";d.textContent=ge,d.setAttribute("title",ge)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ge=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=ge,l.setAttribute("title",ge)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ge=(w=a.agentIconSize)!=null?w:"40px";if(m.style.height=ge,m.style.width=ge,m.innerHTML="",a.agentIconName){let ye=parseFloat(ge)||24,Le=be(a.agentIconName,ye*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(m.appendChild(Le),m.style.display=""):(m.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ge=($=a.agentIconSize)!=null?$:"40px";g.style.height=ge,g.style.width=ge,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let ge=(B=a.callToActionIconSize)!=null?B:"32px";u.style.height=ge,u.style.width=ge,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let ye=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,ye=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Le=parseFloat(ge)||24,He=Math.max(Le-ye,8),ee=be(a.callToActionIconName,He,"currentColor",2);ee?u.appendChild(ee):u.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else u.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let v=a.position&&br[a.position]?br[a.position]:br["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",C="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?C:`${x} ${v}`,i||(n.style.zIndex=String((oe=a.zIndex)!=null?oe:fn));let T="1px solid var(--persona-border, #e5e7eb)",H="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(We=a.border)!=null?We:T,n.style.boxShadow=(je=a.shadow)!=null?je:H,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(Ne=a.collapsedMaxWidth)!=null?Ne:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var $h="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ka=(e,t={})=>{var x,C,T,H,L,P;let{showClose:n=!0,wrapperClassName:r=$h,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(C=s!=null?s:a.closeButtonSize)!=null?C:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(T=a.closeButtonTooltipText)!=null?T:"Close chat",m=(H=a.closeButtonShowTooltip)!=null?H:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let g=(L=a.closeButtonIconName)!=null?L:"x",u=(P=a.closeButtonIconText)!=null?P:"\xD7";l.style.color=a.closeButtonColor||En.actionIconColor;let v=be(g,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let W=null,w=()=>{if(W)return;let O=l.ownerDocument,$=O.body;if(!$)return;W=Sr(O,"div","persona-clear-chat-tooltip"),W.textContent=p;let B=Sr(O,"div");B.className="persona-clear-chat-tooltip-arrow",W.appendChild(B);let j=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(eo),W.style.left=`${j.left+j.width/2}px`,W.style.top=`${j.top-8}px`,W.style.transform="translate(-50%, -100%)",$.appendChild(W)},I=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",I),l.addEventListener("focus",w),l.addEventListener("blur",I),d._cleanupTooltip=()=>{I(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",I),l.removeEventListener("focus",w),l.removeEventListener("blur",I)}}return{button:l,wrapper:d}},_h="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ja=(e,t={})=>{var W,w,I,O,$,B,j,z,oe,We,je,Ne,ge;let{wrapperClassName:n=_h,buttonSize:r,iconSize:s="20px"}=t,a=(w=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?w:{},i=(I=r!=null?r:a.size)!=null?I:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",l=($=a.iconColor)!=null?$:"",p=(B=a.backgroundColor)!=null?B:"",m=(j=a.borderWidth)!=null?j:"",g=(z=a.borderColor)!=null?z:"",u=(oe=a.borderRadius)!=null?oe:"",v=(We=a.paddingX)!=null?We:"",x=(je=a.paddingY)!=null?je:"",C=(Ne=a.tooltipText)!=null?Ne:"Clear chat",T=(ge=a.showTooltip)!=null?ge:!0,H=h("div",n),L=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");L.style.height=i,L.style.width=i,L.type="button",L.setAttribute("aria-label",C),L.style.color=l||En.actionIconColor;let P=be(d,s,"currentColor",1);if(P&&(P.style.display="block",L.appendChild(P)),p&&(L.style.backgroundColor=p,L.classList.remove("hover:persona-bg-gray-100")),m||g){let ye=m||"0px",Le=g||"transparent";L.style.border=`${ye} solid ${Le}`,L.classList.remove("persona-border-none")}if(u&&(L.style.borderRadius=u,L.classList.remove("persona-rounded-full")),v&&(L.style.paddingLeft=v,L.style.paddingRight=v),x&&(L.style.paddingTop=x,L.style.paddingBottom=x),H.appendChild(L),T&&C){let ye=null,Le=()=>{if(ye)return;let ee=L.ownerDocument,Pe=ee.body;if(!Pe)return;ye=Sr(ee,"div","persona-clear-chat-tooltip"),ye.textContent=C;let V=Sr(ee,"div");V.className="persona-clear-chat-tooltip-arrow",ye.appendChild(V);let le=L.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(eo),ye.style.left=`${le.left+le.width/2}px`,ye.style.top=`${le.top-8}px`,ye.style.transform="translate(-50%, -100%)",Pe.appendChild(ye)},He=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};H.addEventListener("mouseenter",Le),H.addEventListener("mouseleave",He),L.addEventListener("focus",Le),L.addEventListener("blur",He),H._cleanupTooltip=()=>{He(),H.removeEventListener("mouseenter",Le),H.removeEventListener("mouseleave",He),L.removeEventListener("focus",Le),L.removeEventListener("blur",He)}}return{button:L,wrapper:H}};var En={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ro=e=>{var W,w,I,O,$,B,j,z,oe,We,je,Ne,ge,ye,Le,He;let{config:t,showClose:n=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(W=t==null?void 0:t.launcher)!=null?W:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(I=s.closeButtonPlacement)!=null?I:"inline",i=(O=s.headerIconHidden)!=null?O:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(o)||24,Pe=be(d,ee*.6,"currentColor",1);Pe?l.replaceChildren(Pe):l.textContent=(B=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?B:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let ee=h("img");ee.src=t.launcher.iconUrl,ee.alt="",ee.className="persona-rounded-xl persona-object-cover",ee.style.height=o,ee.style.width=o,l.replaceChildren(ee)}else l.textContent=(oe=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?oe:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=h("span","persona-text-base persona-font-semibold");m.style.color=En.titleColor,m.textContent=(je=(We=t==null?void 0:t.launcher)==null?void 0:We.title)!=null?je:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=En.subtitleColor,g.textContent=(ge=(Ne=t==null?void 0:t.launcher)==null?void 0:Ne.subtitle)!=null?ge:"Here to help you get answers fast",p.append(m,g),i?r.append(p):r.append(l,p);let u=(ye=s.clearChat)!=null?ye:{},v=(Le=u.enabled)!=null?Le:!0,x=(He=u.placement)!=null?He:"inline",C=null,T=null;if(v){let Pe=Ja(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=Pe.button,T=Pe.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let H=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:L,wrapper:P}=Ka(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&r.appendChild(P),{header:r,iconHolder:l,headerTitle:m,headerSubtitle:g,closeButton:L,closeButtonWrapper:P,clearChatButton:C,clearChatButtonWrapper:T}},Go=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Mo(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(eo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of t){if(u.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let C=be(u.icon,16,"currentColor",1.5);C&&v.appendChild(C)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",C=>{C.stopPropagation(),p(),n(u.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:g}}function qt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=be(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function Ga(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=be(t,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=h("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))p.setAttribute(g,u);return p}function Xa(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=qt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=h("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function l(p){a=p,d()}return{element:o,setSelected:l}}function $i(e){var u,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let m=be(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,C;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(C=d.border)!=null?C:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Mo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let C=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var ru=e=>{var r;let t=ro({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function jh(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=be(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=Mo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var ou=e=>{var H,L,P,W,w,I,O,$,B;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(H=t==null?void 0:t.launcher)!=null?H:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,p;if(d)l=$i({label:(L=a.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=En.titleColor,p=(P=l.querySelector(".persona-combo-btn-label"))!=null?P:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=En.titleColor,p.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(p),jh(l,s==null?void 0:s.trailingActions,(w=s==null?void 0:s.onAction)!=null?w:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let z=s.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||z()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),z())})}let j=s==null?void 0:s.titleRowHover;j&&(l.style.borderRadius=(I=j.borderRadius)!=null?I:"10px",l.style.padding=(O=j.padding)!=null?O:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var z,oe;l.style.backgroundColor=(z=j.background)!=null?z:"",l.style.borderColor=(oe=j.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=($=a.closeButtonSize)!=null?$:"32px",g=h("div",""),u=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||En.actionIconColor;let v=(B=a.closeButtonIconName)!=null?B:"x",x=be(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let C=h("div");C.style.display="none";let T=h("span");return T.style.display="none",{header:i,iconHolder:C,headerTitle:p,headerSubtitle:T,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},_i={default:ru,minimal:ou},su=e=>{var t;return(t=_i[e])!=null?t:_i.default},qs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=h("div");p.style.display="none";let m=h("span"),g=h("span"),u=h("button");u.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=su(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Qa=e=>{var a,i;let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},Ya=e=>{var W,w,I,O,$,B,j,z,oe,We,je,Ne;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(w=t.useIcon)!=null?w:!1,r=(I=t.iconText)!=null?I:"\u2191",s=t.iconName,o=(O=t.stopIconName)!=null?O:"square",a=($=t.tooltipText)!=null?$:"Send message",i=(B=t.stopTooltipText)!=null?B:"Stop generating",d=(z=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?z:"Send",l=(We=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?We:"Stop",p=(je=t.showTooltip)!=null?je:!1,m=(Ne=t.size)!=null?Ne:"40px",g=t.backgroundColor,u=t.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let C=null,T=null;if(n){x.style.width=m,x.style.height=m,x.style.minWidth=m,x.style.minHeight=m,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",u?x.style.color=u:x.style.color="var(--persona-button-primary-fg, #ffffff)";let ge=parseFloat(m)||24,ye=(u==null?void 0:u.trim())||"currentColor";s?(C=be(s,ge,ye,2),C?x.appendChild(C):x.textContent=r):x.textContent=r,T=be(o,ge,ye,2),g?x.style.backgroundColor=g:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,u?x.style.color=u:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let H=null;p&&a&&(H=h("div","persona-send-button-tooltip"),H.textContent=a,v.appendChild(H)),x.setAttribute("aria-label",a),v.appendChild(x);let L="send";return{button:x,wrapper:v,setMode:ge=>{if(ge===L)return;L=ge;let ye=ge==="stop"?i:a;if(x.setAttribute("aria-label",ye),H&&(H.textContent=ye),n){if(C&&T){let Le=ge==="stop"?T:C;x.replaceChildren(Le)}}else x.textContent=ge==="stop"?l:d}}},Za=e=>{var H,L,P,W,w,I,O,$,B,j,z,oe;let t=(H=e==null?void 0:e.voiceRecognition)!=null?H:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((L=t.provider)==null?void 0:L.type)==="runtype";if(!(r||s))return null;let a=(W=(P=e==null?void 0:e.sendButton)==null?void 0:P.size)!=null?W:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=t.iconName)!=null?w:"mic",p=(I=t.iconSize)!=null?I:a,m=parseFloat(p)||24,g=($=t.backgroundColor)!=null?$:(O=e==null?void 0:e.sendButton)==null?void 0:O.backgroundColor,u=(j=t.iconColor)!=null?j:(B=e==null?void 0:e.sendButton)==null?void 0:B.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let x=be(l,m,u||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let C=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((oe=t.showTooltip)!=null?oe:!1)&&C){let We=h("div","persona-send-button-tooltip");We.textContent=C,i.appendChild(We)}return{button:d,wrapper:i}},ei=e=>{var v,x,C,T,H,L,P,W;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(C=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?C:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((T=t.allowedTypes)!=null?T:Nr).join(","),s.multiple=((H=t.maxFiles)!=null?H:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(L=t.buttonTooltipText)!=null?L:"Attach file");let i=(P=t.buttonIconName)!=null?P:"paperclip",d=n,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=be(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),s.click()}),o.appendChild(a);let g=(W=t.buttonTooltipText)!=null?W:"Attach file",u=h("div","persona-send-button-tooltip");return u.textContent=g,o.appendChild(u),{button:a,wrapper:o,input:s,previewsContainer:r}},ti=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=h("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},ni=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var zs=e=>{var v,x,C,T,H,L;let{config:t}=e,n=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let r=ni(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Qa(t);a();let i=Ya(t),d=Za(t),l=ei(t),p=ti(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let m=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(g,u),s.append(m),s.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(C=l==null?void 0:l.button)!=null?C:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(H=l==null?void 0:l.input)!=null?H:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var au=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=h("span","persona-pill-peek__icon"),n=be("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=be("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},iu=e=>{var v,x,C,T,H,L;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=ni();r.style.display="none";let s=ti(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Qa(t);o.style.maxHeight="100px",a();let i=Ya(t),d=Za(t),l=ei(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let g=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(m,o,g),l&&n.append(l.previewsContainer),n.append(p,r,s);let u=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(C=l==null?void 0:l.button)!=null?C:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(H=l==null?void 0:l.input)!=null?H:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var lu=e=>{var p,m,g,u,v,x,C,T,H,L,P,W,w,I,O,$,B;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=an(e);if(no(e)){let j=(u=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?u:{},z=h("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",z.style.zIndex=String((C=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?C:fn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",z.appendChild(oe);let We=h("div","persona-widget-pill-root");return We.setAttribute("data-persona-composer-bar",""),We.dataset.state="collapsed",We.dataset.expandedSize=(T=j.expandedSize)!=null?T:"anchored",We.style.zIndex=String((L=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?L:fn),{wrapper:z,panel:oe,pillRoot:We}}if(n){let j=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(z),{wrapper:j,panel:z}}if(!t){let j=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.width)!=null?W:"100%";return j.style.width=oe,z.style.width="100%",j.appendChild(z),{wrapper:j,panel:z}}let s=(w=e==null?void 0:e.launcher)!=null?w:{},o=s.position&&br[s.position]?br[s.position]:br["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((O=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?O:fn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(B=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?B:e==null?void 0:e.launcherWidth,l=d!=null?d:sr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Uh=(e,t)=>{var P,W,w,I,O,$,B,j,z;let n=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Ka(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(w=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.clearChat)==null?void 0:W.enabled)!=null?w:!0,a=null,i=null;if(o){let oe=Ja(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(O=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?O:"Hello \u{1F44B}";let g=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(B=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",p.append(m,g);let u=h("div","persona-flex persona-flex-col persona-gap-3"),v=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let C=h("div","persona-composer-overlay persona-pointer-events-none");C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20";let T=iu({config:e}),{root:H,textNode:L}=au();return n.append(d,s,l,C),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:C,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:m,introSubtitle:g,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:H,peekTextNode:L}},cu=(e,t=!0)=>{var C,T,H,L,P,W,w,I,O;if(no(e))return Uh(e,t);let n=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let r=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,o=r?qs(e,r,{showClose:t}):ro({config:e,showClose:t}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=an(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(L=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?L:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),m=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=zs({config:e}),v=((O=e==null?void 0:e.layout)==null?void 0:O.showFooter)!==!1;s?Go(n,o,e):(o.header.style.display="none",Go(n,o,e)),n.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(u.footer.style.display="none"),n.append(u.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var qh=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},zh=(e,t)=>{if(!e)return null;let n=qh(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Vh=(e,t)=>{let n=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Kh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ji=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ui=320,pu=320,Jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Gh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Xh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Qh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Yh=(e,t,n)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let l=h("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Ui}px`,l.style.maxHeight=`${pu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),Kh(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Zh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!ji(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Ui}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ey=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!ji(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Ui}px`,s.style.maxHeight=`${pu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ty=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!ji(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Xo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},uu=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Xo};if(t){let s=t(r);if(s!==null)return s}return Xo()},ny=(e,t)=>{let n=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},du=(e,t)=>{let n=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ry=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},mu=(e,t,n)=>{var u,v,x,C,T,H;let r=(u=t.showCopy)!=null?u:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let L=h("div");return L.style.display="none",L.id=`actions-${e.id}`,L.setAttribute("data-actions-for",e.id),L}let a=(C=t.visibility)!=null?C:"hover",i=(T=t.align)!=null?T:"right",d=(H=t.layout)!=null?H:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let g=(L,P,W)=>{let w=qt({icon:L,label:P,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",W),w};return r&&m.appendChild(g("copy","Copy message","copy")),s&&m.appendChild(g("thumbs-up","Upvote","upvote")),o&&m.appendChild(g("thumbs-down","Downvote","downvote")),m},Vs=(e,t,n,r,s,o)=>{var ee,Pe,V,le,ve,fe,we,ze,Q,te,se,ue,ie,re,Qe,Ie,ce;let a=n!=null?n:{},i=(ee=a.layout)!=null?ee:"bubble",d=a.avatar,l=a.timestamp,p=(Pe=d==null?void 0:d.show)!=null?Pe:!1,m=(V=l==null?void 0:l.show)!=null?V:!1,g=(le=d==null?void 0:d.position)!=null?le:"left",u=(ve=l==null?void 0:l.position)!=null?ve:"below",v=ry(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=Jh(e),T=(we=(fe=e.content)==null?void 0:fe.trim())!=null?we:"",L=C.length>0&&T===Pa,P=Ua((Q=(ze=o==null?void 0:o.widgetConfig)==null?void 0:ze.features)==null?void 0:Q.streamAnimation),W=(ue=(se=(te=o==null?void 0:o.widgetConfig)==null?void 0:te.features)==null?void 0:se.streamAnimation)==null?void 0:ue.plugins,w=e.role==="assistant"&&P.type!=="none"?Os(P.type,W):null,I=e.role==="assistant"&&((ie=w==null?void 0:w.isAnimating)==null?void 0:ie.call(w,e))===!0,O=e.role==="assistant"&&w!==null&&(!!e.streaming||I);O&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),O&&w&&(w.containerClass&&$.classList.add(w.containerClass),$.style.setProperty("--persona-stream-step",`${P.speed}ms`),$.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let B=O?qa((re=e.content)!=null?re:"",P.buffer,w,e,!!e.streaming):(Qe=e.content)!=null?Qe:"",j=t({text:B,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=j;O&&(w==null?void 0:w.wrap)==="char"?z=$s(j,"char",e.id,{skipTags:w.skipTags}):O&&(w==null?void 0:w.wrap)==="word"&&(z=$s(j,"word",e.id,{skipTags:w.skipTags}));let oe=null;if(L?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",$.appendChild(oe)):$.innerHTML=z,O&&(w!=null&&w.useCaret)&&!L&&T){let G=za(),$e=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=$e[$e.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(G,Et.nextSibling);else{let de=$.lastElementChild;de?de.appendChild(G):$.appendChild(G)}}if(m&&u==="inline"&&e.createdAt){let G=du(e,l);G.classList.add("persona-ml-2","persona-inline"),$.appendChild(G)}if(C.length>0){let G=Yh(C,!L&&!!T,()=>{L&&oe&&(oe.style.display="")});G?x.appendChild(G):L&&oe&&(oe.style.display="")}let We=Gh(e);if(We.length>0){let G=Zh(We);G&&x.appendChild(G)}let je=Xh(e);if(je.length>0){let G=ey(je);G&&x.appendChild(G)}let Ne=Qh(e);if(Ne.length>0){let G=ty(Ne);G&&x.appendChild(G)}if(x.appendChild($),m&&u==="below"&&e.createdAt){let G=du(e,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let ge=e.role==="assistant"?zh(e.stopReason,(ce=(Ie=o==null?void 0:o.widgetConfig)==null?void 0:Ie.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(B&&B.trim()),$e=P.placeholder==="skeleton",Et=$e&&P.buffer==="line"&&G;if(G)Et&&x.appendChild(_s());else if($e)x.appendChild(_s());else{let de=uu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);de&&x.appendChild(de)}}if(ge&&e.stopReason&&!e.streaming&&(T||($.style.display="none"),x.appendChild(Vh(e.stopReason,ge))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let G=mu(e,r,s);x.appendChild(G)}if(!p||e.role==="system")return x;let Le=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),He=ny(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Le.append(x,He):Le.append(He,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},oy=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Vs(e,t,n,r,s,o)};var Qo=new Set,sy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ay=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
-
`):""},
|
|
25
|
-
`);let s=
|
|
26
|
-
`):""},cy=(e,t)=>{var p,m,g,u,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=ly(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?Wp(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},l=a;return s==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Ai(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ai(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},fu=(e,t,n)=>{var p;let r=Yo.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"currentColor",g=be(r?"chevron-up":"chevron-down",16,m,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},zi=(e,t)=>{var z,oe,We,je,Ne,ge,ye,Le,He;let n=e.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!n)return s;let o=(We=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?We:{},a=o.expandable!==!1,i=a&&Yo.has(e.id),{summary:d,previewText:l,isActive:p}=cy(e,t),m=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((je=n.startedAt)!=null?je:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",v),ee.textContent=ks(n),ee},C=(ge=r.renderCollapsedSummary)==null?void 0:ge.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Ne=o.collapsedMode)!=null?Ne:"tool-call",isActive:p,config:t!=null?t:{},elapsed:ks(n),createElapsedElement:x});typeof C=="string"&&C.trim()?(u.textContent=C,g.appendChild(u)):C instanceof HTMLElement?g.appendChild(C):(u.textContent=d,g.appendChild(u));let T=(ye=o.loadingAnimation)!=null?ye:"none",H=r.activeTextTemplate,L=r.completeTextTemplate,P=p?H:L,W=C instanceof HTMLElement,w=(ee,Pe,V)=>{let le=V;for(let ve of Pe){let fe=h("span","persona-tool-char");fe.style.setProperty("--char-index",String(le)),fe.textContent=ve===" "?"\xA0":ve,ee.appendChild(fe),le++}return le},I=(ee,Pe)=>{var fe;u.textContent="";let V=((fe=n.name)==null?void 0:fe.trim())||"tool",le=Ma(ee,V),ve=0;for(let we of le){let ze=we.styles.length>0?(()=>{let Q=h("span",we.styles.map(te=>`persona-tool-text-${te}`).join(" "));return u.appendChild(Q),Q})():u;if(we.isDuration&&p)ze.appendChild(x());else{let Q=we.isDuration?ks(n):we.text;Pe?ve=w(ze,Q,ve):ze.appendChild(document.createTextNode(Q))}}};if(!W)if(p&&T!=="none"){let ee=(Le=r.loadingAnimationDuration)!=null?Le:2e3;if(u.setAttribute("data-preserve-animation","true"),T==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),P&&I(P,!1);else if(u.classList.add(`persona-tool-loading-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),P)I(P,!0);else{let Pe=u.textContent||d;u.textContent="",w(u,Pe,0)}}else P&&I(P,!1);let O=null;if(a){O=h("div","persona-flex persona-items-center");let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Pe=be(i?"chevron-up":"chevron-down",16,ee,2);Pe?O.appendChild(Pe):O.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append(O),m.append(g,V)}else m.append(g);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let ee=(He=r.renderCollapsedPreview)==null?void 0:He.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});iy($,ee)||($.textContent=l),$.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,$),s;let B=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(B.style.display=i?"":"none",r.contentBackgroundColor&&(B.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(B.style.color=r.contentTextColor),r.contentPaddingX&&(B.style.paddingLeft=r.contentPaddingX,B.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(B.style.paddingTop=r.contentPaddingY,B.style.paddingBottom=r.contentPaddingY),n.name){let ee=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ee.style.color=r.contentTextColor:r.headerTextColor&&(ee.style.color=r.headerTextColor),ee.textContent=n.name,B.appendChild(ee)}if(n.args!==void 0){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Arguments";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=Uo(n.args),ee.append(Pe,V),B.appendChild(ee)}if(n.chunks&&n.chunks.length){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Activity";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=n.chunks.join(""),ee.append(Pe,V),B.appendChild(ee)}if(n.status==="complete"&&n.result!==void 0){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Result";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=Uo(n.result),ee.append(Pe,V),B.appendChild(ee)}if(n.status==="complete"&&typeof n.duration=="number"){let ee=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ee.style.color=r.contentTextColor),ee.textContent=`Duration: ${n.duration}ms`,B.appendChild(ee)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Pe=be(i?"chevron-up":"chevron-down",16,ee,2);Pe?O.appendChild(Pe):O.textContent=i?"Hide":"Show"}B.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(m,$,B),s};import{parse as dy,ARR as py,OBJ as uy,STR as my}from"partial-json";var yu="ask_user_question",Vi=8,Zo="data-persona-ask-sheet-for",gy="Other",fy="Other\u2026",bu="Type your own answer here",xu="Send",hy="Next",yy="Back",by="Submit all",xy="Skip",vy=3,Ki="data-ask-current-index",Ji="data-ask-question-count",vu="data-ask-answers",Gi="data-ask-grouped",wu="data-ask-layout",wy=e=>e.layout==="pills"?"pills":"rows",Cy=e=>e.getAttribute(wu)==="pills"?"pills":"rows",hu=!1,Cu=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===yu,ri=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},so=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=dy(s,my|uy|py);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},Ks=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Vi&&!hu&&(hu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Vi}.`)),t.slice(0,Vi)},Ay=e=>{var t;return(t=Ks(e)[0])!=null?t:null},Sy=(e,t)=>{var n;return(n=Ks(e)[t])!=null?n:null},Au=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Su=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Ty=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Su(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Ey=e=>{let n=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},My=(e,t,n,r)=>{var p,m,g;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<vy;u++)o.appendChild(Ey(r));return o}if(d.forEach((u,v)=>{o.appendChild(Ty(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?gy:fy;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),C=document.createElement("input");C.type="text",C.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",C.placeholder=(p=t.freeTextPlaceholder)!=null?p:bu,C.setAttribute("data-ask-free-text-input","true"),C.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),x.appendChild(C),v.appendChild(x);let T=Su(r,a,d.length);T&&v.appendChild(T),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:u,o.appendChild(v)}}return o},Tu=(e,t)=>{var o,a;let r=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:bu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:xu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},ky=e=>{var r;let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:xu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ly=(e,t,n)=>{var l,p,m,g;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:yy,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:xy,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:by:(g=n.nextLabel)!=null?g:hy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},ko=e=>{let t=e.getAttribute(vu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Eu=(e,t)=>{e.setAttribute(vu,JSON.stringify(t))},ar=e=>{var n;let t=Number((n=e.getAttribute(Ki))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Py=(e,t)=>{e.setAttribute(Ki,String(Math.max(0,Math.floor(t))))},es=e=>{var n;let t=Number((n=e.getAttribute(Ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ao=e=>e.getAttribute(Gi)==="true",Iy=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Wy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},oi=(e,t)=>{let{payload:n}=so(t),r=Ks(n),s=ko(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Mu=e=>{let t=ko(e),n=ar(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},ku=e=>{if(!ao(e))return;let t=ko(e),n=ar(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Xi=(e,t,n)=>{let r=ri(n),s=Cy(e),{payload:o,complete:a}=so(t),i=ao(e),d=ar(e),l=es(e),p=i?Sy(o,d):Ay(o),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let H=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=H,v.classList.toggle("persona-ask-question-skeleton",!H&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let H=My(p,r,a,s);x.replaceWith(H)}if(s!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(Tu(r,s))}let C=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!C?e.appendChild(ky(r)):(!m||i)&&C&&C.remove(),e.setAttribute("data-multi-select",m?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let H=Ly(d,l,r);T?T.replaceWith(H):e.appendChild(H)}else T&&T.remove();Mu(e),ku(e)},Ry=(e,t,n)=>{let r=ri(t),s=wy(r),o=e.toolCall.id,a=Ks(n),i=Math.max(1,a.length),d=i>1,l=Iy(e,a),p=d?Wy(e,i):0,m=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Zo,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(Ji,String(i)),m.setAttribute(Ki,String(p)),m.setAttribute(Gi,d?"true":"false"),m.setAttribute(wu,s),Eu(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Au(m,r);let g=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=h("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),m.appendChild(g);let C=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),m.appendChild(C),s!=="rows"&&m.appendChild(Tu(r,s)),Xi(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Hy=(e,t,n)=>{let{payload:r}=so(t),s=Math.max(1,Ks(r).length);s>es(e)&&(e.setAttribute(Ji,String(s)),s>1&&!ao(e)&&e.setAttribute(Gi,"true")),Xi(e,t,n)},By=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=ri(t);Au(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=so(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Js=(e,t,n)=>{if(!n||!oo(e)||ri(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${Zo}]`).forEach(l=>{l.getAttribute(Zo)!==s&&l.remove()});let a=n.querySelector(`[${Zo}="${Cu(s)}"]`);if(a){Hy(a,e,t);return}let{payload:i}=so(e),d=Ry(e,t,i);n.appendChild(d)},Lo=(e,t)=>{if(!e)return;let n=t?`[${Zo}="${Cu(t)}"]`:`[${Zo}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Qi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),io=(e,t)=>{let n=ko(e),r=ar(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Eu(e,n),Mu(e),ku(e)},si=(e,t,n,r)=>{let s=es(e),o=Math.max(0,Math.min(s-1,r));Py(e,o),Xi(e,t,n)};var Yi=(e,t)=>{var x,C,T,H,L,P,W,w,I,O,$,B;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=r==null?void 0:r.borderColor)!=null?C:"var(--persona-approval-border, #fef08a)",!n)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(T=r==null?void 0:r.titleColor)!=null?T:"currentColor",p=be(d,20,l,2);p&&i.appendChild(p);let m=h("div","persona-flex-1 persona-min-w-0"),g=h("div","persona-flex persona-items-center persona-gap-2"),u=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",g.appendChild(u),!s){let j=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");j.setAttribute("data-approval-status",n.status),n.status==="approved"?(j.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",j.style.color="var(--persona-palette-colors-success-700, #15803d)",j.textContent="Approved"):n.status==="denied"?(j.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",j.style.color="var(--persona-palette-colors-error-700, #b91c1c)",j.textContent="Denied"):n.status==="timeout"&&(j.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",j.style.color="var(--persona-palette-colors-warning-700, #b45309)",j.textContent="Timeout"),g.appendChild(j)}m.appendChild(g);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=n.description,m.appendChild(v),n.parameters){let j=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(j.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(j.style.color=r.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=Uo(n.parameters),m.appendChild(j)}if(s){let j=h("div","persona-flex persona-gap-2 persona-mt-2");j.setAttribute("data-approval-buttons","true");let z=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");z.type="button",z.style.backgroundColor=(L=r==null?void 0:r.approveButtonColor)!=null?L:"var(--persona-approval-approve-bg, #22c55e)",z.style.color=(P=r==null?void 0:r.approveButtonTextColor)!=null?P:"#ffffff",z.setAttribute("data-approval-action","approve");let oe=be("shield-check",14,(W=r==null?void 0:r.approveButtonTextColor)!=null?W:"#ffffff",2);oe&&(oe.style.marginRight="4px",z.appendChild(oe));let We=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");z.appendChild(We);let je=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");je.type="button",je.style.backgroundColor=(I=r==null?void 0:r.denyButtonColor)!=null?I:"transparent",je.style.color=(O=r==null?void 0:r.denyButtonTextColor)!=null?O:"var(--persona-feedback-error, #dc2626)",je.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,je.setAttribute("data-approval-action","deny");let Ne=be("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);Ne&&(Ne.style.marginRight="4px",je.appendChild(Ne));let ge=document.createTextNode((B=r==null?void 0:r.denyLabel)!=null?B:"Deny");je.appendChild(ge),j.append(z,je),m.appendChild(j)}return a.append(i,m),o.appendChild(a),o};var Lu=e=>{let t=[];return{buttons:t,render:(r,s,o,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=s?s.isStreaming():!1,g=u=>{switch(u){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(u=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=u,v.disabled=m,i!=null&&i.fontFamily&&(v.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(u))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var Gs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Dy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ny=new Set(["step_start","execution_start"]),Fy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Oy=new Set(["step_complete","agent_turn_complete"]),$y=new Set(["flow_complete","agent_complete"]),Pu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Wu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Po=(e,t)=>{let n=e[t];return Wu(n)?n:void 0};function Zi(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ai(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function _y(e,t){return typeof t.type=="string"?t.type:e}function jy(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Uy(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Iu(e){var r,s,o,a,i;let t=Po(e,"result"),n=[Po(e,"tokens"),Po(e,"totalTokens"),t?Po(t,"tokens"):void 0,Po(e,"usage"),t?Po(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Gn(d.output))!=null?r:Gn(d.outputTokens))!=null?s:Gn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Gn(e.outputTokens))!=null?o:Gn(e.completionTokens))!=null?i:t?(a=Gn(t.outputTokens))!=null?a:Gn(t.completionTokens):void 0}function qy(e){var n,r,s,o,a;let t=Po(e,"result");return(a=(s=(r=(n=Gn(e.executionTime))!=null?n:Gn(e.executionTimeMs))!=null?r:Gn(e.execution_time))!=null?s:Gn(e.duration))!=null?a:t?(o=Gn(t.executionTime))!=null?o:Gn(t.executionTimeMs):void 0}function zy(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=zy){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ai(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!Wu(n)){Pu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=_y(t,n),s=this.now();if(Dy.has(r)){this.startRun(s);return}if(Ny.has(r)){this.run||this.startRun(s);return}if(Fy.has(r)){if(!Uy(r,n))return;let a=jy(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Zi(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ai(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Oy.has(r)){if(!this.run)return;let a=this.run,i=Iu(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Zi(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:ai(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if($y.has(r)){if(!this.run)return;let a=this.run,i=Iu(n),d=i!=null?i:a.exactOutputTokens+Zi(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:ai(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Pu.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=qy(n);return o!=null?o:r-t.startedAt}};function ts(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Vy={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Ky={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Jy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Gy=100;function Xy(e,t){let n={...Vy,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Ky}function Qy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Yy(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function Zy(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function eb(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function tb(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function nb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function rb(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function ob(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function el(e,t,n,r,s,o,a,i){var g;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");ts(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var z,oe;let u=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=be(d?"chevron-down":"chevron-right","14px","currentColor",2);C&&x.appendChild(C);let T=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),H=(z=r.timestampFormat)!=null?z:"relative";T.textContent=H==="relative"?Qy(e.timestamp,n):Yy(e.timestamp);let L=null;r.showSequenceNumbers!==!1&&(L=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(t+1));let P=Xy(e.type,r.badgeColors),W=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");W.style.backgroundColor=P.bg,W.style.color=P.text,W.style.borderColor=P.text+"50",W.textContent=e.type;let w=(oe=r.descriptionFields)!=null?oe:Jy,I=Zy(e.payload,w),O=null;I&&(O=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),O.textContent=I);let $=h("div","persona-flex-1 persona-min-w-0"),B=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),j=be("clipboard","12px","currentColor",1.5);return j&&B.appendChild(j),B.addEventListener("click",async We=>{We.stopPropagation(),await eb(tb(e)),B.innerHTML="";let je=be("check","12px","currentColor",1.5);je&&B.appendChild(je),setTimeout(()=>{B.innerHTML="";let Ne=be("clipboard","12px","currentColor",1.5);Ne&&B.appendChild(Ne)},1500)}),v.appendChild(x),v.appendChild(T),L&&v.appendChild(L),v.appendChild(W),O&&v.appendChild(O),v.appendChild($),v.appendChild(B),u.appendChild(v),d&&u.appendChild(ob(e,a,i)),u}}function Ru(e){var v,x,C,T,H;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(C=i==null?void 0:i.label)!=null?C:"",m=(H=(T=s==null?void 0:s.features)==null?void 0:T.eventStream)!=null?H:{},g=o.find(L=>L.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let L=g.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>u().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return u();function u(){let L=m.classNames,P=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ts(P,L==null?void 0:L.panel);let W=[],w="",I="",O=null,$=[],B={},j=0,z=$a(),oe=0,We=0,je=!1,Ne=null,ge=!1,ye=0,Le=new Set,He=new Map,ee="",Pe="",V=null,le,ve,fe,we,ze,Q=null,te=null,se=null;function ue(){let ne=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),me=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");ts(me,L==null?void 0:L.headerBar);let vt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(vt.textContent="Events",le=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),le.textContent="0",a){te=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),te.style.cursor="help";let Bn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Bn.textContent="Throughput",Q=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Q.textContent="-- tok/s",se=h("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),se.style.display="none",se.style.pointerEvents="none";let Qn=te,yn=se,Dn=()=>{if(!yn.textContent)return;let xr=Qn.getBoundingClientRect(),Nn=ne.getBoundingClientRect();yn.style.left=`${xr.left-Nn.left}px`,yn.style.top=`${xr.bottom-Nn.top+4}px`,yn.style.display="block"},ut=()=>{yn.style.display="none"};te.addEventListener("mouseenter",Dn),te.addEventListener("mouseleave",ut),te.appendChild(Bn),te.appendChild(Q)}let jt=h("div","persona-flex-1");ve=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Zt=h("option","");Zt.value="",Zt.textContent="All events",ve.appendChild(Zt),fe=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),fe.type="button",fe.title="Copy All";let St=be("clipboard-copy","12px","currentColor",1.5);St&&fe.appendChild(St);let wt=h("span","persona-text-xs");wt.textContent="Copy All",fe.appendChild(wt),me.appendChild(vt),me.appendChild(le),te&&me.appendChild(te),me.appendChild(jt),me.appendChild(ve),me.appendChild(fe);let ft=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ts(ft,L==null?void 0:L.searchBar);let yt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");yt&&zt.appendChild(yt),we=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ts(we,L==null?void 0:L.searchInput),we.type="text",we.placeholder="Search event payloads...",ze=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ze.type="button",ze.style.display="none";let tt=be("x","12px","currentColor",2);return tt&&ze.appendChild(tt),ft.appendChild(zt),ft.appendChild(we),ft.appendChild(ze),ne.appendChild(me),ne.appendChild(ft),se&&ne.appendChild(se),ne}let ie,re=o.find(ne=>ne.renderEventStreamToolbar);if(re!=null&&re.renderEventStreamToolbar&&s){let ne=re.renderEventStreamToolbar({config:s,defaultRenderer:()=>ue(),eventCount:t.getSize(),filteredCount:0,onFilterChange:me=>{w=me,Hn(),N()},onSearchChange:me=>{I=me,Hn(),N()}});ie=ne!=null?ne:ue()}else ie=ue();let Qe=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Qe.style.display="none";function Ie(){if(!a||!Q||!te)return;let ne=a();Q.textContent=nb(ne);let me=rb(ne);se&&(se.textContent=me,me||(se.style.display="none")),me?te.setAttribute("aria-label",me):te.removeAttribute("aria-label")}let ce=h("div","persona-flex-1 persona-min-h-0 persona-relative"),G=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let $e=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ts($e,L==null?void 0:L.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Et=be(l,"14px","currentColor",2);Et&&$e.appendChild(Et);let de=h("span","");de.textContent=p,$e.appendChild(de);let ae=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",ce.appendChild(G),ce.appendChild(ae),ce.appendChild($e),P.setAttribute("tabindex","0"),P.appendChild(ie),P.appendChild(Qe),P.appendChild(ce);function Mn(){let ne=t.getAll(),me={};for(let wt of ne)me[wt.type]=(me[wt.type]||0)+1;let vt=Object.keys(me).sort(),jt=vt.length!==$.length||!vt.every((wt,ft)=>wt===$[ft]),Zt=!jt&&vt.some(wt=>me[wt]!==B[wt]),hn=ne.length!==Object.values(B).reduce((wt,ft)=>wt+ft,0);if(!jt&&!Zt&&!hn||($=vt,B=me,!ve))return;let St=ve.value;if(ve.options[0].textContent="All events",jt){for(;ve.options.length>1;)ve.remove(1);for(let wt of vt){let ft=h("option","");ft.value=wt,ft.textContent=`${wt} (${me[wt]||0})`,ve.appendChild(ft)}St&&vt.includes(St)?ve.value=St:St&&(ve.value="",w="")}else for(let wt=1;wt<ve.options.length;wt++){let ft=ve.options[wt];ft.textContent=`${ft.value} (${me[ft.value]||0})`}}function Ot(){let ne=t.getAll();if(w&&(ne=ne.filter(me=>me.type===w)),I){let me=I.toLowerCase();ne=ne.filter(vt=>vt.type.toLowerCase().includes(me)||vt.payload.toLowerCase().includes(me))}return ne}function ln(){return w!==""||I!==""}function Hn(){j=0,oe=0,z.resume(),$e.style.display="none"}function Xn(ne){Le.has(ne)?Le.delete(ne):Le.add(ne),V=ne;let me=G.scrollTop,vt=z.isFollowing();ge=!0,z.pause(),N(),G.scrollTop=me,vt&&z.resume(),ge=!1}function Ue(){return Ds(G,50)}function N(){We=Date.now(),je=!1,Ie(),Mn();let ne=t.getEvictedCount();ne>0?(Qe.textContent=`${ne.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",W=Ot();let me=W.length,vt=t.getSize()>0;le&&(le.textContent=String(t.getSize())),me===0&&vt&&ln()?(ae.textContent=I?`No events matching '${I}'`:"No events matching filter",ae.style.display="",G.style.display="none"):(ae.style.display="none",G.style.display=""),fe&&(fe.title=ln()?`Copy Filtered (${me})`:"Copy All"),d&&!z.isFollowing()&&me>j&&(oe+=me-j,de.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",$e.style.display=""),j=me;let jt=t.getAll(),Zt=jt.length>0?jt[0].timestamp:0,hn=new Set(W.map(ft=>ft.id));for(let ft of Le)hn.has(ft)||Le.delete(ft);let St=w!==ee||I!==Pe,wt=He.size===0&&W.length>0;if(St||wt||W.length===0){G.innerHTML="",He.clear();let ft=document.createDocumentFragment();for(let yt=0;yt<W.length;yt++){let zt=el(W[yt],yt,Zt,m,Le,Xn,o,s);He.set(W[yt].id,zt),ft.appendChild(zt)}G.appendChild(ft),ee=w,Pe=I,V=null}else{if(V!==null){let yt=He.get(V);if(yt&&yt.parentNode===G){let zt=W.findIndex(tt=>tt.id===V);if(zt>=0){let tt=el(W[zt],zt,Zt,m,Le,Xn,o,s);G.insertBefore(tt,yt),yt.remove(),He.set(V,tt)}}V=null}let ft=new Set(W.map(yt=>yt.id));for(let[yt,zt]of He)ft.has(yt)||(zt.remove(),He.delete(yt));for(let yt=0;yt<W.length;yt++){let zt=W[yt];if(!He.has(zt.id)){let tt=el(zt,yt,Zt,m,Le,Xn,o,s);He.set(zt.id,tt),G.appendChild(tt)}}}z.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Ae(){if(Date.now()-We>=Gy){Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),N();return}je||(je=!0,Ne=requestAnimationFrame(()=>{Ne=null,N()}))}let Be=(ne,me)=>{if(!fe)return;fe.innerHTML="";let vt=be(ne,"12px","currentColor",1.5);vt&&fe.appendChild(vt);let jt=h("span","persona-text-xs");jt.textContent="Copy All",fe.appendChild(jt),setTimeout(()=>{fe.innerHTML="";let Zt=be("clipboard-copy","12px","currentColor",1.5);Zt&&fe.appendChild(Zt);let hn=h("span","persona-text-xs");hn.textContent="Copy All",fe.appendChild(hn),fe.disabled=!1},me)},De=async()=>{if(fe){fe.disabled=!0;try{let ne;ln()?ne=W:n?(ne=await n(),ne.length===0&&(ne=t.getAll())):ne=t.getAll();let me=ne.map(vt=>{try{return JSON.parse(vt.payload)}catch{return vt.payload}});await navigator.clipboard.writeText(JSON.stringify(me,null,2)),Be("check",1500)}catch{Be("x",1500)}}},_e=()=>{ve&&(w=ve.value,Hn(),N())},dt=()=>{!we||!ze||(ze.style.display=we.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{I=we.value,Hn(),N()},150))},rt=()=>{!we||!ze||(we.value="",I="",ze.style.display="none",O&&clearTimeout(O),Hn(),N())},At=()=>{if(ge)return;let ne=G.scrollTop,{action:me,nextLastScrollTop:vt}=_a({following:z.isFollowing(),currentScrollTop:ne,lastScrollTop:ye,nearBottom:Ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ye=vt,me==="resume"?(z.resume(),oe=0,$e.style.display="none"):me==="pause"&&(z.pause(),d&&(de.textContent=p,$e.style.display=""))},_t=ne=>{let me=ja({following:z.isFollowing(),deltaY:ne.deltaY,nearBottom:Ue(),resumeWhenNearBottom:!0});me==="pause"?(z.pause(),d&&(de.textContent=p,$e.style.display="")):me==="resume"&&(z.resume(),oe=0,$e.style.display="none")},q=()=>{d&&(G.scrollTop=G.scrollHeight,z.resume(),oe=0,$e.style.display="none")},$t=ne=>{let me=ne.target;if(!me||me.closest("button"))return;let vt=me.closest("[data-event-id]");if(!vt)return;let jt=vt.getAttribute("data-event-id");jt&&Xn(jt)},Ye=ne=>{if((ne.metaKey||ne.ctrlKey)&&ne.key==="f"){ne.preventDefault(),we==null||we.focus(),we==null||we.select();return}ne.key==="Escape"&&(we&&document.activeElement===we?(rt(),we.blur(),P.focus()):r&&r())};fe&&fe.addEventListener("click",De),ve&&ve.addEventListener("change",_e),we&&we.addEventListener("input",dt),ze&&ze.addEventListener("click",rt),G.addEventListener("scroll",At),G.addEventListener("wheel",_t,{passive:!0}),G.addEventListener("click",$t),$e.addEventListener("click",q),P.addEventListener("keydown",Ye);function Dt(){O&&clearTimeout(O),Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),je=!1,He.clear(),fe&&fe.removeEventListener("click",De),ve&&ve.removeEventListener("change",_e),we&&we.removeEventListener("input",dt),ze&&ze.removeEventListener("click",rt),G.removeEventListener("scroll",At),G.removeEventListener("wheel",_t),G.removeEventListener("click",$t),$e.removeEventListener("click",q),P.removeEventListener("keydown",Ye)}return{element:P,update:Ae,destroy:Dt}}}function Hu(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Bu=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Hu(e,t)});if(p)return p}return Hu(e,t)};var tl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},lo=new tl;lo.register("PersonaArtifactCard",Bu);function sb(e){var s;let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Du(e,t){var ve,fe,we,ze;let n=(fe=(ve=e.features)==null?void 0:ve.artifacts)==null?void 0:fe.layout,s=((we=n==null?void 0:n.toolbarPreset)!=null?we:"default")==="document",o=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?_o(e.markdown):null,i=Ts(e.sanitize),d=Q=>{let te=a?a(Q):jo(Q);return i?i(te):te},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};l&&l.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let m=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let g=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let u=h("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let x="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=s?qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):qt({icon:"eye",label:"Rendered view"}),H=s?qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):qt({icon:"code-2",label:"Source"}),L=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),P=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(W&&w&&w.length>0),O=null,$,B=null,j=null;if(s&&(P||W)&&!I){if($=P?Ga({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Q=be("chevron-down",14,"currentColor",2);Q&&$.appendChild(Q)}}else s&&I?(O=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=P?Ga({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B=qt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),O.append($,B)):s?$=qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=qt({icon:"copy",label:"Copy"});let z=s?qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):qt({icon:"refresh-cw",label:"Refresh"}),oe=s?qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):qt({icon:"x",label:"Close"}),We=()=>{var ie,re,Qe;let Q=(ie=He.find(Ie=>Ie.id===ee))!=null?ie:He[He.length-1],te=(re=Q==null?void 0:Q.id)!=null?re:null,se=(Q==null?void 0:Q.artifactType)==="markdown"&&(Qe=Q.markdown)!=null?Qe:"",ue=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:se,jsonPayload:ue,id:te}},je=async()=>{var ie;let{markdown:Q,jsonPayload:te}=We(),se=(ie=He.find(re=>re.id===ee))!=null?ie:He[He.length-1],ue=(se==null?void 0:se.artifactType)==="markdown"?Q:se?te:"";try{await navigator.clipboard.writeText(ue)}catch{}};if($.addEventListener("click",async()=>{let Q=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Q&&I){let{markdown:te,jsonPayload:se,id:ue}=We();try{await Q({actionId:"primary",artifactId:ue,markdown:te,jsonPayload:se})}catch{}return}await je()}),B&&(w!=null&&w.length)){let Q=()=>{var se;return(se=m.closest("[data-persona-root]"))!=null?se:document.body},te=()=>{j=Mo({items:w.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:ue,jsonPayload:ie,id:re}=We(),Qe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Qe?await Qe({actionId:se,artifactId:re,markdown:ue,jsonPayload:ie}):se==="markdown"||se==="md"?await navigator.clipboard.writeText(ue):se==="json"||se==="source"?await navigator.clipboard.writeText(ie):await navigator.clipboard.writeText(ue||ie)}catch{}},anchor:O!=null?O:B,position:"bottom-right",portal:Q()})};m.isConnected?te():requestAnimationFrame(te),B.addEventListener("click",se=>{se.stopPropagation(),j==null||j.toggle()})}z.addEventListener("click",async()=>{var Q;try{await((Q=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Q.call(n))}catch{}V()}),oe.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let Ne=()=>{s&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),H.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Ne(),V()}),H.addEventListener("click",()=>{x="source",Ne(),V()});let ge=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(g.replaceChildren(),C.append(T,H),O?L.append(O,z,oe):L.append($,z,oe),g.append(C,ge,L),Ne()):(g.appendChild(u),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let ye=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ye.style.paddingLeft=o,ye.style.paddingRight=o,Le.style.padding=o),m.appendChild(g),m.appendChild(ye),m.appendChild(Le);let He=[],ee=null,Pe=!1,V=()=>{var ue,ie,re,Qe;let Q=s&&He.length<=1;ye.classList.toggle("persona-hidden",Q),ye.replaceChildren();for(let Ie of He){let ce=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ce.type="button",ce.textContent=Ie.title||Ie.id.slice(0,8),Ie.id===ee&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(Ie.id)),ye.appendChild(ce)}Le.replaceChildren();let te=ee&&He.find(Ie=>Ie.id===ee)||He[He.length-1];if(!te)return;if(s){let Ie=te.artifactType==="markdown"?"MD":(ue=te.component)!=null?ue:"Component",G=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${G} \xB7 ${Ie}`}else u.textContent="Artifacts";if(te.artifactType==="markdown"){if(s&&x==="source"){let ce=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ce.textContent=(ie=te.markdown)!=null?ie:"",Le.appendChild(ce);return}let Ie=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ie.innerHTML=d((re=te.markdown)!=null?re:""),Le.appendChild(Ie);return}let se=te.component?lo.get(te.component):void 0;if(se){let ce={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let G=se((Qe=te.props)!=null?Qe:{},ce);if(G){Le.appendChild(G);return}}catch{}}Le.appendChild(sb(te))},le=()=>{var te;let Q=He.length>0;if(m.classList.toggle("persona-hidden",!Q),l){let se=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,ie=((te=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Q&&ie&&Pe?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(Q){var te,se,ue;He=Q.artifacts,ee=(ue=(se=Q.selectedId)!=null?se:(te=Q.artifacts[Q.artifacts.length-1])==null?void 0:te.id)!=null?ue:null,He.length>0&&(Pe=!0),V(),le()},setMobileOpen(Q){Pe=Q,!Q&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):le()}}}function ir(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Nu(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ir(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function ab(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ii(e,t){var d,l,p,m,g,u,v,x,C,T;if(!ir(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),ab(e),Nu(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=n==null?void 0:n.paneBackground)==null?void 0:u.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(C=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Nu(e,t)}var Fu=["panel","seamless"];function li(e,t){var i,d,l,p,m,g;for(let u of Fu)e.classList.remove(`persona-artifact-appearance-${u}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!ir(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",s=Fu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Ou(e,t){var n,r,s;return!t||!ir(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function ib(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function lb(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function cb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function db(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function $u(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function _u(e,t,n,r,s,o){let a=ib(s,200),i=db(t,n,r,200);i=Math.max(a,i);let d=lb(o);return d!==null&&(i=Math.min(i,d)),cb(e,a,i)}var ju={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},nl=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,C;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=ju[a])!=null?x:ju.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=h("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var w,I;let H=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");H.htmlFor=`${t.id}-${a}-${T.name}`;let L=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=T.label,H.appendChild(L);let P=(w=T.type)!=null?w:"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${T.name}`,W.name=T.name,W.placeholder=(I=T.placeholder)!=null?I:"",T.required&&(W.required=!0),H.appendChild(W),p.appendChild(H)});let m=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");u.type="submit",u.textContent=(C=i.submitLabel)!=null?C:"Submit",m.appendChild(g),m.appendChild(u),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async T=>{var W,w;T.preventDefault();let H=(W=n.formEndpoint)!=null?W:"/form",L=new FormData(p),P={};L.forEach((I,O)=>{P[O]=I}),P.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let I=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let O=await I.json();g.textContent=(w=O.message)!=null?w:"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await r.sendMessage(String(O.nextPrompt))}catch(I){g.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var rl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},ci=new rl;var Uu=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var pb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ub=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},di=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=pb(e),n=ub(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},ol=e=>typeof e=="string"?e:e==null?"":String(e),ns={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ol(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=ol(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ol(n.text)}}},qu=e=>Array.isArray(e)?e.map(t=>String(t)):[],pi=e=>{let t=new Set(qu(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(qu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var mb=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},gb=e=>e.map(t=>({...t,streaming:!1})),fb=e=>e.map(t=>({...t,status:"complete"})),sl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?mb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?gb(n.messages):void 0,artifacts:n.artifacts?fb(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as hb,STR as yb,OBJ as bb}from"partial-json";function xb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function vb(e,t){if(!xb(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function al(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=hb(n,yb|bb),o=vb(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function wb(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function il(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=lo.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Cb(){let e=al();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function zu(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function ll(e){let t=zu(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function cl(e){let t=zu(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Ab=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function dl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Ab}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,u.appendChild(x),g.appendChild(u);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let w=1;w<=5;w++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),I.title=l[w-1],I.dataset.rating=String(w),I.innerHTML=`
|
|
23
|
+
`,n.addEventListener("click",t);let r=o=>{var k,P,W,A,I,O,D,R,_,z,oe,Re,Ue,Fe;let a=(k=o.launcher)!=null?k:{},i=an(o),d=n.querySelector("[data-role='launcher-title']");if(d){let ge=(P=a.title)!=null?P:"Chat Assistant";d.textContent=ge,d.setAttribute("title",ge)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ge=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=ge,l.setAttribute("title",ge)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ge=(A=a.agentIconSize)!=null?A:"40px";if(m.style.height=ge,m.style.width=ge,m.innerHTML="",a.agentIconName){let ye=parseFloat(ge)||24,Le=be(a.agentIconName,ye*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(m.appendChild(Le),m.style.display=""):(m.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ge=(D=a.agentIconSize)!=null?D:"40px";g.style.height=ge,g.style.width=ge,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let ge=(R=a.callToActionIconSize)!=null?R:"32px";u.style.height=ge,u.style.width=ge,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let ye=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,ye=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Le=parseFloat(ge)||24,Be=Math.max(Le-ye,8),ee=be(a.callToActionIconName,Be,"currentColor",2);ee?u.appendChild(ee):u.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else u.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let v=a.position&&br[a.position]?br[a.position]:br["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",C="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?C:`${x} ${v}`,i||(n.style.zIndex=String((oe=a.zIndex)!=null?oe:fn));let T="1px solid var(--persona-border, #e5e7eb)",H="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Re=a.border)!=null?Re:T,n.style.boxShadow=(Ue=a.shadow)!=null?Ue:H,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(Fe=a.collapsedMaxWidth)!=null?Fe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var jh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ja=(e,t={})=>{var x,C,T,H,k,P;let{showClose:n=!0,wrapperClassName:r=jh,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(C=s!=null?s:a.closeButtonSize)!=null?C:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(T=a.closeButtonTooltipText)!=null?T:"Close chat",m=(H=a.closeButtonShowTooltip)!=null?H:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let g=(k=a.closeButtonIconName)!=null?k:"x",u=(P=a.closeButtonIconText)!=null?P:"\xD7";l.style.color=a.closeButtonColor||En.actionIconColor;let v=be(g,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",A=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${A}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let W=null,A=()=>{if(W)return;let O=l.ownerDocument,D=O.body;if(!D)return;W=Sr(O,"div","persona-clear-chat-tooltip"),W.textContent=p;let R=Sr(O,"div");R.className="persona-clear-chat-tooltip-arrow",W.appendChild(R);let _=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(eo),W.style.left=`${_.left+_.width/2}px`,W.style.top=`${_.top-8}px`,W.style.transform="translate(-50%, -100%)",D.appendChild(W)},I=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",A),d.addEventListener("mouseleave",I),l.addEventListener("focus",A),l.addEventListener("blur",I),d._cleanupTooltip=()=>{I(),d.removeEventListener("mouseenter",A),d.removeEventListener("mouseleave",I),l.removeEventListener("focus",A),l.removeEventListener("blur",I)}}return{button:l,wrapper:d}},Uh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ga=(e,t={})=>{var W,A,I,O,D,R,_,z,oe,Re,Ue,Fe,ge;let{wrapperClassName:n=Uh,buttonSize:r,iconSize:s="20px"}=t,a=(A=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?A:{},i=(I=r!=null?r:a.size)!=null?I:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",l=(D=a.iconColor)!=null?D:"",p=(R=a.backgroundColor)!=null?R:"",m=(_=a.borderWidth)!=null?_:"",g=(z=a.borderColor)!=null?z:"",u=(oe=a.borderRadius)!=null?oe:"",v=(Re=a.paddingX)!=null?Re:"",x=(Ue=a.paddingY)!=null?Ue:"",C=(Fe=a.tooltipText)!=null?Fe:"Clear chat",T=(ge=a.showTooltip)!=null?ge:!0,H=h("div",n),k=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");k.style.height=i,k.style.width=i,k.type="button",k.setAttribute("aria-label",C),k.style.color=l||En.actionIconColor;let P=be(d,s,"currentColor",1);if(P&&(P.style.display="block",k.appendChild(P)),p&&(k.style.backgroundColor=p,k.classList.remove("hover:persona-bg-gray-100")),m||g){let ye=m||"0px",Le=g||"transparent";k.style.border=`${ye} solid ${Le}`,k.classList.remove("persona-border-none")}if(u&&(k.style.borderRadius=u,k.classList.remove("persona-rounded-full")),v&&(k.style.paddingLeft=v,k.style.paddingRight=v),x&&(k.style.paddingTop=x,k.style.paddingBottom=x),H.appendChild(k),T&&C){let ye=null,Le=()=>{if(ye)return;let ee=k.ownerDocument,Pe=ee.body;if(!Pe)return;ye=Sr(ee,"div","persona-clear-chat-tooltip"),ye.textContent=C;let V=Sr(ee,"div");V.className="persona-clear-chat-tooltip-arrow",ye.appendChild(V);let le=k.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(eo),ye.style.left=`${le.left+le.width/2}px`,ye.style.top=`${le.top-8}px`,ye.style.transform="translate(-50%, -100%)",Pe.appendChild(ye)},Be=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};H.addEventListener("mouseenter",Le),H.addEventListener("mouseleave",Be),k.addEventListener("focus",Le),k.addEventListener("blur",Be),H._cleanupTooltip=()=>{Be(),H.removeEventListener("mouseenter",Le),H.removeEventListener("mouseleave",Be),k.removeEventListener("focus",Le),k.removeEventListener("blur",Be)}}return{button:k,wrapper:H}};var En={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ro=e=>{var W,A,I,O,D,R,_,z,oe,Re,Ue,Fe,ge,ye,Le,Be;let{config:t,showClose:n=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(W=t==null?void 0:t.launcher)!=null?W:{},o=(A=s.headerIconSize)!=null?A:"48px",a=(I=s.closeButtonPlacement)!=null?I:"inline",i=(O=s.headerIconHidden)!=null?O:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(o)||24,Pe=be(d,ee*.6,"currentColor",1);Pe?l.replaceChildren(Pe):l.textContent=(R=(D=t==null?void 0:t.launcher)==null?void 0:D.agentIconText)!=null?R:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let ee=h("img");ee.src=t.launcher.iconUrl,ee.alt="",ee.className="persona-rounded-xl persona-object-cover",ee.style.height=o,ee.style.width=o,l.replaceChildren(ee)}else l.textContent=(oe=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?oe:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=h("span","persona-text-base persona-font-semibold");m.style.color=En.titleColor,m.textContent=(Ue=(Re=t==null?void 0:t.launcher)==null?void 0:Re.title)!=null?Ue:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=En.subtitleColor,g.textContent=(ge=(Fe=t==null?void 0:t.launcher)==null?void 0:Fe.subtitle)!=null?ge:"Here to help you get answers fast",p.append(m,g),i?r.append(p):r.append(l,p);let u=(ye=s.clearChat)!=null?ye:{},v=(Le=u.enabled)!=null?Le:!0,x=(Be=u.placement)!=null?Be:"inline",C=null,T=null;if(v){let Pe=Ga(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=Pe.button,T=Pe.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let H=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:P}=Ja(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&r.appendChild(P),{header:r,iconHolder:l,headerTitle:m,headerSubtitle:g,closeButton:k,closeButtonWrapper:P,clearChatButton:C,clearChatButtonWrapper:T}},Xo=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function ko(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(eo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of t){if(u.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let C=be(u.icon,16,"currentColor",1.5);C&&v.appendChild(C)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",C=>{C.stopPropagation(),p(),n(u.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:g}}function qt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=be(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function Xa(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=be(t,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=h("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))p.setAttribute(g,u);return p}function Qa(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=qt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=h("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function l(p){a=p,d()}return{element:o,setSelected:l}}function _i(e){var u,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let m=be(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,C;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(C=d.border)!=null?C:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=ko({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let C=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var su=e=>{var r;let t=ro({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function qh(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=be(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=ko({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var au=e=>{var H,k,P,W,A,I,O,D,R;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(H=t==null?void 0:t.launcher)!=null?H:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,p;if(d)l=_i({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=En.titleColor,p=(P=l.querySelector(".persona-combo-btn-label"))!=null?P:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=En.titleColor,p.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(p),qh(l,s==null?void 0:s.trailingActions,(A=s==null?void 0:s.onAction)!=null?A:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let z=s.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||z()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),z())})}let _=s==null?void 0:s.titleRowHover;_&&(l.style.borderRadius=(I=_.borderRadius)!=null?I:"10px",l.style.padding=(O=_.padding)!=null?O:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var z,oe;l.style.backgroundColor=(z=_.background)!=null?z:"",l.style.borderColor=(oe=_.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(D=a.closeButtonSize)!=null?D:"32px",g=h("div",""),u=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||En.actionIconColor;let v=(R=a.closeButtonIconName)!=null?R:"x",x=be(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let C=h("div");C.style.display="none";let T=h("span");return T.style.display="none",{header:i,iconHolder:C,headerTitle:p,headerSubtitle:T,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},ji={default:su,minimal:au},iu=e=>{var t;return(t=ji[e])!=null?t:ji.default},Vs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=h("div");p.style.display="none";let m=h("span"),g=h("span"),u=h("button");u.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=iu(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Ya=e=>{var a,i;let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},Za=e=>{var W,A,I,O,D,R,_,z,oe,Re,Ue,Fe;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(A=t.useIcon)!=null?A:!1,r=(I=t.iconText)!=null?I:"\u2191",s=t.iconName,o=(O=t.stopIconName)!=null?O:"square",a=(D=t.tooltipText)!=null?D:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(z=(_=e==null?void 0:e.copy)==null?void 0:_.sendButtonLabel)!=null?z:"Send",l=(Re=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?Re:"Stop",p=(Ue=t.showTooltip)!=null?Ue:!1,m=(Fe=t.size)!=null?Fe:"40px",g=t.backgroundColor,u=t.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let C=null,T=null;if(n){x.style.width=m,x.style.height=m,x.style.minWidth=m,x.style.minHeight=m,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",u?x.style.color=u:x.style.color="var(--persona-button-primary-fg, #ffffff)";let ge=parseFloat(m)||24,ye=(u==null?void 0:u.trim())||"currentColor";s?(C=be(s,ge,ye,2),C?x.appendChild(C):x.textContent=r):x.textContent=r,T=be(o,ge,ye,2),g?x.style.backgroundColor=g:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,u?x.style.color=u:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let H=null;p&&a&&(H=h("div","persona-send-button-tooltip"),H.textContent=a,v.appendChild(H)),x.setAttribute("aria-label",a),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:ge=>{if(ge===k)return;k=ge;let ye=ge==="stop"?i:a;if(x.setAttribute("aria-label",ye),H&&(H.textContent=ye),n){if(C&&T){let Le=ge==="stop"?T:C;x.replaceChildren(Le)}}else x.textContent=ge==="stop"?l:d}}},ei=e=>{var H,k,P,W,A,I,O,D,R,_,z,oe;let t=(H=e==null?void 0:e.voiceRecognition)!=null?H:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||s))return null;let a=(W=(P=e==null?void 0:e.sendButton)==null?void 0:P.size)!=null?W:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(A=t.iconName)!=null?A:"mic",p=(I=t.iconSize)!=null?I:a,m=parseFloat(p)||24,g=(D=t.backgroundColor)!=null?D:(O=e==null?void 0:e.sendButton)==null?void 0:O.backgroundColor,u=(_=t.iconColor)!=null?_:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let x=be(l,m,u||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let C=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((oe=t.showTooltip)!=null?oe:!1)&&C){let Re=h("div","persona-send-button-tooltip");Re.textContent=C,i.appendChild(Re)}return{button:d,wrapper:i}},ti=e=>{var v,x,C,T,H,k,P,W;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(C=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?C:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((T=t.allowedTypes)!=null?T:Nr).join(","),s.multiple=((H=t.maxFiles)!=null?H:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(k=t.buttonTooltipText)!=null?k:"Attach file");let i=(P=t.buttonIconName)!=null?P:"paperclip",d=n,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=be(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",A=>{A.preventDefault(),s.click()}),o.appendChild(a);let g=(W=t.buttonTooltipText)!=null?W:"Attach file",u=h("div","persona-send-button-tooltip");return u.textContent=g,o.appendChild(u),{button:a,wrapper:o,input:s,previewsContainer:r}},ni=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=h("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},ri=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ks=e=>{var v,x,C,T,H,k;let{config:t}=e,n=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let r=ri(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Ya(t);a();let i=Za(t),d=ei(t),l=ti(t),p=ni(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let m=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(g,u),s.append(m),s.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(C=l==null?void 0:l.button)!=null?C:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(H=l==null?void 0:l.input)!=null?H:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var lu=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=h("span","persona-pill-peek__icon"),n=be("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=be("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},cu=e=>{var v,x,C,T,H,k;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=ri();r.style.display="none";let s=ni(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Ya(t);o.style.maxHeight="100px",a();let i=Za(t),d=ei(t),l=ti(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=h("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let g=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(m,o,g),l&&n.append(l.previewsContainer),n.append(p,r,s);let u=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(C=l==null?void 0:l.button)!=null?C:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(H=l==null?void 0:l.input)!=null?H:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var du=e=>{var p,m,g,u,v,x,C,T,H,k,P,W,A,I,O,D,R;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=an(e);if(no(e)){let _=(u=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?u:{},z=h("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(v=_.expandedSize)!=null?v:"anchored",z.style.zIndex=String((C=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?C:fn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",z.appendChild(oe);let Re=h("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(T=_.expandedSize)!=null?T:"anchored",Re.style.zIndex=String((k=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?k:fn),{wrapper:z,panel:oe,pillRoot:Re}}if(n){let _=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(z),{wrapper:_,panel:z}}if(!t){let _=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.width)!=null?W:"100%";return _.style.width=oe,z.style.width="100%",_.appendChild(z),{wrapper:_,panel:z}}let s=(A=e==null?void 0:e.launcher)!=null?A:{},o=s.position&&br[s.position]?br[s.position]:br["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((O=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?O:fn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?R:e==null?void 0:e.launcherWidth,l=d!=null?d:sr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},zh=(e,t)=>{var P,W,A,I,O,D,R,_,z;let n=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Ja(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(A=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.clearChat)==null?void 0:W.enabled)!=null?A:!0,a=null,i=null;if(o){let oe=Ga(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(O=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?O:"Hello \u{1F44B}";let g=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(R=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",p.append(m,g);let u=h("div","persona-flex persona-flex-col persona-gap-3"),v=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let C=h("div","persona-composer-overlay persona-pointer-events-none");C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20";let T=cu({config:e}),{root:H,textNode:k}=lu();return n.append(d,s,l,C),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:C,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:m,introSubtitle:g,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:H,peekTextNode:k}},pu=(e,t=!0)=>{var C,T,H,k,P,W,A,I,O;if(no(e))return zh(e,t);let n=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let r=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,o=r?Vs(e,r,{showClose:t}):ro({config:e,showClose:t}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=an(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?k:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let p=h("div","persona-flex persona-flex-col persona-gap-3"),m=(A=e==null?void 0:e.layout)==null?void 0:A.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=Ks({config:e}),v=((O=e==null?void 0:e.layout)==null?void 0:O.showFooter)!==!1;s?Xo(n,o,e):(o.header.style.display="none",Xo(n,o,e)),n.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(u.footer.style.display="none"),n.append(u.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Vh=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Kh=(e,t)=>{if(!e)return null;let n=Vh(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Jh=(e,t)=>{let n=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Gh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Ui=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},qi=320,mu=320,Xh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Qh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Yh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Zh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),ey=(e,t,n)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let l=h("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${qi}px`,l.style.maxHeight=`${mu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),Gh(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},ty=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!Ui(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${qi}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ny=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!Ui(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${qi}px`,s.style.maxHeight=`${mu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ry=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!Ui(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Qo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},gu=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Qo};if(t){let s=t(r);if(s!==null)return s}return Qo()},oy=(e,t)=>{let n=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},uu=(e,t)=>{let n=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},sy=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},fu=(e,t,n)=>{var u,v,x,C,T,H;let r=(u=t.showCopy)!=null?u:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let k=h("div");return k.style.display="none",k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id),k}let a=(C=t.visibility)!=null?C:"hover",i=(T=t.align)!=null?T:"right",d=(H=t.layout)!=null?H:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let g=(k,P,W)=>{let A=qt({icon:k,label:P,size:14,className:"persona-message-action-btn"});return A.setAttribute("data-action",W),A};return r&&m.appendChild(g("copy","Copy message","copy")),s&&m.appendChild(g("thumbs-up","Upvote","upvote")),o&&m.appendChild(g("thumbs-down","Downvote","downvote")),m},Js=(e,t,n,r,s,o)=>{var ee,Pe,V,le,ve,fe,Ce,Ve,X,te,se,ue,ie,re,Qe,Ie,ce;let a=n!=null?n:{},i=(ee=a.layout)!=null?ee:"bubble",d=a.avatar,l=a.timestamp,p=(Pe=d==null?void 0:d.show)!=null?Pe:!1,m=(V=l==null?void 0:l.show)!=null?V:!1,g=(le=d==null?void 0:d.position)!=null?le:"left",u=(ve=l==null?void 0:l.position)!=null?ve:"below",v=sy(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=Xh(e),T=(Ce=(fe=e.content)==null?void 0:fe.trim())!=null?Ce:"",k=C.length>0&&T===Ia,P=qa((X=(Ve=o==null?void 0:o.widgetConfig)==null?void 0:Ve.features)==null?void 0:X.streamAnimation),W=(ue=(se=(te=o==null?void 0:o.widgetConfig)==null?void 0:te.features)==null?void 0:se.streamAnimation)==null?void 0:ue.plugins,A=e.role==="assistant"&&P.type!=="none"?_s(P.type,W):null,I=e.role==="assistant"&&((ie=A==null?void 0:A.isAnimating)==null?void 0:ie.call(A,e))===!0,O=e.role==="assistant"&&A!==null&&(!!e.streaming||I);O&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),O&&A&&(A.containerClass&&D.classList.add(A.containerClass),D.style.setProperty("--persona-stream-step",`${P.speed}ms`),D.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let R=O?za((re=e.content)!=null?re:"",P.buffer,A,e,!!e.streaming):(Qe=e.content)!=null?Qe:"",_=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=_;O&&(A==null?void 0:A.wrap)==="char"?z=js(_,"char",e.id,{skipTags:A.skipTags}):O&&(A==null?void 0:A.wrap)==="word"&&(z=js(_,"word",e.id,{skipTags:A.skipTags}));let oe=null;if(k?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",D.appendChild(oe)):D.innerHTML=z,O&&(A!=null&&A.useCaret)&&!k&&T){let J=Va(),_e=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=_e[_e.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(J,Et.nextSibling);else{let de=D.lastElementChild;de?de.appendChild(J):D.appendChild(J)}}if(m&&u==="inline"&&e.createdAt){let J=uu(e,l);J.classList.add("persona-ml-2","persona-inline"),D.appendChild(J)}if(C.length>0){let J=ey(C,!k&&!!T,()=>{k&&oe&&(oe.style.display="")});J?x.appendChild(J):k&&oe&&(oe.style.display="")}let Re=Qh(e);if(Re.length>0){let J=ty(Re);J&&x.appendChild(J)}let Ue=Yh(e);if(Ue.length>0){let J=ny(Ue);J&&x.appendChild(J)}let Fe=Zh(e);if(Fe.length>0){let J=ry(Fe);J&&x.appendChild(J)}if(x.appendChild(D),m&&u==="below"&&e.createdAt){let J=uu(e,l);J.classList.add("persona-mt-1"),x.appendChild(J)}let ge=e.role==="assistant"?Kh(e.stopReason,(ce=(Ie=o==null?void 0:o.widgetConfig)==null?void 0:Ie.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(R&&R.trim()),_e=P.placeholder==="skeleton",Et=_e&&P.buffer==="line"&&J;if(J)Et&&x.appendChild(Us());else if(_e)x.appendChild(Us());else{let de=gu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);de&&x.appendChild(de)}}if(ge&&e.stopReason&&!e.streaming&&(T||(D.style.display="none"),x.appendChild(Jh(e.stopReason,ge))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=fu(e,r,s);x.appendChild(J)}if(!p||e.role==="system")return x;let Le=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Be=oy(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Le.append(x,Be):Le.append(Be,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},ay=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Js(e,t,n,r,s,o)};var Yo=new Set,iy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ly=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
+
`):""},hu=(e,t)=>{let n=Yo.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=be(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},zi=(e,t)=>{var Ue,Fe,ge,ye,Le,Be,ee,Pe,V,le,ve;let n=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(Fe=(Ue=t==null?void 0:t.features)==null?void 0:Ue.reasoningDisplay)!=null?Fe:{},o=s.expandable!==!1,a=o&&Yo.has(e.id),i=n.status!=="complete",d=ly(e,(ge=s.previewMaxLines)!=null?ge:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",u=(ye=t==null?void 0:t.reasoning)!=null?ye:{},v=String((Le=n.startedAt)!=null?Le:Date.now()),x=()=>{let fe=h("span","");return fe.setAttribute("data-tool-elapsed",v),fe.textContent=Ma(n),fe},C=(Be=u.renderCollapsedSummary)==null?void 0:Be.call(u,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ma(n),createElapsedElement:x});typeof C=="string"&&C.trim()?(m.textContent=C,p.appendChild(m)):C instanceof HTMLElement?p.appendChild(C):(m.textContent=g,p.appendChild(m));let T=h("span","persona-text-xs persona-text-persona-primary");T.textContent=Wp(n),p.appendChild(T);let H=(ee=s.loadingAnimation)!=null?ee:"none",k=u.activeTextTemplate,P=u.completeTextTemplate,W=i?k:P,A=C instanceof HTMLElement,I=(fe,Ce,Ve)=>{let X=Ve;for(let te of Ce){let se=h("span","persona-tool-char");se.style.setProperty("--char-index",String(X)),se.textContent=te===" "?"\xA0":te,fe.appendChild(se),X++}return X},O=(fe,Ce)=>{m.textContent="";let Ve=ka(fe,""),X=0;for(let te of Ve){let se=te.styles.length>0?(()=>{let ue=h("span",te.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(ue),ue})():m;if(te.isDuration&&i)se.appendChild(x());else{let ue=te.isDuration?Ma(n):te.text;Ce?X=I(se,ue,X):se.appendChild(document.createTextNode(ue))}}};if(!A&&W)if(T.style.display="none",m.style.display="",i&&H!=="none"){let fe=(Pe=u.loadingAnimationDuration)!=null?Pe:2e3;m.setAttribute("data-preserve-animation","true"),H==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),O(W,!1)):(m.classList.add(`persona-tool-loading-${H}`),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),H==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),O(W,!0))}else O(W,!1);else if(!A&&i&&H!=="none"){m.style.display="";let fe=(V=u.loadingAnimationDuration)!=null?V:2e3;if(m.setAttribute("data-preserve-animation","true"),H==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`);else{m.classList.add(`persona-tool-loading-${H}`),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),H==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let Ce=m.textContent||g;m.textContent="",I(m,Ce,0)}n.status==="complete"&&(m.style.display="none")}else A||(n.status==="complete"?m.style.display="none":m.style.display="");let D=null;if(o){D=h("div","persona-flex persona-items-center");let Ce=be(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?D.appendChild(Ce):D.textContent=a?"Hide":"Show";let Ve=h("div","persona-flex persona-items-center persona-ml-auto");Ve.append(D),l.append(p,Ve)}else l.append(p);let R=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let fe=(ve=(le=t==null?void 0:t.reasoning)==null?void 0:le.renderCollapsedPreview)==null?void 0:ve.call(le,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});iy(R,fe)||(R.textContent=d),R.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,R),r;let _=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=a?"":"none";let z=n.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),D){D.innerHTML="";let Ce=be(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?D.appendChild(Ce):D.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(l,R,_),r};var Zo=new Set,cy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),dy=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
25
|
+
`);let s=qo(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
+
`):""},py=(e,t)=>{var p,m,g,u,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=dy(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?Rp(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},l=a;return s==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Si(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Si(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},yu=(e,t,n)=>{var p;let r=Zo.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"currentColor",g=be(r?"chevron-up":"chevron-down",16,m,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Vi=(e,t)=>{var z,oe,Re,Ue,Fe,ge,ye,Le,Be;let n=e.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!n)return s;let o=(Re=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?Re:{},a=o.expandable!==!1,i=a&&Zo.has(e.id),{summary:d,previewText:l,isActive:p}=py(e,t),m=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((Ue=n.startedAt)!=null?Ue:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",v),ee.textContent=Ls(n),ee},C=(ge=r.renderCollapsedSummary)==null?void 0:ge.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Fe=o.collapsedMode)!=null?Fe:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Ls(n),createElapsedElement:x});typeof C=="string"&&C.trim()?(u.textContent=C,g.appendChild(u)):C instanceof HTMLElement?g.appendChild(C):(u.textContent=d,g.appendChild(u));let T=(ye=o.loadingAnimation)!=null?ye:"none",H=r.activeTextTemplate,k=r.completeTextTemplate,P=p?H:k,W=C instanceof HTMLElement,A=(ee,Pe,V)=>{let le=V;for(let ve of Pe){let fe=h("span","persona-tool-char");fe.style.setProperty("--char-index",String(le)),fe.textContent=ve===" "?"\xA0":ve,ee.appendChild(fe),le++}return le},I=(ee,Pe)=>{var fe;u.textContent="";let V=((fe=n.name)==null?void 0:fe.trim())||"tool",le=ka(ee,V),ve=0;for(let Ce of le){let Ve=Ce.styles.length>0?(()=>{let X=h("span",Ce.styles.map(te=>`persona-tool-text-${te}`).join(" "));return u.appendChild(X),X})():u;if(Ce.isDuration&&p)Ve.appendChild(x());else{let X=Ce.isDuration?Ls(n):Ce.text;Pe?ve=A(Ve,X,ve):Ve.appendChild(document.createTextNode(X))}}};if(!W)if(p&&T!=="none"){let ee=(Le=r.loadingAnimationDuration)!=null?Le:2e3;if(u.setAttribute("data-preserve-animation","true"),T==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),P&&I(P,!1);else if(u.classList.add(`persona-tool-loading-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),P)I(P,!0);else{let Pe=u.textContent||d;u.textContent="",A(u,Pe,0)}}else P&&I(P,!1);let O=null;if(a){O=h("div","persona-flex persona-items-center");let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Pe=be(i?"chevron-up":"chevron-down",16,ee,2);Pe?O.appendChild(Pe):O.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append(O),m.append(g,V)}else m.append(g);let D=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let ee=(Be=r.renderCollapsedPreview)==null?void 0:Be.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});cy(D,ee)||(D.textContent=l),D.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,D),s;let R=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.style.paddingBottom=r.contentPaddingY),n.name){let ee=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ee.style.color=r.contentTextColor:r.headerTextColor&&(ee.style.color=r.headerTextColor),ee.textContent=n.name,R.appendChild(ee)}if(n.args!==void 0){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Arguments";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=qo(n.args),ee.append(Pe,V),R.appendChild(ee)}if(n.chunks&&n.chunks.length){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Activity";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=n.chunks.join(""),ee.append(Pe,V),R.appendChild(ee)}if(n.status==="complete"&&n.result!==void 0){let ee=h("div","persona-space-y-1"),Pe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Pe.style.color=r.labelTextColor),Pe.textContent="Result";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=qo(n.result),ee.append(Pe,V),R.appendChild(ee)}if(n.status==="complete"&&typeof n.duration=="number"){let ee=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ee.style.color=r.contentTextColor),ee.textContent=`Duration: ${n.duration}ms`,R.appendChild(ee)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Pe=be(i?"chevron-up":"chevron-down",16,ee,2);Pe?O.appendChild(Pe):O.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),s.append(m,D,R),s};import{parse as uy,ARR as my,OBJ as gy,STR as fy}from"partial-json";var xu="ask_user_question",Ki=8,es="data-persona-ask-sheet-for",hy="Other",yy="Other\u2026",vu="Type your own answer here",Cu="Send",by="Next",xy="Back",vy="Submit all",Cy="Skip",wy=3,Ji="data-ask-current-index",Gi="data-ask-question-count",wu="data-ask-answers",Xi="data-ask-grouped",Au="data-ask-layout",Ay=e=>e.layout==="pills"?"pills":"rows",Sy=e=>e.getAttribute(Au)==="pills"?"pills":"rows",bu=!1,Su=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===xu,oi=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},so=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=uy(s,fy|gy|my);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},Gs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Ki&&!bu&&(bu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ki}.`)),t.slice(0,Ki)},Ty=e=>{var t;return(t=Gs(e)[0])!=null?t:null},Ey=(e,t)=>{var n;return(n=Gs(e)[t])!=null?n:null},Tu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Eu=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},My=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Eu(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},ky=e=>{let n=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Ly=(e,t,n,r)=>{var p,m,g;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<wy;u++)o.appendChild(ky(r));return o}if(d.forEach((u,v)=>{o.appendChild(My(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?hy:yy;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),C=document.createElement("input");C.type="text",C.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",C.placeholder=(p=t.freeTextPlaceholder)!=null?p:vu,C.setAttribute("data-ask-free-text-input","true"),C.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),x.appendChild(C),v.appendChild(x);let T=Eu(r,a,d.length);T&&v.appendChild(T),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:u,o.appendChild(v)}}return o},Mu=(e,t)=>{var o,a;let r=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:vu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Cu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Py=e=>{var r;let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:Cu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Iy=(e,t,n)=>{var l,p,m,g;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:xy,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Cy,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:vy:(g=n.nextLabel)!=null?g:by,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Lo=e=>{let t=e.getAttribute(wu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},ku=(e,t)=>{e.setAttribute(wu,JSON.stringify(t))},ar=e=>{var n;let t=Number((n=e.getAttribute(Ji))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Wy=(e,t)=>{e.setAttribute(Ji,String(Math.max(0,Math.floor(t))))},ts=e=>{var n;let t=Number((n=e.getAttribute(Gi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ao=e=>e.getAttribute(Xi)==="true",Ry=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Hy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},si=(e,t)=>{let{payload:n}=so(t),r=Gs(n),s=Lo(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Lu=e=>{let t=Lo(e),n=ar(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Pu=e=>{if(!ao(e))return;let t=Lo(e),n=ar(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Qi=(e,t,n)=>{let r=oi(n),s=Sy(e),{payload:o,complete:a}=so(t),i=ao(e),d=ar(e),l=ts(e),p=i?Ey(o,d):Ty(o),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let H=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=H,v.classList.toggle("persona-ask-question-skeleton",!H&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let H=Ly(p,r,a,s);x.replaceWith(H)}if(s!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(Mu(r,s))}let C=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!C?e.appendChild(Py(r)):(!m||i)&&C&&C.remove(),e.setAttribute("data-multi-select",m?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let H=Iy(d,l,r);T?T.replaceWith(H):e.appendChild(H)}else T&&T.remove();Lu(e),Pu(e)},By=(e,t,n)=>{let r=oi(t),s=Ay(r),o=e.toolCall.id,a=Gs(n),i=Math.max(1,a.length),d=i>1,l=Ry(e,a),p=d?Hy(e,i):0,m=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(es,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(Gi,String(i)),m.setAttribute(Ji,String(p)),m.setAttribute(Xi,d?"true":"false"),m.setAttribute(Au,s),ku(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Tu(m,r);let g=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=h("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),m.appendChild(g);let C=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),m.appendChild(C),s!=="rows"&&m.appendChild(Mu(r,s)),Qi(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Dy=(e,t,n)=>{let{payload:r}=so(t),s=Math.max(1,Gs(r).length);s>ts(e)&&(e.setAttribute(Gi,String(s)),s>1&&!ao(e)&&e.setAttribute(Xi,"true")),Qi(e,t,n)},Ny=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=oi(t);Tu(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=so(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Xs=(e,t,n)=>{if(!n||!oo(e)||oi(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${es}]`).forEach(l=>{l.getAttribute(es)!==s&&l.remove()});let a=n.querySelector(`[${es}="${Su(s)}"]`);if(a){Dy(a,e,t);return}let{payload:i}=so(e),d=By(e,t,i);n.appendChild(d)},Po=(e,t)=>{if(!e)return;let n=t?`[${es}="${Su(t)}"]`:`[${es}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Yi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),io=(e,t)=>{let n=Lo(e),r=ar(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,ku(e,n),Lu(e),Pu(e)},ai=(e,t,n,r)=>{let s=ts(e),o=Math.max(0,Math.min(s-1,r));Wy(e,o),Qi(e,t,n)};var Zi=(e,t)=>{var x,C,T,H,k,P,W,A,I,O,D,R;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=r==null?void 0:r.borderColor)!=null?C:"var(--persona-approval-border, #fef08a)",!n)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(T=r==null?void 0:r.titleColor)!=null?T:"currentColor",p=be(d,20,l,2);p&&i.appendChild(p);let m=h("div","persona-flex-1 persona-min-w-0"),g=h("div","persona-flex persona-items-center persona-gap-2"),u=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",g.appendChild(u),!s){let _=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");_.setAttribute("data-approval-status",n.status),n.status==="approved"?(_.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",_.style.color="var(--persona-palette-colors-success-700, #15803d)",_.textContent="Approved"):n.status==="denied"?(_.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",_.style.color="var(--persona-palette-colors-error-700, #b91c1c)",_.textContent="Denied"):n.status==="timeout"&&(_.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",_.style.color="var(--persona-palette-colors-warning-700, #b45309)",_.textContent="Timeout"),g.appendChild(_)}m.appendChild(g);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=n.description,m.appendChild(v),n.parameters){let _=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(_.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(_.style.color=r.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=qo(n.parameters),m.appendChild(_)}if(s){let _=h("div","persona-flex persona-gap-2 persona-mt-2");_.setAttribute("data-approval-buttons","true");let z=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");z.type="button",z.style.backgroundColor=(k=r==null?void 0:r.approveButtonColor)!=null?k:"var(--persona-approval-approve-bg, #22c55e)",z.style.color=(P=r==null?void 0:r.approveButtonTextColor)!=null?P:"#ffffff",z.setAttribute("data-approval-action","approve");let oe=be("shield-check",14,(W=r==null?void 0:r.approveButtonTextColor)!=null?W:"#ffffff",2);oe&&(oe.style.marginRight="4px",z.appendChild(oe));let Re=document.createTextNode((A=r==null?void 0:r.approveLabel)!=null?A:"Approve");z.appendChild(Re);let Ue=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Ue.type="button",Ue.style.backgroundColor=(I=r==null?void 0:r.denyButtonColor)!=null?I:"transparent",Ue.style.color=(O=r==null?void 0:r.denyButtonTextColor)!=null?O:"var(--persona-feedback-error, #dc2626)",Ue.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ue.setAttribute("data-approval-action","deny");let Fe=be("shield-x",14,(D=r==null?void 0:r.denyButtonTextColor)!=null?D:"var(--persona-feedback-error, #dc2626)",2);Fe&&(Fe.style.marginRight="4px",Ue.appendChild(Fe));let ge=document.createTextNode((R=r==null?void 0:r.denyLabel)!=null?R:"Deny");Ue.appendChild(ge),_.append(z,Ue),m.appendChild(_)}return a.append(i,m),o.appendChild(a),o};var Iu=e=>{let t=[];return{buttons:t,render:(r,s,o,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=s?s.isStreaming():!1,g=u=>{switch(u){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(u=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=u,v.disabled=m,i!=null&&i.fontFamily&&(v.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(u))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var Qs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ys=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Fy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Oy=new Set(["step_start","execution_start"]),$y=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),_y=new Set(["step_complete","agent_turn_complete"]),jy=new Set(["flow_complete","agent_complete"]),Wu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Hu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Io=(e,t)=>{let n=e[t];return Hu(n)?n:void 0};function el(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ii(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Uy(e,t){return typeof t.type=="string"?t.type:e}function qy(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function zy(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Ru(e){var r,s,o,a,i;let t=Io(e,"result"),n=[Io(e,"tokens"),Io(e,"totalTokens"),t?Io(t,"tokens"):void 0,Io(e,"usage"),t?Io(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Gn(d.output))!=null?r:Gn(d.outputTokens))!=null?s:Gn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Gn(e.outputTokens))!=null?o:Gn(e.completionTokens))!=null?i:t?(a=Gn(t.outputTokens))!=null?a:Gn(t.completionTokens):void 0}function Vy(e){var n,r,s,o,a;let t=Io(e,"result");return(a=(s=(r=(n=Gn(e.executionTime))!=null?n:Gn(e.executionTimeMs))!=null?r:Gn(e.execution_time))!=null?s:Gn(e.duration))!=null?a:t?(o=Gn(t.executionTime))!=null?o:Gn(t.executionTimeMs):void 0}function Ky(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(t=Ky){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ii(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!Hu(n)){Wu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Uy(t,n),s=this.now();if(Fy.has(r)){this.startRun(s);return}if(Oy.has(r)){this.run||this.startRun(s);return}if($y.has(r)){if(!zy(r,n))return;let a=qy(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+el(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ii(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(_y.has(r)){if(!this.run)return;let a=this.run,i=Ru(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+el(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:ii(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(jy.has(r)){if(!this.run)return;let a=this.run,i=Ru(n),d=i!=null?i:a.exactOutputTokens+el(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:ii(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Wu.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=Vy(n);return o!=null?o:r-t.startedAt}};function ns(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Jy={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Gy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Xy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Qy=100;function Yy(e,t){let n={...Jy,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Gy}function Zy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function eb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function tb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function nb(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function rb(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function ob(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function sb(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function ab(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function tl(e,t,n,r,s,o,a,i){var g;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");ns(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var z,oe;let u=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=be(d?"chevron-down":"chevron-right","14px","currentColor",2);C&&x.appendChild(C);let T=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),H=(z=r.timestampFormat)!=null?z:"relative";T.textContent=H==="relative"?Zy(e.timestamp,n):eb(e.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let P=Yy(e.type,r.badgeColors),W=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");W.style.backgroundColor=P.bg,W.style.color=P.text,W.style.borderColor=P.text+"50",W.textContent=e.type;let A=(oe=r.descriptionFields)!=null?oe:Xy,I=tb(e.payload,A),O=null;I&&(O=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),O.textContent=I);let D=h("div","persona-flex-1 persona-min-w-0"),R=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),_=be("clipboard","12px","currentColor",1.5);return _&&R.appendChild(_),R.addEventListener("click",async Re=>{Re.stopPropagation(),await nb(rb(e)),R.innerHTML="";let Ue=be("check","12px","currentColor",1.5);Ue&&R.appendChild(Ue),setTimeout(()=>{R.innerHTML="";let Fe=be("clipboard","12px","currentColor",1.5);Fe&&R.appendChild(Fe)},1500)}),v.appendChild(x),v.appendChild(T),k&&v.appendChild(k),v.appendChild(W),O&&v.appendChild(O),v.appendChild(D),v.appendChild(R),u.appendChild(v),d&&u.appendChild(ab(e,a,i)),u}}function Bu(e){var v,x,C,T,H;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(C=i==null?void 0:i.label)!=null?C:"",m=(H=(T=s==null?void 0:s.features)==null?void 0:T.eventStream)!=null?H:{},g=o.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let k=g.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>u().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return u();function u(){let k=m.classNames,P=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ns(P,k==null?void 0:k.panel);let W=[],A="",I="",O=null,D=[],R={},_=0,z=_a(),oe=0,Re=0,Ue=!1,Fe=null,ge=!1,ye=0,Le=new Set,Be=new Map,ee="",Pe="",V=null,le,ve,fe,Ce,Ve,X=null,te=null,se=null;function ue(){let ne=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),me=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");ns(me,k==null?void 0:k.headerBar);let vt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(vt.textContent="Events",le=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),le.textContent="0",a){te=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),te.style.cursor="help";let Bn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Bn.textContent="Throughput",X=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),X.textContent="-- tok/s",se=h("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),se.style.display="none",se.style.pointerEvents="none";let Qn=te,yn=se,Dn=()=>{if(!yn.textContent)return;let xr=Qn.getBoundingClientRect(),Nn=ne.getBoundingClientRect();yn.style.left=`${xr.left-Nn.left}px`,yn.style.top=`${xr.bottom-Nn.top+4}px`,yn.style.display="block"},ut=()=>{yn.style.display="none"};te.addEventListener("mouseenter",Dn),te.addEventListener("mouseleave",ut),te.appendChild(Bn),te.appendChild(X)}let jt=h("div","persona-flex-1");ve=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Zt=h("option","");Zt.value="",Zt.textContent="All events",ve.appendChild(Zt),fe=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),fe.type="button",fe.title="Copy All";let St=be("clipboard-copy","12px","currentColor",1.5);St&&fe.appendChild(St);let Ct=h("span","persona-text-xs");Ct.textContent="Copy All",fe.appendChild(Ct),me.appendChild(vt),me.appendChild(le),te&&me.appendChild(te),me.appendChild(jt),me.appendChild(ve),me.appendChild(fe);let ft=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ns(ft,k==null?void 0:k.searchBar);let yt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");yt&&zt.appendChild(yt),Ce=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ns(Ce,k==null?void 0:k.searchInput),Ce.type="text",Ce.placeholder="Search event payloads...",Ve=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ve.type="button",Ve.style.display="none";let tt=be("x","12px","currentColor",2);return tt&&Ve.appendChild(tt),ft.appendChild(zt),ft.appendChild(Ce),ft.appendChild(Ve),ne.appendChild(me),ne.appendChild(ft),se&&ne.appendChild(se),ne}let ie,re=o.find(ne=>ne.renderEventStreamToolbar);if(re!=null&&re.renderEventStreamToolbar&&s){let ne=re.renderEventStreamToolbar({config:s,defaultRenderer:()=>ue(),eventCount:t.getSize(),filteredCount:0,onFilterChange:me=>{A=me,Hn(),F()},onSearchChange:me=>{I=me,Hn(),F()}});ie=ne!=null?ne:ue()}else ie=ue();let Qe=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Qe.style.display="none";function Ie(){if(!a||!X||!te)return;let ne=a();X.textContent=ob(ne);let me=sb(ne);se&&(se.textContent=me,me||(se.style.display="none")),me?te.setAttribute("aria-label",me):te.removeAttribute("aria-label")}let ce=h("div","persona-flex-1 persona-min-h-0 persona-relative"),J=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let _e=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ns(_e,k==null?void 0:k.scrollIndicator),_e.style.display="none",_e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Et=be(l,"14px","currentColor",2);Et&&_e.appendChild(Et);let de=h("span","");de.textContent=p,_e.appendChild(de);let ae=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",ce.appendChild(J),ce.appendChild(ae),ce.appendChild(_e),P.setAttribute("tabindex","0"),P.appendChild(ie),P.appendChild(Qe),P.appendChild(ce);function Mn(){let ne=t.getAll(),me={};for(let Ct of ne)me[Ct.type]=(me[Ct.type]||0)+1;let vt=Object.keys(me).sort(),jt=vt.length!==D.length||!vt.every((Ct,ft)=>Ct===D[ft]),Zt=!jt&&vt.some(Ct=>me[Ct]!==R[Ct]),hn=ne.length!==Object.values(R).reduce((Ct,ft)=>Ct+ft,0);if(!jt&&!Zt&&!hn||(D=vt,R=me,!ve))return;let St=ve.value;if(ve.options[0].textContent="All events",jt){for(;ve.options.length>1;)ve.remove(1);for(let Ct of vt){let ft=h("option","");ft.value=Ct,ft.textContent=`${Ct} (${me[Ct]||0})`,ve.appendChild(ft)}St&&vt.includes(St)?ve.value=St:St&&(ve.value="",A="")}else for(let Ct=1;Ct<ve.options.length;Ct++){let ft=ve.options[Ct];ft.textContent=`${ft.value} (${me[ft.value]||0})`}}function Ot(){let ne=t.getAll();if(A&&(ne=ne.filter(me=>me.type===A)),I){let me=I.toLowerCase();ne=ne.filter(vt=>vt.type.toLowerCase().includes(me)||vt.payload.toLowerCase().includes(me))}return ne}function ln(){return A!==""||I!==""}function Hn(){_=0,oe=0,z.resume(),_e.style.display="none"}function Xn(ne){Le.has(ne)?Le.delete(ne):Le.add(ne),V=ne;let me=J.scrollTop,vt=z.isFollowing();ge=!0,z.pause(),F(),J.scrollTop=me,vt&&z.resume(),ge=!1}function qe(){return Fs(J,50)}function F(){Re=Date.now(),Ue=!1,Ie(),Mn();let ne=t.getEvictedCount();ne>0?(Qe.textContent=`${ne.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",W=Ot();let me=W.length,vt=t.getSize()>0;le&&(le.textContent=String(t.getSize())),me===0&&vt&&ln()?(ae.textContent=I?`No events matching '${I}'`:"No events matching filter",ae.style.display="",J.style.display="none"):(ae.style.display="none",J.style.display=""),fe&&(fe.title=ln()?`Copy Filtered (${me})`:"Copy All"),d&&!z.isFollowing()&&me>_&&(oe+=me-_,de.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",_e.style.display=""),_=me;let jt=t.getAll(),Zt=jt.length>0?jt[0].timestamp:0,hn=new Set(W.map(ft=>ft.id));for(let ft of Le)hn.has(ft)||Le.delete(ft);let St=A!==ee||I!==Pe,Ct=Be.size===0&&W.length>0;if(St||Ct||W.length===0){J.innerHTML="",Be.clear();let ft=document.createDocumentFragment();for(let yt=0;yt<W.length;yt++){let zt=tl(W[yt],yt,Zt,m,Le,Xn,o,s);Be.set(W[yt].id,zt),ft.appendChild(zt)}J.appendChild(ft),ee=A,Pe=I,V=null}else{if(V!==null){let yt=Be.get(V);if(yt&&yt.parentNode===J){let zt=W.findIndex(tt=>tt.id===V);if(zt>=0){let tt=tl(W[zt],zt,Zt,m,Le,Xn,o,s);J.insertBefore(tt,yt),yt.remove(),Be.set(V,tt)}}V=null}let ft=new Set(W.map(yt=>yt.id));for(let[yt,zt]of Be)ft.has(yt)||(zt.remove(),Be.delete(yt));for(let yt=0;yt<W.length;yt++){let zt=W[yt];if(!Be.has(zt.id)){let tt=tl(zt,yt,Zt,m,Le,Xn,o,s);Be.set(zt.id,tt),J.appendChild(tt)}}}z.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Ae(){if(Date.now()-Re>=Qy){Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),F();return}Ue||(Ue=!0,Fe=requestAnimationFrame(()=>{Fe=null,F()}))}let De=(ne,me)=>{if(!fe)return;fe.innerHTML="";let vt=be(ne,"12px","currentColor",1.5);vt&&fe.appendChild(vt);let jt=h("span","persona-text-xs");jt.textContent="Copy All",fe.appendChild(jt),setTimeout(()=>{fe.innerHTML="";let Zt=be("clipboard-copy","12px","currentColor",1.5);Zt&&fe.appendChild(Zt);let hn=h("span","persona-text-xs");hn.textContent="Copy All",fe.appendChild(hn),fe.disabled=!1},me)},Ne=async()=>{if(fe){fe.disabled=!0;try{let ne;ln()?ne=W:n?(ne=await n(),ne.length===0&&(ne=t.getAll())):ne=t.getAll();let me=ne.map(vt=>{try{return JSON.parse(vt.payload)}catch{return vt.payload}});await navigator.clipboard.writeText(JSON.stringify(me,null,2)),De("check",1500)}catch{De("x",1500)}}},je=()=>{ve&&(A=ve.value,Hn(),F())},dt=()=>{!Ce||!Ve||(Ve.style.display=Ce.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{I=Ce.value,Hn(),F()},150))},rt=()=>{!Ce||!Ve||(Ce.value="",I="",Ve.style.display="none",O&&clearTimeout(O),Hn(),F())},At=()=>{if(ge)return;let ne=J.scrollTop,{action:me,nextLastScrollTop:vt}=ja({following:z.isFollowing(),currentScrollTop:ne,lastScrollTop:ye,nearBottom:qe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ye=vt,me==="resume"?(z.resume(),oe=0,_e.style.display="none"):me==="pause"&&(z.pause(),d&&(de.textContent=p,_e.style.display=""))},_t=ne=>{let me=Ua({following:z.isFollowing(),deltaY:ne.deltaY,nearBottom:qe(),resumeWhenNearBottom:!0});me==="pause"?(z.pause(),d&&(de.textContent=p,_e.style.display="")):me==="resume"&&(z.resume(),oe=0,_e.style.display="none")},q=()=>{d&&(J.scrollTop=J.scrollHeight,z.resume(),oe=0,_e.style.display="none")},$t=ne=>{let me=ne.target;if(!me||me.closest("button"))return;let vt=me.closest("[data-event-id]");if(!vt)return;let jt=vt.getAttribute("data-event-id");jt&&Xn(jt)},Ye=ne=>{if((ne.metaKey||ne.ctrlKey)&&ne.key==="f"){ne.preventDefault(),Ce==null||Ce.focus(),Ce==null||Ce.select();return}ne.key==="Escape"&&(Ce&&document.activeElement===Ce?(rt(),Ce.blur(),P.focus()):r&&r())};fe&&fe.addEventListener("click",Ne),ve&&ve.addEventListener("change",je),Ce&&Ce.addEventListener("input",dt),Ve&&Ve.addEventListener("click",rt),J.addEventListener("scroll",At),J.addEventListener("wheel",_t,{passive:!0}),J.addEventListener("click",$t),_e.addEventListener("click",q),P.addEventListener("keydown",Ye);function Dt(){O&&clearTimeout(O),Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),Ue=!1,Be.clear(),fe&&fe.removeEventListener("click",Ne),ve&&ve.removeEventListener("change",je),Ce&&Ce.removeEventListener("input",dt),Ve&&Ve.removeEventListener("click",rt),J.removeEventListener("scroll",At),J.removeEventListener("wheel",_t),J.removeEventListener("click",$t),_e.removeEventListener("click",q),P.removeEventListener("keydown",Ye)}return{element:P,update:Ae,destroy:Dt}}}function Du(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Nu=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Du(e,t)});if(p)return p}return Du(e,t)};var nl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},lo=new nl;lo.register("PersonaArtifactCard",Nu);function ib(e){var s;let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Fu(e,t){var ve,fe,Ce,Ve;let n=(fe=(ve=e.features)==null?void 0:ve.artifacts)==null?void 0:fe.layout,s=((Ce=n==null?void 0:n.toolbarPreset)!=null?Ce:"default")==="document",o=(Ve=n==null?void 0:n.panePadding)==null?void 0:Ve.trim(),a=e.markdown?jo(e.markdown):null,i=Es(e.sanitize),d=X=>{let te=a?a(X):Uo(X);return i?i(te):te},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let m=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let g=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let u=h("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let x="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=s?qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):qt({icon:"eye",label:"Rendered view"}),H=s?qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):qt({icon:"code-2",label:"Source"}),k=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),P=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,A=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(W&&A&&A.length>0),O=null,D,R=null,_=null;if(s&&(P||W)&&!I){if(D=P?Xa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let X=be("chevron-down",14,"currentColor",2);X&&D.appendChild(X)}}else s&&I?(O=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=P?Xa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=qt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),O.append(D,R)):s?D=qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=qt({icon:"copy",label:"Copy"});let z=s?qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):qt({icon:"refresh-cw",label:"Refresh"}),oe=s?qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):qt({icon:"x",label:"Close"}),Re=()=>{var ie,re,Qe;let X=(ie=Be.find(Ie=>Ie.id===ee))!=null?ie:Be[Be.length-1],te=(re=X==null?void 0:X.id)!=null?re:null,se=(X==null?void 0:X.artifactType)==="markdown"&&(Qe=X.markdown)!=null?Qe:"",ue=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:se,jsonPayload:ue,id:te}},Ue=async()=>{var ie;let{markdown:X,jsonPayload:te}=Re(),se=(ie=Be.find(re=>re.id===ee))!=null?ie:Be[Be.length-1],ue=(se==null?void 0:se.artifactType)==="markdown"?X:se?te:"";try{await navigator.clipboard.writeText(ue)}catch{}};if(D.addEventListener("click",async()=>{let X=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(X&&I){let{markdown:te,jsonPayload:se,id:ue}=Re();try{await X({actionId:"primary",artifactId:ue,markdown:te,jsonPayload:se})}catch{}return}await Ue()}),R&&(A!=null&&A.length)){let X=()=>{var se;return(se=m.closest("[data-persona-root]"))!=null?se:document.body},te=()=>{_=ko({items:A.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:ue,jsonPayload:ie,id:re}=Re(),Qe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Qe?await Qe({actionId:se,artifactId:re,markdown:ue,jsonPayload:ie}):se==="markdown"||se==="md"?await navigator.clipboard.writeText(ue):se==="json"||se==="source"?await navigator.clipboard.writeText(ie):await navigator.clipboard.writeText(ue||ie)}catch{}},anchor:O!=null?O:R,position:"bottom-right",portal:X()})};m.isConnected?te():requestAnimationFrame(te),R.addEventListener("click",se=>{se.stopPropagation(),_==null||_.toggle()})}z.addEventListener("click",async()=>{var X;try{await((X=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:X.call(n))}catch{}V()}),oe.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let Fe=()=>{s&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),H.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Fe(),V()}),H.addEventListener("click",()=>{x="source",Fe(),V()});let ge=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(g.replaceChildren(),C.append(T,H),O?k.append(O,z,oe):k.append(D,z,oe),g.append(C,ge,k),Fe()):(g.appendChild(u),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let ye=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ye.style.paddingLeft=o,ye.style.paddingRight=o,Le.style.padding=o),m.appendChild(g),m.appendChild(ye),m.appendChild(Le);let Be=[],ee=null,Pe=!1,V=()=>{var ue,ie,re,Qe;let X=s&&Be.length<=1;ye.classList.toggle("persona-hidden",X),ye.replaceChildren();for(let Ie of Be){let ce=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ce.type="button",ce.textContent=Ie.title||Ie.id.slice(0,8),Ie.id===ee&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(Ie.id)),ye.appendChild(ce)}Le.replaceChildren();let te=ee&&Be.find(Ie=>Ie.id===ee)||Be[Be.length-1];if(!te)return;if(s){let Ie=te.artifactType==="markdown"?"MD":(ue=te.component)!=null?ue:"Component",J=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${J} \xB7 ${Ie}`}else u.textContent="Artifacts";if(te.artifactType==="markdown"){if(s&&x==="source"){let ce=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ce.textContent=(ie=te.markdown)!=null?ie:"",Le.appendChild(ce);return}let Ie=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ie.innerHTML=d((re=te.markdown)!=null?re:""),Le.appendChild(Ie);return}let se=te.component?lo.get(te.component):void 0;if(se){let ce={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=se((Qe=te.props)!=null?Qe:{},ce);if(J){Le.appendChild(J);return}}catch{}}Le.appendChild(ib(te))},le=()=>{var te;let X=Be.length>0;if(m.classList.toggle("persona-hidden",!X),l){let se=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,ie=((te=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;X&&ie&&Pe?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(X){var te,se,ue;Be=X.artifacts,ee=(ue=(se=X.selectedId)!=null?se:(te=X.artifacts[X.artifacts.length-1])==null?void 0:te.id)!=null?ue:null,Be.length>0&&(Pe=!0),V(),le()},setMobileOpen(X){Pe=X,!X&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):le()}}}function ir(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Ou(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ir(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function lb(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function li(e,t){var d,l,p,m,g,u,v,x,C,T;if(!ir(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),lb(e),Ou(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=n==null?void 0:n.paneBackground)==null?void 0:u.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(C=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ou(e,t)}var $u=["panel","seamless"];function ci(e,t){var i,d,l,p,m,g;for(let u of $u)e.classList.remove(`persona-artifact-appearance-${u}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!ir(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",s=$u.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function _u(e,t){var n,r,s;return!t||!ir(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function cb(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function db(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function pb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ub(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function ju(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Uu(e,t,n,r,s,o){let a=cb(s,200),i=ub(t,n,r,200);i=Math.max(a,i);let d=db(o);return d!==null&&(i=Math.min(i,d)),pb(e,a,i)}var qu={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},rl=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,C;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=qu[a])!=null?x:qu.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=h("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var A,I;let H=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");H.htmlFor=`${t.id}-${a}-${T.name}`;let k=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,H.appendChild(k);let P=(A=T.type)!=null?A:"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${T.name}`,W.name=T.name,W.placeholder=(I=T.placeholder)!=null?I:"",T.required&&(W.required=!0),H.appendChild(W),p.appendChild(H)});let m=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");u.type="submit",u.textContent=(C=i.submitLabel)!=null?C:"Submit",m.appendChild(g),m.appendChild(u),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async T=>{var W,A;T.preventDefault();let H=(W=n.formEndpoint)!=null?W:"/form",k=new FormData(p),P={};k.forEach((I,O)=>{P[O]=I}),P.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let I=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let O=await I.json();g.textContent=(A=O.message)!=null?A:"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await r.sendMessage(String(O.nextPrompt))}catch(I){g.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var ol=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},di=new ol;var zu=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var mb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},gb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},pi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=mb(e),n=gb(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},sl=e=>typeof e=="string"?e:e==null?"":String(e),rs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:sl(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=sl(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:sl(n.text)}}},Vu=e=>Array.isArray(e)?e.map(t=>String(t)):[],ui=e=>{let t=new Set(Vu(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Vu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var fb=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},hb=e=>e.map(t=>({...t,streaming:!1})),yb=e=>e.map(t=>({...t,status:"complete"})),al=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?fb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?hb(n.messages):void 0,artifacts:n.artifacts?yb(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as bb,STR as xb,OBJ as vb}from"partial-json";function Cb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function wb(e,t){if(!Cb(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function il(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=bb(n,xb|vb),o=wb(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ab(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ll(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=lo.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Sb(){let e=il();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ku(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function cl(e){let t=Ku(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function dl(e){let t=Ku(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Tb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function pl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Tb}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,u.appendChild(x),g.appendChild(u);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let A=1;A<=5;A++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${l[A-1]}`),I.title=l[A-1],I.dataset.rating=String(A),I.innerHTML=`
|
|
27
27
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
28
28
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
29
29
|
</svg>
|
|
30
|
-
`,I.addEventListener("click",()=>{m=w,T.forEach((O,$)=>{let B=$<w;O.classList.toggle("selected",B),O.setAttribute("aria-checked",$===w-1?"true":"false")})}),T.push(I),C.appendChild(I)}g.appendChild(C);let H=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=o,H.rows=3,H.setAttribute("aria-label","Additional comments"),w.appendChild(H),g.appendChild(w)}let L=document.createElement("div");L.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.addEventListener("click",()=>{n==null||n(),p.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(m===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let w=(H==null?void 0:H.value.trim())||void 0;await t(m,w),p.remove()}catch(w){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),L.appendChild(P),L.appendChild(W),g.appendChild(L),p.appendChild(g),p}function pl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,v.appendChild(C),u.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="persona-feedback-labels";let L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=l;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=p,H.appendChild(L),H.appendChild(P);let W=document.createElement("div");W.className="persona-feedback-numbers";let w=[];for(let j=0;j<=10;j++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${j} out of 10`),z.textContent=String(j),z.dataset.rating=String(j),j<=6?z.classList.add("persona-feedback-detractor"):j<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{g=j,w.forEach((oe,We)=>{oe.classList.toggle("selected",We===j),oe.setAttribute("aria-checked",We===j?"true":"false")})}),w.push(z),W.appendChild(z)}T.appendChild(H),T.appendChild(W),u.appendChild(T);let I=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),j.appendChild(I),u.appendChild(j)}let O=document.createElement("div");O.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{n==null||n(),m.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(g===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let j=(I==null?void 0:I.value.trim())||void 0;await t(g,j),m.remove()}catch(j){B.disabled=!1,B.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),O.appendChild($),O.appendChild(B),u.appendChild(O),m.appendChild(u),m}var rs="persona-chat-history",Sb=30*1e3,Tb={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Eb(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Tb[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function ui(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Mb(e){var t,n,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function kb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var ul=e=>!e||typeof e!="object"?{}:{...e},Vu=e=>e.map(t=>({...t,streaming:!1})),Ku=(e,t,n)=>{let r=e!=null&&e.markdown?_o(e.markdown):null,s=Ts(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,p,m;let a=(l=o.text)!=null?l:"",i=(p=o.message.rawContent)!=null?p:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(m=i!=null?i:o.text)!=null?m:""}):r?d=r(a):d=jo(a),s?s(d):d}};function Ju(e){var i,d,l,p;let t=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=be(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=h("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var ml=(e,t,n)=>{var Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,Ul,ql,zl,Vl,Kl,Jl,Gl,Xl,Ql,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc,Ac;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Ii(t),s=ci.getForInstance(r.plugins);r.components&&lo.registerAll(r.components);let o=Uu(),i=r.persistState===!1?null:(Pl=r.storageAdapter)!=null?Pl:sl(),d={},l=null,p=!1,m=c=>{if(r.onStateLoaded)try{let f=r.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:y,open:b}=f;return b&&(p=!0),y}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let y=f!=null?f:{messages:[],metadata:{}};return m(y)});else{let f=c!=null?c:{messages:[],metadata:{}},y=m(f);y.metadata&&(d=ul(y.metadata)),(Il=y.messages)!=null&&Il.length&&(r={...r,initialMessages:y.messages}),(Wl=y.artifacts)!=null&&Wl.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Rl=y.selectedArtifactId)!=null?Rl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=m({messages:[],metadata:{}});(Hl=c.messages)!=null&&Hl.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,u=c=>{var y;d=(y=c({...d}))!=null?y:{},Ro()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[di],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick],C=pi({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let T=(Dl=(Bl=r.launcher)==null?void 0:Bl.enabled)!=null?Dl:!0,H=(Fl=(Nl=r.launcher)==null?void 0:Nl.autoExpand)!=null?Fl:!1,L=(Ol=r.autoFocusInput)!=null?Ol:!1,P=H,W=T,w=(_l=($l=r.layout)==null?void 0:$l.header)==null?void 0:_l.layout,I=!1,O=()=>no(r),$=()=>T||O(),B=O()?!1:T?H:!0,j=!1,z=null,oe=()=>{j=!0,z&&clearTimeout(z),z=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},We=Ku(r,C,oe),je=(Ul=(jl=r.features)==null?void 0:jl.showReasoning)!=null?Ul:!0,Ne=(zl=(ql=r.features)==null?void 0:ql.showToolCalls)!=null?zl:!0,ge=(Kl=(Vl=r.features)==null?void 0:Vl.showEventStreamToggle)!=null?Kl:!1,ye=(Gl=(Jl=r.features)==null?void 0:Jl.scrollToBottom)!=null?Gl:{},He=`${(Ql=typeof r.persistState=="object"?(Xl=r.persistState)==null?void 0:Xl.keyPrefix:void 0)!=null?Ql:"persona-"}event-stream`,ee=ge?new Xs(He):null,Pe=(ec=(Zl=(Yl=r.features)==null?void 0:Yl.eventStream)==null?void 0:Zl.maxEvents)!=null?ec:2e3,V=ge?new Gs(Pe,ee):null,le=ge?new Qs:null,ve=null,fe=!1,we=null,ze=0;ee==null||ee.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Q={onCopy:c=>{var f,y;o.emit("message:copy",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onCopy)==null||y.call(f,c)},onFeedback:c=>{var f,y;o.emit("message:feedback",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(f=r.messageActions)==null?void 0:f.onFeedback)==null||y.call(f,c)}},te=(tc=r.statusIndicator)!=null?tc:{},se=c=>{var f,y,b,M;return c==="idle"?(f=te.idleText)!=null?f:gn.idle:c==="connecting"?(y=te.connectingText)!=null?y:gn.connecting:c==="connected"?(b=te.connectedText)!=null?b:gn.connected:c==="error"?(M=te.errorText)!=null?M:gn.error:gn[c]};function ue(c,f,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let M=document.createElement("a");M.href=y.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=f,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=f}let{wrapper:ie,panel:re,pillRoot:Qe}=lu(r),Ie=cu(r,$()),{container:ce,body:G,messagesWrapper:$e,suggestions:Et,textarea:de,sendButton:ae,sendButtonWrapper:Mn,composerForm:Ot,statusText:ln,introTitle:Hn,introSubtitle:Xn,closeButton:Ue,iconHolder:N,headerTitle:Ae,headerSubtitle:Be,header:De,footer:_e,actionsRow:dt,leftActions:rt,rightActions:At}=Ie,_t=Ie.setSendButtonMode,q=Ie.micButton,$t=Ie.micButtonWrapper,Ye=Ie.attachmentButton,Dt=Ie.attachmentButtonWrapper,ne=Ie.attachmentInput,me=Ie.attachmentPreviewsContainer;ce.classList.add("persona-relative"),G.classList.add("persona-relative");let vt=12,jt=()=>{var c;return(c=ye.label)!=null?c:""},Zt=()=>{var c;return(c=ye.iconName)!=null?c:"arrow-down"},hn=()=>ye.enabled!==!1,St=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");St.type="button",St.style.display="none",St.setAttribute("data-persona-scroll-to-bottom","true");let wt=h("span","persona-flex persona-items-center"),ft=h("span","");St.append(wt,ft),ce.appendChild(St);let yt=()=>{let f=_e.style.display==="none"?0:_e.offsetHeight;St.style.bottom=`${f+vt}px`};yt();let zt=()=>{let c=!!jt();St.setAttribute("aria-label",jt()||"Jump to latest"),St.title=jt(),St.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),wt.innerHTML="";let f=be(Zt(),"14px","currentColor",2);f?(wt.appendChild(f),wt.style.display=""):wt.style.display="none",ft.textContent=jt(),ft.style.display=c?"":"none"};zt();let tt=null,Bn=null,Qn=s.find(c=>c.renderHeader);if(Qn!=null&&Qn.renderHeader){let c=Qn.renderHeader({config:r,defaultRenderer:()=>{let f=ro({config:r,showClose:$()});return Go(ce,f,r),f.header},onClose:()=>Rt(!1,"user")});if(c){let f=ce.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),De=c)}}let yn=()=>{var f,y,b,M;if(!V)return;if(fe=!0,!ve&&V&&(ve=Ru({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>Dn(),config:r,plugins:s,getThroughput:()=>{var D;return(D=le==null?void 0:le.getMetric())!=null?D:{status:"idle"}}})),ve&&(G.style.display="none",(f=_e.parentNode)==null||f.insertBefore(ve.element,_e),ve.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${En.actionIconColor}`;let D=(M=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:M.toggleButtonActive;D&&D.split(/\s+/).forEach(F=>F&&ut.classList.add(F))}let c=()=>{if(!fe)return;let D=Date.now();D-ze>=200&&(ve==null||ve.update(),ze=D),we=requestAnimationFrame(c)};ze=0,we=requestAnimationFrame(c),Wr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Dn=()=>{var c,f,y;if(fe){if(fe=!1,ve&&ve.element.remove(),G.style.display="",ut){ut.style.boxShadow="";let b=(y=(f=(c=r.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(M=>M&&ut.classList.remove(M))}we!==null&&(cancelAnimationFrame(we),we=null),Wr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ge){let c=(rc=(nc=r.features)==null?void 0:nc.eventStream)==null?void 0:rc.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=h("button",f),ut.style.width="28px",ut.style.height="28px",ut.style.color=En.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let y=be("activity","18px","currentColor",1.5);y&&ut.appendChild(y);let b=Ie.clearChatButtonWrapper,M=Ie.closeButtonWrapper,D=b||M;D&&D.parentNode===De?De.insertBefore(ut,D):De.appendChild(ut),ut.addEventListener("click",()=>{fe?Dn():yn()})}let xr=c=>{var b,M,D;let f=r.attachments;if(!(f!=null&&f.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let F=c.querySelector("[data-persona-composer-form]");F!=null&&F.parentNode?F.parentNode.insertBefore(y,F):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let F=h("input");F.type="file",F.accept=((b=f.allowedTypes)!=null?b:Nr).join(","),F.multiple=((M=f.maxFiles)!=null?M:4)>1,F.style.display="none",F.setAttribute("aria-label",(D=f.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(F)}},Nn=s.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=r.composer,f=Nn.renderComposer({config:r,defaultRenderer:()=>zs({config:r}).footer,onSubmit:y=>{var F;if(!S||S.isStreaming())return;let b=y.trim(),M=(F=tt==null?void 0:tt.hasAttachments())!=null?F:!1;if(!b&&!M)return;gs();let D;M&&(D=[],D.push(...tt.getContentParts()),b&&D.push(Ia(b))),S.sendMessage(b,{contentParts:D}),M&&tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ne==null||ne.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((oc=r.voiceRecognition)==null?void 0:oc.enabled)===!0?()=>{Bn==null||Bn()}:void 0});f&&(_e.replaceWith(f),_e=f)}let po=c=>{let f=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");f&&(Ot=f),y&&(de=y),b&&(ae=b),M&&(q=M,$t=M.parentElement),D&&(ln=D);let F=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Et=F);let U=c.querySelector(".persona-attachment-button");U&&(Ye=U,Dt=U.parentElement),ne=c.querySelector('input[type="file"]'),me=c.querySelector(".persona-attachment-previews");let R=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");R&&(dt=R)};xr(_e),po(_e);let kn=(cc=(sc=r.layout)==null?void 0:sc.contentMaxWidth)!=null?cc:O()?(lc=(ic=(ac=r.launcher)==null?void 0:ac.composerBar)==null?void 0:ic.contentMaxWidth)!=null?lc:"720px":void 0;if(kn&&($e.style.maxWidth=kn,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),kn&&Ot&&!O()&&(Ot.style.maxWidth=kn,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),kn&&Et&&!O()&&(Et.style.maxWidth=kn,Et.style.marginLeft="auto",Et.style.marginRight="auto"),kn&&me&&!O()&&(me.style.maxWidth=kn,me.style.marginLeft="auto",me.style.marginRight="auto"),(dc=r.attachments)!=null&&dc.enabled&&ne&&me){tt=Ko.fromConfig(r.attachments),tt.setPreviewsContainer(me),ne.addEventListener("change",y=>{let b=y.target;tt==null||tt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,f=Ju(c);ce.appendChild(f)}(()=>{var b,M;let c=(M=(b=r.layout)==null?void 0:b.slots)!=null?M:{},f=D=>{switch(D){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return Et;case"composer":return Ot;case"footer-bottom":return ln;default:return null}},y=(D,F)=>{var U;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")De.insertBefore(F,De.firstChild);else if(D==="header-right")De.appendChild(F);else{let R=De.querySelector(".persona-flex-col");R?(U=R.parentNode)==null||U.insertBefore(F,R.nextSibling):De.appendChild(F)}break;case"body-top":{let R=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(F):G.insertBefore(F,G.firstChild);break}case"body-bottom":G.appendChild(F);break;case"footer-top":Et.replaceWith(F);break;case"footer-bottom":ln.replaceWith(F);break;default:break}};for(let[D,F]of Object.entries(c))if(F)try{let U=F({config:r,defaultContent:()=>f(D)});U&&y(D,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,U)}})();let Or=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let M=b.getAttribute("data-message-id");if(!M)return;let D=y.getAttribute("data-bubble-type");D==="reasoning"?(Qo.has(M)?Qo.delete(M):Qo.add(M),gu(M,b)):D==="tool"&&(Yo.has(M)?Yo.delete(M):Yo.add(M),fu(M,b,r)),dr.delete(M)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Or(c))}),$e.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Or(c))});let Er=new Map;$e.addEventListener("click",c=>{var F;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let M=b.getAttribute("data-actions-for");if(!M)return;let D=y.getAttribute("data-action");if(D==="copy"){let R=S.getMessages().find(Ce=>Ce.id===M);if(R&&Q.onCopy){let Ce=R.content||"";navigator.clipboard.writeText(Ce).then(()=>{y.classList.add("persona-message-action-success");let pe=be("check",14,"currentColor",2);pe&&(y.innerHTML="",y.appendChild(pe)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Z=be("copy",14,"currentColor",2);Z&&(y.innerHTML="",y.appendChild(Z))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),Q.onCopy(R)}}else if(D==="upvote"||D==="downvote"){let R=((F=Er.get(M))!=null?F:null)===D,Ce=D==="upvote"?"thumbs-up":"thumbs-down";if(R){Er.delete(M),y.classList.remove("persona-message-action-active");let pe=be(Ce,14,"currentColor",2);pe&&(y.innerHTML="",y.appendChild(pe))}else{let pe=D==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${pe}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Ge=be(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(Z.innerHTML="",Z.appendChild(Ge))}Er.set(M,D),y.classList.add("persona-message-action-active");let he=be(Ce,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(he)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Fe=S.getMessages().find(nt=>nt.id===M);Fe&&Q.onFeedback&&Q.onFeedback({type:D,messageId:Fe.id,message:Fe})}}}),$e.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let M=b.getAttribute("data-message-id");if(!M)return;let D=y.getAttribute("data-approval-action");if(!D)return;let F=D==="approve"?"approved":"denied",R=S.getMessages().find(pe=>pe.id===M);if(!(R!=null&&R.approval))return;let Ce=b.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),R.approval.toolType==="webmcp"?S.resolveWebMcpApproval(M,F):S.resolveApproval(R.approval,F)});let bt=null,Fn=null,On={artifacts:[],selectedId:null},bn=!1,Lt={current:null};$e.addEventListener("click",c=>{var Z,he,Se,Fe,nt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Se=(he=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Se.call(he,{type:"download",artifactId:b}))===!0)return;let D=S.getArtifactById(b),F=D==null?void 0:D.markdown,U=(D==null?void 0:D.title)||"artifact";if(!F){let Ge=y.closest("[data-open-artifact]"),at=Ge==null?void 0:Ge.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Me=S.getMessages().find(qe=>qe.id===it);if(Me!=null&&Me.rawContent)try{let qe=JSON.parse(Me.rawContent);F=(Fe=qe==null?void 0:qe.props)==null?void 0:Fe.markdown,U=((nt=qe==null?void 0:qe.props)==null?void 0:nt.title)||U}catch{}}}if(!F)return;let R=new Blob([F],{type:"text/markdown"}),Ce=URL.createObjectURL(R),pe=document.createElement("a");pe.href=Ce,pe.download=`${U}.md`,pe.click(),URL.revokeObjectURL(Ce)}),$e.addEventListener("click",c=>{var D,F,U;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((U=(F=(D=r.features)==null?void 0:D.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:U.call(F,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),bn=!1,S.selectArtifact(b),jn())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let Yn=Ie.composerOverlay,Zn=(c,f,y)=>{var U,R,Ce,pe;let b=f.trim();if(!b||!Lt.current)return;let M=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",D=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:b,answers:y.structured,values:(R=y.values)!=null?R:y.source==="multi"?b.split(", "):[b],isFreeText:D,source:y.source},bubbles:!0,composed:!0})),Lo(Yn,M);let F=Lt.current.getMessages().find(Z=>{var he;return((he=Z.toolCall)==null?void 0:he.id)===M});(Ce=F==null?void 0:F.agentMetadata)!=null&&Ce.awaitingLocalTool?Lt.current.resolveAskUserQuestion(F,(pe=y.structured)!=null?pe:b):Lt.current.sendMessage(b)},$n=c=>{var M;let f=Lt.current;if(!f)return;let y=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",b=f.getMessages().find(D=>{var F;return((F=D.toolCall)==null?void 0:F.id)===y});b&&f.persistAskUserQuestionProgress(b,{answers:oi(c,b),currentIndex:ar(c)})},$r=c=>Object.entries(c).map(([f,y])=>`${f}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Mr=c=>{var M,D,F;if(((D=(M=r.features)==null?void 0:M.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let f=ar(c),y=es(c);if(f>=y-1)return;let b=(F=Lt.current)==null?void 0:F.getMessages().find(U=>{var R;return((R=U.toolCall)==null?void 0:R.id)===c.getAttribute("data-tool-call-id")});b&&(si(c,b,r,f+1),$n(c))};Yn.addEventListener("click",c=>{var D,F,U,R,Ce,pe,Z,he,Se,Fe,nt,Ge,at,it;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let M=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let ke=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ke},bubbles:!0,composed:!0})),Lo(Yn,ke);let Me=(F=Lt.current)==null?void 0:F.getMessages().find(qe=>{var E;return((E=qe.toolCall)==null?void 0:E.id)===ke});(U=Me==null?void 0:Me.agentMetadata)!=null&&U.awaitingLocalTool&&((R=Lt.current)==null||R.markAskUserQuestionResolved(Me),(Ce=Lt.current)==null||Ce.resolveAskUserQuestion(Me,"(dismissed)"));return}if(M==="pick"){let ke=y.getAttribute("data-option-label");if(!ke)return;let Me=b.getAttribute("data-multi-select")==="true",qe=ao(b);if(qe&&Me){let E=ko(b)[ar(b)],Te=new Set(Array.isArray(E)?E:[]);Te.has(ke)?Te.delete(ke):Te.add(ke),io(b,Array.from(Te)),$n(b);return}if(qe){io(b,ke),$n(b),Mr(b);return}if(Me){let E=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",E?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!E);let Te=b.querySelector('[data-ask-user-action="submit-multi"]');Te&&(Te.disabled=Qi(b).length===0);return}Zn(b,ke,{source:"pick",values:[ke]});return}if(M==="submit-multi"){let ke=Qi(b);if(ke.length===0)return;Zn(b,ke.join(", "),{source:"multi",values:ke});return}if(M==="open-free-text"){let ke=b.querySelector('[data-ask-free-text-row="true"]');if(ke){ke.classList.remove("persona-hidden");let Me=ke.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus()}return}if(M==="focus-free-text"){let ke=b.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus();return}if(M==="submit-free-text"){let ke=b.querySelector('[data-ask-free-text-input="true"]'),Me=(pe=ke==null?void 0:ke.value)!=null?pe:"";if(!Me.trim())return;if(ao(b)){io(b,Me.trim()),$n(b),Mr(b);return}Zn(b,Me,{source:"free-text"});return}if(M==="next"||M==="back"){if(!Lt.current)return;let ke=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Me=Lt.current.getMessages().find(Ke=>{var xe;return((xe=Ke.toolCall)==null?void 0:xe.id)===ke});if(!Me)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),E=(Se=(he=qe==null?void 0:qe.value)==null?void 0:he.trim())!=null?Se:"";if(E){let Ke=ko(b)[ar(b)];(typeof Ke!="string"||Ke!==E)&&io(b,E)}let Te=M==="next"?1:-1,Re=ar(b)+Te;si(b,Me,r,Re),$n(b);return}if(M==="submit-all"){if(!Lt.current)return;let ke=(Fe=b.getAttribute("data-tool-call-id"))!=null?Fe:"",Me=Lt.current.getMessages().find(Ke=>{var xe;return((xe=Ke.toolCall)==null?void 0:xe.id)===ke});if(!Me)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),E=(Ge=(nt=qe==null?void 0:qe.value)==null?void 0:nt.trim())!=null?Ge:"";E&&io(b,E);let Te=oi(b,Me);Lt.current.persistAskUserQuestionProgress(Me,{answers:Te,currentIndex:ar(b)});let Re=$r(Te);Zn(b,Re||"(submitted)",{source:"submit-all",structured:Te});return}if(M==="skip"){if(!Lt.current)return;let ke=(at=b.getAttribute("data-tool-call-id"))!=null?at:"",Me=Lt.current.getMessages().find(xe=>{var kt;return((kt=xe.toolCall)==null?void 0:kt.id)===ke});if(!Me)return;let qe=ao(b),E=ar(b),Te=es(b),Re=E>=Te-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ke},bubbles:!0,composed:!0})),Lo(Yn,ke),(it=Me.agentMetadata)!=null&&it.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Me),Lt.current.resolveAskUserQuestion(Me,"(dismissed)"));return}io(b,"");let Ke=b.querySelector('[data-ask-free-text-input="true"]');if(Ke&&(Ke.value=""),Re){let xe=oi(b,Me),kt=$r(xe);Zn(b,kt||"(skipped)",{source:"submit-all",structured:xe});return}si(b,Me,r,E+1),$n(b);return}}),Yn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let y=c.target;if(!((D=y.matches)!=null&&D.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let M=y.value;if(M.trim()){if(ao(b)){io(b,M.trim()),$n(b),Mr(b);return}Zn(b,M,{source:"free-text"})}});let _r=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let y=Yn.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),D=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",_r);let _n=null,Wt=null,xn=null,er=null,jr=()=>{};function kr(){er==null||er(),er=null}let Ur=()=>{var F;if(!_n||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((F=e.ownerDocument.defaultView)!=null?F:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let b=_n.firstElementChild;if(!b||b===Wt)return;let M=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${M}px`,Wt.style.zIndex="5";let D=b.offsetWidth-M/2;Wt.style.left=`${Math.max(0,D)}px`},vr=()=>{},jn=()=>{var y,b,M,D,F;if(!bt||!ir(r))return;ii(e,r),li(e,r),vr();let c=(D=(M=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:M.narrowHostMaxWidth)!=null?D:520,f=re.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),bt.update(On),bn?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(F=bt.backdrop)==null||F.classList.add("persona-hidden")):On.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),jr()};if(ir(r)){re.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ce),bt=Du(r,{onSelect:y=>{var b;return(b=Lt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{bn=!0,jn()}}),bt.element.classList.add("persona-hidden"),_n=f,f.appendChild(c),f.appendChild(bt.element),bt.backdrop&&re.appendChild(bt.backdrop),re.appendChild(f),jr=()=>{var b,M,D,F;if(!_n||!bt)return;if(!(((D=(M=(b=r.features)==null?void 0:b.artifacts)==null?void 0:M.layout)==null?void 0:D.resizable)===!0)){xn==null||xn(),xn=null,kr(),Wt&&(Wt.remove(),Wt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Wt){let U=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let R=e.ownerDocument,Ce=(F=R.defaultView)!=null?F:window,pe=Z=>{var at,it;if(!bt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;Z.preventDefault(),kr();let he=Z.clientX,Se=bt.element.getBoundingClientRect().width,Fe=(it=(at=r.features)==null?void 0:at.artifacts)==null?void 0:it.layout,nt=ke=>{let Me=_n.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),E=qe?0:$u(_n,Ce),Te=qe?0:U.getBoundingClientRect().width||6,Re=Se-(ke.clientX-he),Ke=_u(Re,Me,E,Te,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);bt.element.style.width=`${Ke}px`,bt.element.style.maxWidth="none",Ur()},Ge=()=>{R.removeEventListener("pointermove",nt),R.removeEventListener("pointerup",Ge),R.removeEventListener("pointercancel",Ge),er=null;try{U.releasePointerCapture(Z.pointerId)}catch{}};er=Ge,R.addEventListener("pointermove",nt),R.addEventListener("pointerup",Ge),R.addEventListener("pointercancel",Ge);try{U.setPointerCapture(Z.pointerId)}catch{}};U.addEventListener("pointerdown",pe),Wt=U,_n.insertBefore(U,bt.element),xn=()=>{U.removeEventListener("pointerdown",pe)}}if(Wt){let U=On.artifacts.length>0&&!bn;Wt.classList.toggle("persona-hidden",!U),Ur()}},vr=()=>{var Ce,pe,Z,he,Se,Fe,nt,Ge,at,it,ke,Me,qe,E;if(!T||!bt||((pe=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?pe:!1)||an(r)&&yr(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,M=(Se=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?Se:!0,D=(nt=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?nt:640;if(M&&b.innerWidth<=D||!Ou(r,T))return;let F=(it=(at=(Ge=r.launcher)==null?void 0:Ge.width)!=null?at:r.launcherWidth)!=null?it:sr,U=(E=(qe=(Me=(ke=r.features)==null?void 0:ke.artifacts)==null?void 0:Me.layout)==null?void 0:qe.expandedPanelWidth)!=null?E:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!bn?(re.style.width=U,re.style.maxWidth=U):(re.style.width=F,re.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{jn()}),Fn.observe(re))}else re.appendChild(ce),O()&&Qe&&(Ie.peekBanner&&Qe.appendChild(Ie.peekBanner),Qe.appendChild(_e));e.appendChild(ie),Qe&&e.appendChild(Qe);let lr=()=>{var Ke,xe,kt,st,Qt,cn,It,Cn,dn,Ze,lt,An,un,yo,bo,xo,Oo,$o,Vt,vo,Zr,ht,Pn,Br,Sn,In,Ht,Ut;if(O()){re.style.width="100%",re.style.maxWidth="100%";let Bt=(xe=(Ke=r.launcher)==null?void 0:Ke.composerBar)!=null?xe:{},Kt=ie.dataset.state==="expanded",Wn=(kt=Bt.expandedSize)!=null?kt:"anchored";if(!(Kt&&Wn!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let tn=(Qt=(st=r.theme)==null?void 0:st.components)==null?void 0:Qt.panel,Ar=Hs(r),Dr=(wo,xa)=>{var Cs;return wo==null||wo===""?xa:(Cs=Jo(Ar,wo))!=null?Cs:wo},ha="1px solid var(--persona-border)",ya="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ba="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=Dr(tn==null?void 0:tn.border,ha),ce.style.borderRadius=Dr(tn==null?void 0:tn.borderRadius,ba),ce.style.boxShadow=Dr(tn==null?void 0:tn.shadow,ya),ce.style.overflow="hidden";return}let c=an(r),f=(It=(cn=r.launcher)==null?void 0:cn.sidebarMode)!=null?It:!1,y=c||f||((dn=(Cn=r.launcher)==null?void 0:Cn.fullHeight)!=null?dn:!1),b=((Ze=r.launcher)==null?void 0:Ze.enabled)===!1,M=(An=(lt=r.theme)==null?void 0:lt.components)==null?void 0:An.panel,D=Hs(r),F=(Bt,Kt)=>{var Wn;return Bt==null||Bt===""?Kt:(Wn=Jo(D,Bt))!=null?Wn:Bt},U=(un=e.ownerDocument.defaultView)!=null?un:window,R=(bo=(yo=r.launcher)==null?void 0:yo.mobileFullscreen)!=null?bo:!0,Ce=(Oo=(xo=r.launcher)==null?void 0:xo.mobileBreakpoint)!=null?Oo:640,pe=U.innerWidth<=Ce,Z=R&&pe&&T,he=(Vt=($o=r.launcher)==null?void 0:$o.position)!=null?Vt:"bottom-left",Se=he==="bottom-left"||he==="top-left",Fe=(Zr=(vo=r.launcher)==null?void 0:vo.zIndex)!=null?Zr:fn,nt=f||Z?"none":"1px solid var(--persona-border)",Ge=Z?"none":f?Se?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(Ge="none",nt="none");let at=f||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=F(M==null?void 0:M.border,nt),ke=F(M==null?void 0:M.shadow,Ge),Me=F(M==null?void 0:M.borderRadius,at),qe=G.scrollTop;e.style.cssText="",ie.style.cssText="",re.style.cssText="",ce.style.cssText="",G.style.cssText="",_e.style.cssText="";let E=()=>{var Kt;if(qe<=0)return;((Kt=G.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(G.scrollTop===qe)return;let Wn=G.scrollHeight-G.clientHeight;Wn<=0||(G.scrollTop=Math.min(qe,Wn))})};if(Z){ie.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ie.style.cssText=`
|
|
30
|
+
`,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=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -37,7 +37,7 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
|
|
|
37
37
|
padding: 0 !important;
|
|
38
38
|
display: flex !important;
|
|
39
39
|
flex-direction: column !important;
|
|
40
|
-
z-index: ${
|
|
40
|
+
z-index: ${Oe} !important;
|
|
41
41
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
42
42
|
`,re.style.cssText=`
|
|
43
43
|
position: relative !important;
|
|
@@ -63,7 +63,7 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
|
|
|
63
63
|
overflow: hidden !important;
|
|
64
64
|
border-radius: 0 !important;
|
|
65
65
|
border: none !important;
|
|
66
|
-
`,
|
|
66
|
+
`,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",je.style.flexShrink="0",I=!0,E();return}let Te=(Pn=(ht=r==null?void 0:r.launcher)==null?void 0:ht.width)!=null?Pn:r==null?void 0:r.launcherWidth,He=Te!=null?Te:sr;if(!f&&!c)b&&y?(re.style.width="100%",re.style.maxWidth="100%"):(re.style.width=He,re.style.maxWidth=He);else if(c)if(yr(r).reveal==="emerge"){let Kt=yr(r).width;re.style.width=Kt,re.style.maxWidth=Kt}else re.style.width="100%",re.style.maxWidth="100%";if(vr(),re.style.boxShadow=ke,re.style.borderRadius=Me,ce.style.border=it,ce.style.borderRadius=Me,c&&!Y&&(M==null?void 0:M.border)===void 0&&(ce.style.border="none",yr(r).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.height="100%",b&&(ie.style.overflow="hidden"),re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.height="100%",re.style.overflow="hidden",ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",je.style.flexShrink="0"),ie.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!b&&!c&&((Br=br[he])!=null?Br:br["bottom-right"]).split(" ").forEach(Kt=>ie.classList.add(Kt)),f){let Bt=(In=(Sn=r.launcher)==null?void 0:Sn.sidebarWidth)!=null?In:"420px";ie.style.cssText=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
@@ -74,7 +74,7 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
|
|
|
74
74
|
padding: 0 !important;
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
|
-
z-index: ${
|
|
77
|
+
z-index: ${Oe} !important;
|
|
78
78
|
${Se?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
79
79
|
`,re.style.cssText=`
|
|
80
80
|
position: relative !important;
|
|
@@ -100,27 +100,27 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
|
|
|
100
100
|
overflow: hidden !important;
|
|
101
101
|
border-radius: ${Me} !important;
|
|
102
102
|
border: ${it} !important;
|
|
103
|
-
`,
|
|
103
|
+
`,je.style.cssText=`
|
|
104
104
|
flex-shrink: 0 !important;
|
|
105
105
|
border-top: none !important;
|
|
106
106
|
padding: 8px 16px 12px 16px !important;
|
|
107
|
-
`}if(!b&&!c){let Bt="max-height: -moz-available !important; max-height: stretch !important;",Kt=f?"":"padding-top: 1.25em !important;",Wn=f?"":`z-index: ${(Ut=(Ht=r.launcher)==null?void 0:Ht.zIndex)!=null?Ut:fn} !important;`;ie.style.cssText+=Bt+Kt+Wn}E()};lr(),Eo(e,r),ii(e,r),li(e,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",_r)});let Jt=null,Gt=null;gt.push(()=>{Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null}),Fn&>.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(()=>{we!==null&&(cancelAnimationFrame(we),we=null),ve==null||ve.destroy(),ve=null,V==null||V.destroy(),V=null,ee=null});let Un=null,qr=()=>{Un&&(Un(),Un=null),r.colorScheme==="auto"&&(Un=Hi(()=>{Eo(e,r)}))};qr(),gt.push(()=>{Un&&(Un(),Un=null)});let tr=(pc=r.features)==null?void 0:pc.streamAnimation;if(tr!=null&&tr.type&&tr.type!=="none"){let c=Os(tr.type,tr.plugins);c&&(Ni(c,e),gt.push(()=>nu(e)))}let cr=Lu(Et),qn=null,S,zn=!1,dr=Xp(),Lr=new Map,wr=new Map,ss=0,pr=$a(),ur=0,mr=null,Pr=!1,uo=!1,Zs=4,as=24,ea=80,Wo=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=(mc=(uc=r.voiceRecognition)==null?void 0:uc.autoResume)!=null?mc:!1,nr=c=>{o.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Ln=()=>{u(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},ta=()=>{var b,M;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=ul(d.voiceState),f=!!c.active,y=Number((M=c.timestamp)!=null?M:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-y<Sb&&setTimeout(()=>{var D,F;mt.active||(mt.manuallyDeactivated=!1,((F=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:F.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("restore"),S.isVoiceActive()&&_()}):ho("restore"))},1e3)},na=()=>S?Vu(S.getMessages()).filter(c=>!c.__skipPersist):[];function Ro(c){if(!(i!=null&&i.save))return;let y={messages:c?Vu(c):S?na():[],metadata:d,artifacts:On.artifacts,selectedArtifactId:On.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Ir=null,ra=()=>ie.querySelector("#persona-scroll-container")||G,mo=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),Pr=!1},ls=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),uo=!1,mo()},Wr=()=>{if(!hn()||fe){St.parentNode&&St.remove(),St.style.display="none";return}St.parentNode!==ce&&ce.appendChild(St),yt();let c=Bs(G)>0;St.style.display=pr.isFollowing()||!c?"none":""},cs=()=>{pr.pause()&&(ls(),Wr())},zr=()=>{pr.resume(),Wr()},Vr=(c=!1)=>{pr.isFollowing()&&(!c&&!zn||(mr!==null&&(cancelAnimationFrame(mr),mr=null),uo=!0,mr=requestAnimationFrame(()=>{mr=null,uo=!1,pr.isFollowing()&&oa(ra(),c?220:140)})))},oa=(c,f=500)=>{let y=c.scrollTop,b=Bs(c),M=b-y;if(Math.abs(M)<1){ur=c.scrollTop;return}if(Math.abs(M)>=ea){mo(),Pr=!0,c.scrollTop=b,ur=c.scrollTop,Pr=!1;return}mo();let D=performance.now();Pr=!0;let F=R=>1-Math.pow(1-R,3),U=R=>{if(!pr.isFollowing()){mo();return}let Ce=Bs(c);Ce!==b&&(b=Ce,M=b-y);let pe=R-D,Z=Math.min(pe/f,1),he=F(Z),Se=y+M*he;c.scrollTop=Se,ur=c.scrollTop,Z<1?Ir=requestAnimationFrame(U):(c.scrollTop=b,ur=c.scrollTop,Ir=null,Pr=!1)};Ir=requestAnimationFrame(U)},sa=c=>{let f=new Map;c.forEach(y=>{let b=Wo.get(y.id);f.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Wo.clear(),f.forEach((y,b)=>{Wo.set(b,y)})},go=(c,f,y)=>{var Ge,at,it,ke,Me,qe;let b=document.createElement("div"),D=(()=>{var Te;let E=s.find(Re=>Re.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((Te=r.loadingIndicator)!=null&&Te.render)return r.loadingIndicator.render})(),F=(E,Te)=>Te==null?!1:typeof Te=="string"?(E.textContent=Te,!0):(E.appendChild(Te),!0),U=new Set,R=new Set,Ce=s.some(E=>E.renderAskUserQuestion),pe=[],Z=[],he=r.enableComponentStreaming!==!1;if(f.forEach(E=>{var Cn,dn,Ze,lt,An,un,yo,bo,xo,Oo,$o,Vt,vo,Zr;U.add(E.id);let Te=Ce&&oo(E),Re=!Te&&E.role==="assistant"&&!E.variant&&he&&ll(E);if(!Re&&wr.has(E.id)){let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),wr.delete(E.id)}let Ke=oo(E)?`:${(Cn=E.agentMetadata)!=null&&Cn.askUserQuestionAnswered?"a":"u"}:${(dn=E.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(E.agentMetadata.askUserQuestionAnswers).length:0}`:"",xe=Gp(E,ss)+Ke,kt=Te||Re?null:Qp(dr,E.id,xe);if(kt){b.appendChild(kt.cloneNode(!0)),oo(E)&&((Ze=E.toolCall)!=null&&Ze.id)&&((lt=E.agentMetadata)==null?void 0:lt.awaitingLocalTool)===!0&&!((An=E.agentMetadata)!=null&&An.askUserQuestionAnswered)&&(R.add(E.toolCall.id),Js(E,r,Ie.composerOverlay));return}let st=null,Qt=s.find(ht=>!!(E.variant==="reasoning"&&ht.renderReasoning||E.variant==="tool"&&ht.renderToolCall||E.variant==="approval"&&ht.renderApproval||!E.variant&&ht.renderMessage)),cn=(un=r.layout)==null?void 0:un.messages;if(oo(E)&&((yo=E.agentMetadata)==null?void 0:yo.askUserQuestionAnswered)===!0){Lr.delete(E.id);let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(oo(E)&&((xo=(bo=r.features)==null?void 0:bo.askUserQuestion)==null?void 0:xo.enabled)!==!1){let ht=s.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(ht&&Lt.current){let Pn=Lr.get(E.id),Br=Pn!==xe,Sn=null;if(Br){let{payload:Ut,complete:Bt}=so(E),Kt=E.id,Wn=()=>{var Kn;return(Kn=Lt.current)==null?void 0:Kn.getMessages().find(tn=>tn.id===Kt)};Sn=ht.renderAskUserQuestion({message:E,payload:Ut,complete:Bt,resolve:Kn=>{var Ar;let tn=Wn();tn&&((Ar=Lt.current)==null||Ar.resolveAskUserQuestion(tn,Kn))},dismiss:()=>{var tn,Ar,Dr;let Kn=Wn();(tn=Kn==null?void 0:Kn.agentMetadata)!=null&&tn.awaitingLocalTool&&((Ar=Lt.current)==null||Ar.markAskUserQuestionResolved(Kn),(Dr=Lt.current)==null||Dr.resolveAskUserQuestion(Kn,"(dismissed)"))},config:r})}let In=Pn!=null;if(Br&&Sn===null&&!In){((Oo=E.agentMetadata)==null?void 0:Oo.awaitingLocalTool)===!0&&!(($o=E.agentMetadata)!=null&&$o.askUserQuestionAnswered)&&(R.add(E.toolCall.id),Js(E,r,Ie.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${E.id}`,Ht.setAttribute("data-wrapper-id",E.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),b.appendChild(Ht),pe.push({messageId:E.id,fingerprint:xe,bubble:Sn});return}else{((Vt=E.agentMetadata)==null?void 0:Vt.awaitingLocalTool)===!0&&!((vo=E.agentMetadata)!=null&&vo.askUserQuestionAnswered)&&(R.add(E.toolCall.id),Js(E,r,Ie.composerOverlay));return}}else if(Qt)if(E.variant==="reasoning"&&E.reasoning&&Qt.renderReasoning){if(!je)return;st=Qt.renderReasoning({message:E,defaultRenderer:()=>qi(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Qt.renderToolCall){if(!Ne)return;st=Qt.renderToolCall({message:E,defaultRenderer:()=>zi(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Qt.renderApproval){if(r.approval===!1)return;st=Qt.renderApproval({message:E,defaultRenderer:()=>Yi(E,r),config:r})}else Qt.renderMessage&&(st=Qt.renderMessage({message:E,defaultRenderer:()=>{let ht=Vs(E,y,cn,r.messageActions,Q,{loadingIndicatorRenderer:D,widgetConfig:r});return E.role!=="user"&&nl(ht,E,r,S),ht},config:r}));if(!st&&Re){let ht=cl(E);if(ht){let Pn=wr.get(E.id),Br=Pn!==xe,Sn=r.wrapComponentDirectiveInBubble!==!1,In=null;if(Br){let Ht=il(ht,{config:r,message:E,transform:y});if(Ht)if(Sn){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${E.id}`,Ut.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let Bt=document.createElement("div");Bt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Bt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),Ut.appendChild(Bt)}Ut.appendChild(Ht),In=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${E.id}`,Ut.setAttribute("data-message-id",E.id),Ut.setAttribute("data-persona-component-directive","true"),E.content&&E.content.trim()){let Bt=document.createElement("div");Bt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Bt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),Ut.appendChild(Bt)}Ut.appendChild(Ht),In=Ut}}if(In||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${E.id}`,Ht.setAttribute("data-wrapper-id",E.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),Sn||Ht.classList.add("persona-w-full"),b.appendChild(Ht),Z.push({messageId:E.id,fingerprint:xe,bubble:In});return}}}if(!st)if(E.variant==="reasoning"&&E.reasoning){if(!je)return;st=qi(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!Ne)return;st=zi(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;st=Yi(E,r)}else{let ht=(Zr=r.layout)==null?void 0:Zr.messages;ht!=null&&ht.renderUserMessage&&E.role==="user"?st=ht.renderUserMessage({message:E,config:r,streaming:!!E.streaming}):ht!=null&&ht.renderAssistantMessage&&E.role==="assistant"?st=ht.renderAssistantMessage({message:E,config:r,streaming:!!E.streaming}):st=Vs(E,y,ht,r.messageActions,Q,{loadingIndicatorRenderer:D,widgetConfig:r}),E.role!=="user"&&st&&nl(st,E,r,S)}let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-${E.id}`,It.setAttribute("data-wrapper-id",E.id),E.role==="user"&&It.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&It.classList.add("persona-w-full"),It.appendChild(st),Yp(dr,E.id,xe,It),b.appendChild(It)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let Re=Te.getAttribute("data-persona-ask-sheet-for");Re&&!R.has(Re)&&Lo(Ie.composerOverlay,Re)}),(at=(Ge=r.features)==null?void 0:Ge.toolCallDisplay)!=null&&at.grouped){let E=[],Te=[];f.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&Ne){Te.push(Re);return}Te.length>1&&E.push(Te),Te=[]}),Te.length>1&&E.push(Te),E.forEach((Re,Ke)=>{var dn,Ze;let xe=Re.map(lt=>Array.from(b.children).find(An=>An instanceof HTMLElement&&An.getAttribute("data-wrapper-id")===lt.id)).filter(lt=>!!lt);if(xe.length<2)return;let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-tool-group-${Ke}-${Re[0].id}`,kt.setAttribute("data-wrapper-id",`tool-group-${Ke}-${Re[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Qt=document.createElement("div");Qt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${Re.length} tools`,It=(Ze=(dn=r.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Ze.call(dn,{messages:Re,toolCalls:Re.map(lt=>lt.toolCall).filter(lt=>!!lt),defaultSummary:cn,config:r});F(Qt,It)||(Qt.textContent=cn);let Cn=document.createElement("div");Cn.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Qt,Cn),kt.appendChild(st),xe[0].before(kt),xe.forEach((lt,An)=>{let un=document.createElement("div");un.className="persona-tool-group-item persona-relative",un.setAttribute("data-persona-tool-group-item","true"),An<xe.length-1&&un.setAttribute("data-persona-tool-group-connector","true"),un.appendChild(lt),Cn.appendChild(un)})})}Zp(dr,U);let Se=f.some(E=>E.role==="assistant"&&E.streaming),Fe=f[f.length-1],nt=(Fe==null?void 0:Fe.role)==="assistant"&&!Fe.streaming&&Fe.variant!=="approval";if(zn&&f.some(E=>E.role==="user")&&!Se&&!nt){let E={config:r,streaming:!0,location:"standalone",defaultRenderer:Xo},Te=s.find(Ke=>Ke.renderLoadingIndicator),Re=null;if(Te!=null&&Te.renderLoadingIndicator&&(Re=Te.renderLoadingIndicator(E)),Re===null&&((it=r.loadingIndicator)!=null&&it.render)&&(Re=r.loadingIndicator.render(E)),Re===null&&(Re=Xo()),Re){let Ke=document.createElement("div"),xe=((ke=r.loadingIndicator)==null?void 0:ke.showBubble)!==!1;Ke.className=xe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ke.setAttribute("data-typing-indicator","true"),Ke.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ke.appendChild(Re);let kt=document.createElement("div");kt.className="persona-flex",kt.id="wrapper-typing-indicator",kt.setAttribute("data-wrapper-id","typing-indicator"),kt.appendChild(Ke),b.appendChild(kt)}}if(!zn&&f.length>0){let E=f[f.length-1],Te={config:r,lastMessage:E,messageCount:f.length},Re=s.find(xe=>xe.renderIdleIndicator),Ke=null;if(Re!=null&&Re.renderIdleIndicator&&(Ke=Re.renderIdleIndicator(Te)),Ke===null&&((Me=r.loadingIndicator)!=null&&Me.renderIdle)&&(Ke=r.loadingIndicator.renderIdle(Te)),Ke){let xe=document.createElement("div"),kt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;xe.className=kt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),xe.setAttribute("data-idle-indicator","true"),xe.appendChild(Ke);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(xe),b.appendChild(st)}}if(Fa(c,b),pe.length>0)for(let{messageId:E,fingerprint:Te,bubble:Re}of pe){let Ke=c.querySelector(`#wrapper-${E}`);Ke&&Re!==null&&(Ke.replaceChildren(Re),Ke.setAttribute("data-bubble-fp",Te),Lr.set(E,Te))}if(Lr.size>0)for(let E of Lr.keys())U.has(E)||Lr.delete(E);if(Z.length>0)for(let{messageId:E,fingerprint:Te,bubble:Re}of Z){let Ke=c.querySelector(`#wrapper-${E}`);Ke&&Re!==null&&(Ke.replaceChildren(Re),Ke.setAttribute("data-bubble-fp",Te),wr.set(E,Te))}if(wr.size>0)for(let E of wr.keys())U.has(E)||wr.delete(E)},Kr=null,aa=()=>{var y;if(Kr)return;let c=b=>{let M=b.composedPath();M.includes(ie)||Qe&&M.includes(Qe)||Rt(!1,"user")};Kr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},ds=()=>{var f;if(!Kr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Kr,!0),Kr=null};gt.push(()=>ds());let Jr=null,ia=()=>{var y;if(Jr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Rt(!1,"user"))};Jr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},ps=()=>{var f;if(!Jr)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Jr,!0),Jr=null};gt.push(()=>ps());let Gr=!1,us=new Set,la=()=>{var f,y,b,M;let c=(b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((M=r.features)==null?void 0:M.streamAnimation)},Rr=()=>{var at,it,ke,Me;if(!O())return;let c=Ie.peekBanner,f=Ie.peekTextNode;if(!c||!f)return;if(B){c.classList.remove("persona-pill-peek--visible");return}let y=(at=S==null?void 0:S.getMessages())!=null?at:[],b;for(let qe=y.length-1;qe>=0;qe--){let E=y[qe];if(E.role==="assistant"&&E.content){b=E;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let M=b.content,D=!!b.streaming,F=la(),U=Ua(F),R=U.type!=="none"?Os(U.type,F==null?void 0:F.plugins):null,Ce=((it=R==null?void 0:R.isAnimating)==null?void 0:it.call(R,b))===!0,pe=R!==null&&(D||Ce);pe&&R&&!us.has(R.name)&&(Ni(R,e),us.add(R.name));let Z=pe&&(R!=null&&R.containerClass)?R.containerClass:null,he=(ke=f.dataset.personaPeekStreamClass)!=null?ke:null;he&&he!==Z&&(f.classList.remove(he),delete f.dataset.personaPeekStreamClass),Z&&he!==Z&&(f.classList.add(Z),f.dataset.personaPeekStreamClass=Z),pe?(f.style.setProperty("--persona-stream-step",`${U.speed}ms`),f.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Se=pe?qa(M,U.buffer,R,b,D):M;if(pe&&U.placeholder==="skeleton"&&D&&(!Se||!Se.trim())){let qe=document.createElement("div"),E=_s();E.classList.add("persona-pill-peek__skeleton"),qe.appendChild(E),Fa(f,qe)}else{let qe=Math.max(0,Se.length-100),E=Se.length>100?Se.slice(-100):Se,Te=jo(E);if(!pe||!R){let Re=Se.length>100?`\u2026${E}`:E;f.textContent!==Re&&(f.textContent=Re)}else{let Re=Te;(R.wrap==="char"||R.wrap==="word")&&(Re=$s(Te,R.wrap,`peek-${b.id}`,{skipTags:R.skipTags,startIndex:qe}));let Ke=document.createElement("div");if(Ke.innerHTML=Re,R.useCaret&&E.length>0){let xe=za(),kt=Ke.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=kt[kt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(xe,st.nextSibling):Ke.appendChild(xe)}Fa(f,Ke),(Me=R.onAfterRender)==null||Me.call(R,{container:f,bubble:c,messageId:b.id,message:b,speed:U.speed,duration:U.duration})}}let Ge=zn||Gr;c.classList.toggle("persona-pill-peek--visible",Ge)};if(O()){let c=Ie.peekBanner;if(c){let b=M=>{M.preventDefault(),M.stopPropagation(),Rt(!0,"user")};c.addEventListener("pointerdown",b),gt.push(()=>{c.removeEventListener("pointerdown",b)})}let f=()=>{Gr||(Gr=!0,Rr())},y=()=>{Gr&&(Gr=!1,Rr())};re.addEventListener("pointerenter",f),re.addEventListener("pointerleave",y),gt.push(()=>{re.removeEventListener("pointerenter",f),re.removeEventListener("pointerleave",y)}),Qe&&(Qe.addEventListener("pointerenter",f),Qe.addEventListener("pointerleave",y),gt.push(()=>{Qe.removeEventListener("pointerenter",f),Qe.removeEventListener("pointerleave",y)}))}let ca=c=>{var he,Se,Fe,nt,Ge,at,it,ke;let f=(Se=(he=r.launcher)==null?void 0:he.composerBar)!=null?Se:{},y=(Fe=f.expandedSize)!=null?Fe:"anchored",b=(nt=f.bottomOffset)!=null?nt:"16px",M=f.collapsedMaxWidth,D=(Ge=f.expandedMaxWidth)!=null?Ge:"880px",F=(at=f.expandedTopOffset)!=null?at:"5vh",U=(it=f.modalMaxWidth)!=null?it:"880px",R=(ke=f.modalMaxHeight)!=null?ke:"min(90vh, 800px)",Ce="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",Z=ie.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Qe){let Me=Qe.style;Me.bottom=b,Me.width=M!=null?M:""}if(c&&y!=="fullscreen"){if(y==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=U,Z.maxWidth=Ce,Z.maxHeight=R,Z.height=R;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${pe})`,Z.top=F,Z.width=D,Z.maxWidth=Ce}},Xr=()=>{var R,Ce,pe,Z,he,Se,Fe,nt;if(!$())return;if(O()){let at=(pe=((Ce=(R=r.launcher)==null?void 0:R.composerBar)!=null?Ce:{}).expandedSize)!=null?pe:"anchored",it=B?"expanded":"collapsed";ie.dataset.state=it,ie.dataset.expandedSize=at,Qe&&(Qe.dataset.state=it,Qe.dataset.expandedSize=at),ie.style.removeProperty("display"),ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ca(B),ce.style.display=B?"flex":"none",lr(),B?(aa(),ia()):(ds(),ps()),Rr();return}let c=an(r),f=(Z=e.ownerDocument.defaultView)!=null?Z:window,y=(Se=(he=r.launcher)==null?void 0:he.mobileBreakpoint)!=null?Se:640,b=(nt=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?nt:!0,M=f.innerWidth<=y,D=b&&M&&T,F=yr(r).reveal;B?(ie.style.removeProperty("display"),ie.style.display=c?"flex":"",ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-95","persona-opacity-0"),re.classList.add("persona-scale-100","persona-opacity-100"),Ee?Ee.element.style.display="none":Je&&(Je.style.display="none")):(c?c&&(F==="overlay"||F==="push")&&!D?(ie.style.removeProperty("display"),ie.style.display="flex",ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ie.style.setProperty("display","none","important"),ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ie.style.display="",ie.classList.add("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100"),re.classList.add("persona-scale-95","persona-opacity-0")),Ee?Ee.element.style.display=c?"none":"":Je&&(Je.style.display=c?"none":""))},Rt=(c,f="user")=>{var D,F;if(!$()||B===c)return;let y=B;B=c,Xr();let b=(()=>{var Fe,nt,Ge,at,it,ke,Me,qe,E,Te;let U=(nt=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?nt:!1,R=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,Ce=(it=(at=r.launcher)==null?void 0:at.mobileFullscreen)!=null?it:!0,pe=(Me=(ke=r.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Me:640,Z=R.innerWidth<=pe,he=an(r)&&Ce&&Z,Se=O()&&((Te=(E=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:E.expandedSize)!=null?Te:"fullscreen")==="fullscreen";return U||Ce&&Z&&T||he||Se})();if(B&&b){if(!Jt){let U=e.getRootNode(),R=U instanceof ShadowRoot?U.host:e.closest(".persona-host");R&&(Jt=Fi(R,(F=(D=r.launcher)==null?void 0:D.zIndex)!=null?F:fn))}Gt||(Gt=Oi(e.ownerDocument))}else B||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null);B&&(Pt(),Vr(!0));let M={open:B,source:f,timestamp:Date.now()};B&&!y?o.emit("widget:opened",M):!B&&y&&o.emit("widget:closed",M),o.emit("widget:state",{open:B,launcherEnabled:T,voiceActive:mt.active,streaming:S.isStreaming()})},Ho=c=>{_t(c?"stop":"send"),q&&(q.disabled=c),cr.buttons.forEach(f=>{f.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Bo=()=>{mt.active||de&&de.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Bo(),200)});let ms=()=>{var y,b,M,D,F,U,R,Ce,pe,Z,he;Hn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",Xn.textContent=(D=(M=r.copy)==null?void 0:M.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",de.placeholder=(U=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?U:"How can I help...";let c=G.querySelector("[data-persona-intro-card]");if(c){let Se=((R=r.copy)==null?void 0:R.showWelcomeCard)!==!1;c.style.display=Se?"":"none",Se?(G.classList.remove("persona-gap-3"),G.classList.add("persona-gap-6")):(G.classList.remove("persona-gap-6"),G.classList.add("persona-gap-3"))}!((pe=(Ce=r.sendButton)==null?void 0:Ce.useIcon)!=null&&pe)&&!(S!=null&&S.isStreaming())&&(ae.textContent=(he=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?he:"Send"),de.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',de.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(f=>({...f,sessionId:c}))}});let Cr=null,da=()=>{Cr==null&&(Cr=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Cr),Cr=null;return}let f=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=Ta(f-b))})},100))};if(S=new Is(r,{onMessagesChanged(c){go($e,c,We),da(),S&&(c.some(M=>M.role==="user")?cr.render([],S,de,c):cr.render(r.suggestionChips,S,de,c,r.suggestionChipsConfig)),Vr(!zn),sa(c);let f=[...c].reverse().find(b=>b.role==="user"),y=mt.lastUserMessageId;f&&f.id!==y&&(mt.lastUserMessageId=f.id,o.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Ro(c),Rr()},onStatusChanged(c){var b;let f=(b=r.statusIndicator)!=null?b:{};ue(ln,(M=>{var D,F,U,R;return M==="idle"?(D=f.idleText)!=null?D:gn.idle:M==="connecting"?(F=f.connectingText)!=null?F:gn.connecting:M==="connected"?(U=f.connectedText)!=null?U:gn.connected:M==="error"?(R=f.errorText)!=null?R:gn.error:gn[M]})(c),f,c)},onStreamingChanged(c){zn=c,Ho(c),S&&go($e,S.getMessages(),We),c||Vr(!0),Rr()},onVoiceStatusChanged(c){var f,y;if(((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":K(),k();break;case"speaking":K(),Y();break;default:c==="idle"&&S.isBargeInActive()?(K(),_(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,K(),nr("system"),Ln());break}},onArtifactsState(c){On=c,jn(),Ro()}}),Lt.current=S,((fc=(gc=r.voiceRecognition)==null?void 0:gc.provider)==null?void 0:fc.type)==="runtype")try{S.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&S.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(V||r.onSSEEvent)&&S.setSSEEventCallback((c,f)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,f),le==null||le.processEvent(c,f),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,y,b;c&&(c.metadata&&(d=ul(c.metadata),C.syncFromMetadata()),(f=c.messages)!=null&&f.length&&S.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&S.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var f,y,b;!O()||B||!((b=(y=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Rt(!0,"auto")},fs=c=>{var M;if(c.preventDefault(),S.isStreaming()){S.cancel(),le==null||le.reset(),ve==null||ve.update();return}let f=de.value.trim(),y=(M=tt==null?void 0:tt.hasAttachments())!=null?M:!1;if(!f&&!y)return;gs();let b;y&&(b=[],b.push(...tt.getContentParts()),f&&b.push(Ia(f))),de.value="",de.style.height="auto",fo(),S.sendMessage(f,{contentParts:b}),y&&tt.clearAttachments()},pa=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Do={...Oa},No=!1,fo=()=>{Do={...Oa}},ua=()=>S.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),ma=c=>{if(!de)return;No=!0,de.value=c,de.dispatchEvent(new Event("input",{bubbles:!0})),No=!1;let f=de.value.length;de.setSelectionRange(f,f)},hs=()=>{No||fo()},ys=c=>{if(de){if(pa()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=de.selectionStart===0&&de.selectionEnd===0,y=Jp({direction:c.key==="ArrowUp"?"up":"down",history:ua(),currentValue:de.value,atStart:f,state:Do});if(Do=y.state,y.handled){c.preventDefault(),y.value!==void 0&&ma(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(S.isStreaming()){c.preventDefault();return}fo(),c.preventDefault(),ae.click()}}},bs=c=>{c.key!=="Escape"||c.isComposing||S.isStreaming()&&c.composedPath().includes(ce)&&(S.cancel(),le==null||le.reset(),ve==null||ve.update(),fo(),c.preventDefault(),c.stopImmediatePropagation())},xs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!tt)return;let f=Eb(c.clipboardData);f.length!==0&&(c.preventDefault(),await tt.handleFiles(f))},vn=null,Vn=!1,Hr=null,ot=null,vs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ho=(c="user")=>{var D,F,U,R,Ce,pe,Z;if(Vn||S.isStreaming())return;let f=vs();if(!f)return;vn=new f;let b=(F=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?F:2e3;vn.continuous=!0,vn.interimResults=!0,vn.lang="en-US";let M=de.value;vn.onresult=he=>{let Se="",Fe="";for(let Ge=0;Ge<he.results.length;Ge++){let at=he.results[Ge],it=at[0].transcript;at.isFinal?Se+=it+" ":Fe=it}let nt=M+Se+Fe;de.value=nt,Hr&&clearTimeout(Hr),(Se||Fe)&&(Hr=window.setTimeout(()=>{let Ge=de.value.trim();Ge&&vn&&Vn&&(gr(),de.value="",de.style.height="auto",S.sendMessage(Ge,{viaVoice:!0}))},b))},vn.onerror=he=>{he.error!=="no-speech"&&gr()},vn.onend=()=>{if(Vn){let he=de.value.trim();he&&he!==M.trim()&&(de.value="",de.style.height="auto",S.sendMessage(he,{viaVoice:!0})),gr()}};try{if(vn.start(),Vn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),nr(c),Ln(),q){let he=(U=r.voiceRecognition)!=null?U:{};ot={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(R=he.iconName)!=null?R:"mic",iconSize:parseFloat((Z=(pe=he.iconSize)!=null?pe:(Ce=r.sendButton)==null?void 0:Ce.size)!=null?Z:"40")||24};let Se=he.recordingBackgroundColor,Fe=he.recordingIconColor,nt=he.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Se!=null?Se:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let Ge=q.querySelector("svg");Ge&&Ge.setAttribute("stroke",Fe)}nt&&(q.style.borderColor=nt),q.setAttribute("aria-label","Stop voice recognition")}}catch{gr("system")}},gr=(c="user")=>{if(Vn){if(Vn=!1,Hr&&(clearTimeout(Hr),Hr=null),vn){try{vn.stop()}catch{}vn=null}if(mt.active=!1,nr(c),Ln(),q){if(q.classList.remove("persona-voice-recording"),ot){q.style.backgroundColor=ot.backgroundColor,q.style.color=ot.color,q.style.borderColor=ot.borderColor;let f=q.querySelector("svg");f&&f.setAttribute("stroke",ot.color||"currentColor"),ot=null}q.setAttribute("aria-label","Start voice recognition")}}},ga=(c,f)=>{var at,it,ke,Me,qe,E,Te,Re;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((at=c==null?void 0:c.provider)==null?void 0:at.type)==="runtype";if(!(y||b))return null;let D=h("div","persona-send-button-wrapper"),F=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let U=(it=c==null?void 0:c.iconName)!=null?it:"mic",R=(ke=f==null?void 0:f.size)!=null?ke:"40px",Ce=(Me=c==null?void 0:c.iconSize)!=null?Me:R,pe=parseFloat(Ce)||24,Z=(qe=c==null?void 0:c.backgroundColor)!=null?qe:f==null?void 0:f.backgroundColor,he=(E=c==null?void 0:c.iconColor)!=null?E:f==null?void 0:f.textColor;F.style.width=Ce,F.style.height=Ce,F.style.minWidth=Ce,F.style.minHeight=Ce,F.style.fontSize="18px",F.style.lineHeight="1",he?F.style.color=he:F.style.color="var(--persona-text, #111827)";let Fe=be(U,pe,he||"currentColor",1.5);Fe?F.appendChild(Fe):F.textContent="\u{1F3A4}",Z?F.style.backgroundColor=Z:F.style.backgroundColor="",c!=null&&c.borderWidth&&(F.style.borderWidth=c.borderWidth,F.style.borderStyle="solid"),c!=null&&c.borderColor&&(F.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(F.style.paddingLeft=c.paddingX,F.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(F.style.paddingTop=c.paddingY,F.style.paddingBottom=c.paddingY),D.appendChild(F);let nt=(Te=c==null?void 0:c.tooltipText)!=null?Te:"Start voice recognition";if(((Re=c==null?void 0:c.showTooltip)!=null?Re:!1)&&nt){let Ke=h("div","persona-send-button-tooltip");Ke.textContent=nt,D.appendChild(Ke)}return{micButton:F,micButtonWrapper:D}},Qr=()=>{var f,y,b,M,D;if(!q||ot)return;let c=(f=r.voiceRecognition)!=null?f:{};ot={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((D=(M=c.iconSize)!=null?M:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},Ve=(c,f)=>{var D,F,U,R,Ce;if(!q)return;let y=q.querySelector("svg");y&&y.remove();let b=(Ce=ot==null?void 0:ot.iconSize)!=null?Ce:parseFloat((R=(U=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?U:(F=r.sendButton)==null?void 0:F.size)!=null?R:"40")||24,M=be(c,b,f,1.5);M&&q.appendChild(M)},A=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},_=()=>{var M;if(!q)return;Qr();let c=(M=r.voiceRecognition)!=null?M:{},f=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(A(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let D=q.querySelector("svg");D&&D.setAttribute("stroke",y)}b&&(q.style.borderColor=b),q.setAttribute("aria-label","Stop voice recognition")},k=()=>{var U,R,Ce,pe,Z,he,Se,Fe;if(!q)return;Qr();let c=(U=r.voiceRecognition)!=null?U:{},f=S.getVoiceInterruptionMode(),y=(R=c.processingIconName)!=null?R:"loader",b=(pe=(Ce=c.processingIconColor)!=null?Ce:ot==null?void 0:ot.color)!=null?pe:"",M=(he=(Z=c.processingBackgroundColor)!=null?Z:ot==null?void 0:ot.backgroundColor)!=null?he:"",D=(Fe=(Se=c.processingBorderColor)!=null?Se:ot==null?void 0:ot.borderColor)!=null?Fe:"";A(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=M,q.style.borderColor=D;let F=b||"currentColor";q.style.color=F,Ve(y,F),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},Y=()=>{var Ce,pe,Z,he,Se,Fe,nt,Ge,at,it,ke,Me;if(!q)return;Qr();let c=(Ce=r.voiceRecognition)!=null?Ce:{},f=S.getVoiceInterruptionMode(),y=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=(pe=c.speakingIconName)!=null?pe:y,M=(Fe=c.speakingIconColor)!=null?Fe:f==="barge-in"?(he=(Z=c.recordingIconColor)!=null?Z:ot==null?void 0:ot.color)!=null?he:"":(Se=ot==null?void 0:ot.color)!=null?Se:"",D=(at=c.speakingBackgroundColor)!=null?at:f==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(Ge=ot==null?void 0:ot.backgroundColor)!=null?Ge:"",F=(Me=c.speakingBorderColor)!=null?Me:f==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(ke=ot==null?void 0:ot.borderColor)!=null?ke:"";A(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=D,q.style.borderColor=F;let U=M||"currentColor";q.style.color=U,Ve(b,U);let R=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",R),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},K=()=>{var c,f,y;q&&(A(),ot&&(q.style.backgroundColor=(c=ot.backgroundColor)!=null?c:"",q.style.color=(f=ot.color)!=null?f:"",q.style.borderColor=(y=ot.borderColor)!=null?y:"",Ve(ot.iconName,ot.color||"currentColor"),ot=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},J=()=>{var c,f;if(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let y=S.getVoiceStatus(),b=S.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){S.stopVoicePlayback();return}if(S.isBargeInActive()){S.stopVoicePlayback(),S.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Ln(),nr("user"),K()});return}S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),mt.manuallyDeactivated=!S.isVoiceActive(),Ln(),nr("user"),S.isVoiceActive()?_():K()});return}if(Vn){let y=de.value.trim();mt.manuallyDeactivated=!0,Ln(),gr("user"),y&&(de.value="",de.style.height="auto",S.sendMessage(y))}else mt.manuallyDeactivated=!1,Ln(),ho("user")};Bn=J,q&&(q.addEventListener("click",J),gt.push(()=>{var c,f;((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(S.isVoiceActive()&&S.toggleVoice(),K()):gr("system"),q&&q.removeEventListener("click",J)}));let Xe=o.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("auto"),S.isVoiceActive()&&_()}):ho("auto"))},600))});gt.push(Xe);let Oe=o.on("action:resubmit",()=>{setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)});gt.push(Oe);let et=()=>{Rt(!B,"user")},Ee=null,Je=null;if(T&&!O()){let c=s.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:r,defaultRenderer:()=>Us(r,et).element,onToggle:et});f&&(Je=f)}Je||(Ee=Us(r,et))}Ee?e.appendChild(Ee.element):Je&&e.appendChild(Je),Xr(),cr.render(r.suggestionChips,S,de,void 0,r.suggestionChipsConfig),ms(),Ho(S.isStreaming()),Vr(!0),ta(),L&&(!T||O()?setTimeout(()=>Bo(),0):B&&setTimeout(()=>Bo(),200));let Pt=()=>{var R,Ce,pe,Z,he,Se,Fe,nt,Ge,at,it,ke,Me,qe,E,Te,Re,Ke,xe,kt,st,Qt;if(O()){yt(),Xr();return}let c=an(r),f=(Ce=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?Ce:!1,y=c||f||((Z=(pe=r.launcher)==null?void 0:pe.fullHeight)!=null?Z:!1),b=(he=e.ownerDocument.defaultView)!=null?he:window,M=(Fe=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?Fe:!0,D=(Ge=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?Ge:640,F=b.innerWidth<=D,U=M&&F&&T;try{if(U){lr(),Eo(e,r);return}if(I&&(I=!1,lr(),Eo(e,r)),!T&&!c){re.style.height="",re.style.width="";return}if(!f&&!c){let cn=(it=(at=r==null?void 0:r.launcher)==null?void 0:at.width)!=null?it:r==null?void 0:r.launcherWidth,It=cn!=null?cn:sr;re.style.width=It,re.style.maxWidth=It}if(vr(),!y){let cn=b.innerHeight,It=64,Cn=(Me=(ke=r.launcher)==null?void 0:ke.heightOffset)!=null?Me:0,dn=Math.max(200,cn-It),Ze=Math.min(640,dn),lt=Math.max(200,Ze-Cn);re.style.height=`${lt}px`}}finally{if(yt(),Xr(),B&&T){let It=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Te=(E=r.launcher)==null?void 0:E.mobileBreakpoint)!=null?Te:640),Cn=(Ke=(Re=r.launcher)==null?void 0:Re.sidebarMode)!=null?Ke:!1,dn=(kt=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?kt:!0,Ze=an(r)&&dn&&It,lt=Cn||dn&&It&&T||Ze;if(lt&&!Gt){let An=e.getRootNode(),un=An instanceof ShadowRoot?An.host:e.closest(".persona-host");un&&!Jt&&(Jt=Fi(un,(Qt=(st=r.launcher)==null?void 0:st.zIndex)!=null?Qt:fn)),Gt=Oi(e.ownerDocument)}else lt||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null)}}};Pt();let nn=(hc=e.ownerDocument.defaultView)!=null?hc:window;if(nn.addEventListener("resize",Pt),gt.push(()=>nn.removeEventListener("resize",Pt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yt()});c.observe(_e),gt.push(()=>c.disconnect())}ur=G.scrollTop;let Ct=G.scrollHeight,Mt=()=>{let c=G.scrollTop,f=G.scrollHeight,y=f<Ct;Ct=f;let{action:b,nextLastScrollTop:M}=_a({following:pr.isFollowing(),currentScrollTop:c,lastScrollTop:ur,nearBottom:Ds(G,as),userScrollThreshold:Zs,isAutoScrolling:Pr||uo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ur=M,b==="resume"){zr();return}b==="pause"&&cs()};G.addEventListener("scroll",Mt,{passive:!0}),gt.push(()=>G.removeEventListener("scroll",Mt));let rn=c=>{let f=ja({following:pr.isFollowing(),deltaY:c.deltaY,nearBottom:Ds(G,as),resumeWhenNearBottom:!0});f==="pause"?cs():f==="resume"&&zr()};G.addEventListener("wheel",rn,{passive:!0}),gt.push(()=>G.removeEventListener("wheel",rn)),St.addEventListener("click",()=>{G.scrollTop=G.scrollHeight,ur=G.scrollTop,zr(),Vr(!0)}),gt.push(()=>St.remove()),gt.push(()=>{ls()});let pn=()=>{Ue&&(qn&&(Ue.removeEventListener("click",qn),qn=null),$()?(Ue.style.display="",qn=()=>{Rt(!1,"user")},Ue.addEventListener("click",qn)):Ue.style.display="none")};pn(),(()=>{let{clearChatButton:c}=Ie;c&&c.addEventListener("click",()=>{S.clearMessages(),dr.clear(),zr(),Lo(Ie.composerOverlay);try{localStorage.removeItem(rs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},C.syncFromMetadata(),V==null||V.clear(),le==null||le.reset(),ve==null||ve.update()})})(),Ot&&Ot.addEventListener("submit",fs),de==null||de.addEventListener("keydown",ys),de==null||de.addEventListener("input",hs),de==null||de.addEventListener("paste",xs);let Xt=(yc=e.ownerDocument)!=null?yc:document;Xt.addEventListener("keydown",bs,!0);let rr="persona-attachment-drop-active",ws=0,Ci=()=>{ws=0,ce.classList.remove(rr)},Fo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&tt!==null},Sl=c=>{!ui(c.dataTransfer)||!Fo()||(ws++,ws===1&&ce.classList.add(rr))},Tl=c=>{!ui(c.dataTransfer)||!Fo()||(ws--,ws<=0&&Ci())},El=c=>{!ui(c.dataTransfer)||!Fo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Ml=c=>{var y;if(!ui(c.dataTransfer)||!Fo())return;c.preventDefault(),c.stopPropagation(),Ci();let f=Array.from((y=c.dataTransfer.files)!=null?y:[]);f.length!==0&&tt.handleFiles(f)},Yr=!0;ce.addEventListener("dragenter",Sl,Yr),ce.addEventListener("dragleave",Tl,Yr),e.addEventListener("dragover",El,Yr),e.addEventListener("drop",Ml,Yr);let fa=e.ownerDocument,kl=c=>{Fo()&&c.preventDefault()},Ll=c=>{Fo()&&c.preventDefault()};fa.addEventListener("dragover",kl),fa.addEventListener("drop",Ll),gt.push(()=>{Ot&&Ot.removeEventListener("submit",fs),de==null||de.removeEventListener("keydown",ys),de==null||de.removeEventListener("input",hs),de==null||de.removeEventListener("paste",xs),Xt.removeEventListener("keydown",bs,!0)}),gt.push(()=>{ce.removeEventListener("dragenter",Sl,Yr),ce.removeEventListener("dragleave",Tl,Yr),e.removeEventListener("dragover",El,Yr),e.removeEventListener("drop",Ml,Yr),fa.removeEventListener("dragover",kl),fa.removeEventListener("drop",Ll),Ci()}),gt.push(()=>{S.cancel()}),Ee?gt.push(()=>{Ee==null||Ee.destroy()}):Je&>.push(()=>{Je==null||Je.remove()});let en={update(c){var tn,Ar,Dr,ha,ya,ba,wo,xa,Cs,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp;let f=r.toolCall,y=r.messageActions,b=(tn=r.layout)==null?void 0:tn.messages,M=r.colorScheme,D=r.loadingIndicator,F=r.iterationDisplay,U=(Ar=r.features)==null?void 0:Ar.showReasoning,R=(Dr=r.features)==null?void 0:Dr.showToolCalls,Ce=(ha=r.features)==null?void 0:ha.toolCallDisplay,pe=(ya=r.features)==null?void 0:ya.reasoningDisplay;r={...r,...c},lr(),Eo(e,r),ii(e,r),li(e,r),jn(),r.colorScheme!==M&&qr();let Z=ci.getForInstance(r.plugins);s.length=0,s.push(...Z),T=(wo=(ba=r.launcher)==null?void 0:ba.enabled)!=null?wo:!0,H=(Cs=(xa=r.launcher)==null?void 0:xa.autoExpand)!=null?Cs:!1,je=(Tc=(Sc=r.features)==null?void 0:Sc.showReasoning)!=null?Tc:!0,Ne=(Mc=(Ec=r.features)==null?void 0:Ec.showToolCalls)!=null?Mc:!0,ye=(Lc=(kc=r.features)==null?void 0:kc.scrollToBottom)!=null?Lc:{},zt(),Wr();let he=ge;if(ge=(Ic=(Pc=r.features)==null?void 0:Pc.showEventStreamToggle)!=null?Ic:!1,ge&&!he){if(V||(ee=new Xs(He),V=new Gs(Pe,ee),le=le!=null?le:new Qs,ee.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),S.setSSEEventCallback((X,xt)=>{var Nt;(Nt=r.onSSEEvent)==null||Nt.call(r,X,xt),le==null||le.processEvent(X,xt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!ut&&De){let X=(Rc=(Wc=r.features)==null?void 0:Wc.eventStream)==null?void 0:Rc.classNames,xt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");ut=h("button",xt),ut.style.width="28px",ut.style.height="28px",ut.style.color=En.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Nt=be("activity","18px","currentColor",1.5);Nt&&ut.appendChild(Nt);let ct=Ie.clearChatButtonWrapper,Tt=Ie.closeButtonWrapper,on=ct||Tt;on&&on.parentNode===De?De.insertBefore(ut,on):De.appendChild(ut),ut.addEventListener("click",()=>{fe?Dn():yn()})}}else!ge&&he&&(Dn(),ut&&(ut.remove(),ut=null),V==null||V.clear(),ee==null||ee.destroy(),V=null,ee=null,le==null||le.reset(),le=null);if(((Hc=r.launcher)==null?void 0:Hc.enabled)===!1&&Ee&&(Ee.destroy(),Ee=null),((Bc=r.launcher)==null?void 0:Bc.enabled)===!1&&Je&&(Je.remove(),Je=null),((Dc=r.launcher)==null?void 0:Dc.enabled)!==!1&&!Ee&&!Je){let X=s.find(xt=>xt.renderLauncher);if(X!=null&&X.renderLauncher){let xt=X.renderLauncher({config:r,defaultRenderer:()=>Us(r,et).element,onToggle:et});xt&&(Je=xt,e.appendChild(Je))}Je||(Ee=Us(r,et),e.appendChild(Ee.element))}Ee&&Ee.update(r),Ae&&((Nc=r.launcher)==null?void 0:Nc.title)!==void 0&&(Ae.textContent=r.launcher.title),Be&&((Fc=r.launcher)==null?void 0:Fc.subtitle)!==void 0&&(Be.textContent=r.launcher.subtitle);let Se=(Oc=r.layout)==null?void 0:Oc.header;if((Se==null?void 0:Se.layout)!==w&&De){let X=Se?qs(r,Se,{showClose:$(),onClose:()=>Rt(!1,"user")}):ro({config:r,showClose:$(),onClose:()=>Rt(!1,"user")});De.replaceWith(X.header),De=X.header,N=X.iconHolder,Ae=X.headerTitle,Be=X.headerSubtitle,Ue=X.closeButton,w=Se==null?void 0:Se.layout}else if(Se&&(N&&(N.style.display=Se.showIcon===!1?"none":""),Ae&&(Ae.style.display=Se.showTitle===!1?"none":""),Be&&(Be.style.display=Se.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=Se.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let X=Se.showClearChat;if(X!==void 0){Ie.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:xt}=Ie;xt&&!xt.classList.contains("persona-absolute")&&(X?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let nt=(($c=r.layout)==null?void 0:$c.showHeader)!==!1;De&&(De.style.display=nt?"":"none");let Ge=((_c=r.layout)==null?void 0:_c.showFooter)!==!1;_e&&(_e.style.display=Ge?"":"none"),yt(),Wr(),T!==W?T?Rt(H,"auto"):(B=!0,Xr()):H!==P&&Rt(H,"auto"),P=H,W=T,Pt(),pn();let ke=JSON.stringify(c.toolCall)!==JSON.stringify(f),Me=JSON.stringify(r.messageActions)!==JSON.stringify(y),qe=JSON.stringify((jc=r.layout)==null?void 0:jc.messages)!==JSON.stringify(b),E=((Uc=r.loadingIndicator)==null?void 0:Uc.render)!==(D==null?void 0:D.render)||((qc=r.loadingIndicator)==null?void 0:qc.renderIdle)!==(D==null?void 0:D.renderIdle)||((zc=r.loadingIndicator)==null?void 0:zc.showBubble)!==(D==null?void 0:D.showBubble),Te=r.iterationDisplay!==F,Re=((Kc=(Vc=r.features)==null?void 0:Vc.showReasoning)!=null?Kc:!0)!==(U!=null?U:!0)||((Gc=(Jc=r.features)==null?void 0:Jc.showToolCalls)!=null?Gc:!0)!==(R!=null?R:!0)||JSON.stringify((Xc=r.features)==null?void 0:Xc.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Qc=r.features)==null?void 0:Qc.reasoningDisplay)!==JSON.stringify(pe);(ke||Me||qe||E||Te||Re)&&S&&(ss++,go($e,S.getMessages(),We));let xe=(Yc=r.launcher)!=null?Yc:{},kt=(Zc=xe.headerIconHidden)!=null?Zc:!1,st=(td=(ed=r.layout)==null?void 0:ed.header)==null?void 0:td.showIcon,Qt=kt||st===!1,cn=xe.headerIconName,It=(nd=xe.headerIconSize)!=null?nd:"48px";if(N){let X=ce.querySelector(".persona-border-b-persona-divider"),xt=X==null?void 0:X.querySelector(".persona-flex-col");if(Qt)N.style.display="none",X&&xt&&!X.contains(xt)&&X.insertBefore(xt,X.firstChild);else{if(N.style.display="",N.style.height=It,N.style.width=It,X&&xt&&(X.contains(N)?N.nextSibling!==xt&&(N.remove(),X.insertBefore(N,xt)):X.insertBefore(N,xt)),cn){let ct=parseFloat(It)||24,Tt=be(cn,ct*.6,"#ffffff",2);Tt?N.replaceChildren(Tt):N.textContent=(rd=xe.agentIconText)!=null?rd:"\u{1F4AC}"}else if(xe.iconUrl){let ct=N.querySelector("img");if(ct)ct.src=xe.iconUrl,ct.style.height=It,ct.style.width=It;else{let Tt=document.createElement("img");Tt.src=xe.iconUrl,Tt.alt="",Tt.className="persona-rounded-xl persona-object-cover",Tt.style.height=It,Tt.style.width=It,N.replaceChildren(Tt)}}else{let ct=N.querySelector("svg"),Tt=N.querySelector("img");(ct||Tt)&&N.replaceChildren(),N.textContent=(od=xe.agentIconText)!=null?od:"\u{1F4AC}"}let Nt=N.querySelector("img");Nt&&(Nt.style.height=It,Nt.style.width=It)}}let Cn=(ad=(sd=r.layout)==null?void 0:sd.header)==null?void 0:ad.showTitle,dn=(ld=(id=r.layout)==null?void 0:id.header)==null?void 0:ld.showSubtitle;if(Ae&&(Ae.style.display=Cn===!1?"none":""),Be&&(Be.style.display=dn===!1?"none":""),Ue){((dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let xt=(pd=xe.closeButtonSize)!=null?pd:"32px",Nt=(ud=xe.closeButtonPlacement)!=null?ud:"inline";Ue.style.height=xt,Ue.style.width=xt;let{closeButtonWrapper:ct}=Ie,Tt=Nt==="top-right",on=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&Tt!==on)if(ct.remove(),Tt)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(ct);else{let pt=(gd=(md=xe.clearChat)==null?void 0:md.placement)!=null?gd:"inline",sn=(hd=(fd=xe.clearChat)==null?void 0:fd.enabled)!=null?hd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Rn=ce.querySelector(".persona-border-b-persona-divider");Rn&&Rn.appendChild(ct)}if(Ue.style.color=xe.closeButtonColor||En.actionIconColor,xe.closeButtonBackgroundColor?(Ue.style.backgroundColor=xe.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let pt=xe.closeButtonBorderWidth||"0px",sn=xe.closeButtonBorderColor||"transparent";Ue.style.border=`${pt} solid ${sn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");xe.closeButtonBorderRadius?(Ue.style.borderRadius=xe.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(Ue.style.paddingLeft=xe.closeButtonPaddingX,Ue.style.paddingRight=xe.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),xe.closeButtonPaddingY?(Ue.style.paddingTop=xe.closeButtonPaddingY,Ue.style.paddingBottom=xe.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let mn=(yd=xe.closeButtonIconName)!=null?yd:"x",fr=(bd=xe.closeButtonIconText)!=null?bd:"\xD7";Ue.innerHTML="";let Tn=be(mn,"28px","currentColor",1);Tn?Ue.appendChild(Tn):Ue.textContent=fr;let Yt=(xd=xe.closeButtonTooltipText)!=null?xd:"Close chat",Jn=(vd=xe.closeButtonShowTooltip)!=null?vd:!0;if(Ue.setAttribute("aria-label",Yt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Jn&&Yt)){let pt=null,sn=()=>{if(pt||!Ue)return;let Co=Ue.ownerDocument,As=Co.body;if(!As)return;pt=Sr(Co,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Ss=Sr(Co,"div");Ss.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ss);let Ao=Ue.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(eo),pt.style.left=`${Ao.left+Ao.width/2}px`,pt.style.top=`${Ao.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Rn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Rn),Ue.addEventListener("focus",sn),Ue.addEventListener("blur",Rn),ct._cleanupTooltip=()=>{Rn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Rn)),Ue&&(Ue.removeEventListener("focus",sn),Ue.removeEventListener("blur",Rn))}}}let{clearChatButton:Ze,clearChatButtonWrapper:lt}=Ie;if(Ze){let X=(wd=xe.clearChat)!=null?wd:{},xt=(Cd=X.enabled)!=null?Cd:!0,Nt=(Sd=(Ad=r.layout)==null?void 0:Ad.header)==null?void 0:Sd.showClearChat,ct=Nt!==void 0?Nt:xt,Tt=(Td=X.placement)!=null?Td:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:on}=Ie;!O()&&on&&!on.classList.contains("persona-absolute")&&(ct?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let mn=Tt==="top-right",fr=lt.classList.contains("persona-absolute");if(!O()&&mn!==fr&&ct){if(lt.remove(),mn)lt.className="persona-absolute persona-top-4 persona-z-50",lt.style.right="48px",ce.style.position="relative",ce.appendChild(lt);else{lt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",lt.style.right="";let Yt=ce.querySelector(".persona-border-b-persona-divider"),Jn=Ie.closeButtonWrapper;Yt&&Jn&&Jn.parentElement===Yt?Yt.insertBefore(lt,Jn):Yt&&Yt.appendChild(lt)}let Tn=Ie.closeButtonWrapper;Tn&&!Tn.classList.contains("persona-absolute")&&(mn?Tn.classList.add("persona-ml-auto"):Tn.classList.remove("persona-ml-auto"))}}if(ct){if(!O()){let pt=(Ed=X.size)!=null?Ed:"32px";Ze.style.height=pt,Ze.style.width=pt}let on=(Md=X.iconName)!=null?Md:"refresh-cw",mn=(kd=X.iconColor)!=null?kd:"";Ze.style.color=mn||En.actionIconColor,Ze.innerHTML="";let fr=O()?"14px":"20px",Tn=be(on,fr,"currentColor",2);if(Tn&&Ze.appendChild(Tn),X.backgroundColor?(Ze.style.backgroundColor=X.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let pt=X.borderWidth||"0px",sn=X.borderColor||"transparent";Ze.style.border=`${pt} solid ${sn}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");X.borderRadius?(Ze.style.borderRadius=X.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),X.paddingX?(Ze.style.paddingLeft=X.paddingX,Ze.style.paddingRight=X.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),X.paddingY?(Ze.style.paddingTop=X.paddingY,Ze.style.paddingBottom=X.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let Yt=(Ld=X.tooltipText)!=null?Ld:"Clear chat",Jn=(Pd=X.showTooltip)!=null?Pd:!0;if(Ze.setAttribute("aria-label",Yt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Jn&&Yt)){let pt=null,sn=()=>{if(pt||!Ze)return;let Co=Ze.ownerDocument,As=Co.body;if(!As)return;pt=Sr(Co,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Ss=Sr(Co,"div");Ss.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ss);let Ao=Ze.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(eo),pt.style.left=`${Ao.left+Ao.width/2}px`,pt.style.top=`${Ao.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Rn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",Rn),Ze.addEventListener("focus",sn),Ze.addEventListener("blur",Rn),lt._cleanupTooltip=()=>{Rn(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",Rn)),Ze&&(Ze.removeEventListener("focus",sn),Ze.removeEventListener("blur",Rn))}}}}let An=r.actionParsers&&r.actionParsers.length?r.actionParsers:[di],un=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick];C=pi({parsers:An,handlers:un,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),We=Ku(r,C,oe),S.updateConfig(r),go($e,S.getMessages(),We),cr.render(r.suggestionChips,S,de,void 0,r.suggestionChipsConfig),ms(),Ho(S.isStreaming());let yo=((Id=r.voiceRecognition)==null?void 0:Id.enabled)===!0,bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),xo=((Rd=(Wd=r.voiceRecognition)==null?void 0:Wd.provider)==null?void 0:Rd.type)==="runtype";if(yo&&(bo||xo))if(!q||!$t){let X=ga(r.voiceRecognition,r.sendButton);X&&(q=X.micButton,$t=X.micButtonWrapper,At.insertBefore($t,Mn),q.addEventListener("click",J),q.disabled=S.isStreaming())}else{let X=(Hd=r.voiceRecognition)!=null?Hd:{},xt=(Bd=r.sendButton)!=null?Bd:{},Nt=(Dd=X.iconName)!=null?Dd:"mic",ct=(Nd=xt.size)!=null?Nd:"40px",Tt=(Fd=X.iconSize)!=null?Fd:ct,on=parseFloat(Tt)||24;q.style.width=Tt,q.style.height=Tt,q.style.minWidth=Tt,q.style.minHeight=Tt;let mn=($d=(Od=X.iconColor)!=null?Od:xt.textColor)!=null?$d:"currentColor";q.innerHTML="";let fr=be(Nt,on,mn,2);fr?q.appendChild(fr):q.textContent="\u{1F3A4}";let Tn=(_d=X.backgroundColor)!=null?_d:xt.backgroundColor;Tn?q.style.backgroundColor=Tn:q.style.backgroundColor="",mn?q.style.color=mn:q.style.color="var(--persona-text, #111827)",X.borderWidth?(q.style.borderWidth=X.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),X.borderColor?q.style.borderColor=X.borderColor:q.style.borderColor="",X.paddingX?(q.style.paddingLeft=X.paddingX,q.style.paddingRight=X.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),X.paddingY?(q.style.paddingTop=X.paddingY,q.style.paddingBottom=X.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Yt=$t==null?void 0:$t.querySelector(".persona-send-button-tooltip"),Jn=(jd=X.tooltipText)!=null?jd:"Start voice recognition";if(((Ud=X.showTooltip)!=null?Ud:!1)&&Jn)if(Yt)Yt.textContent=Jn,Yt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Jn,$t==null||$t.insertBefore(sn,q)}else Yt&&(Yt.style.display="none");$t.style.display="",q.disabled=S.isStreaming()}else q&&$t&&($t.style.display="none",((zd=(qd=r.voiceRecognition)==null?void 0:qd.provider)==null?void 0:zd.type)==="runtype"?S.isVoiceActive()&&S.toggleVoice():Vn&&gr());if(((Vd=r.attachments)==null?void 0:Vd.enabled)===!0)if(!Dt||!Ye){let X=(Kd=r.attachments)!=null?Kd:{},Nt=(Gd=((Jd=r.sendButton)!=null?Jd:{}).size)!=null?Gd:"40px";me||(me=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),me.style.display="none",Ot.insertBefore(me,de)),ne||(ne=document.createElement("input"),ne.type="file",ne.accept=((Xd=X.allowedTypes)!=null?Xd:Nr).join(","),ne.multiple=((Qd=X.maxFiles)!=null?Qd:4)>1,ne.style.display="none",ne.setAttribute("aria-label","Attach files"),Ot.insertBefore(ne,de)),Dt=h("div","persona-send-button-wrapper"),Ye=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ye.type="button",Ye.setAttribute("aria-label",(Yd=X.buttonTooltipText)!=null?Yd:"Attach file");let ct=(Zd=X.buttonIconName)!=null?Zd:"paperclip",Tt=Nt,on=parseFloat(Tt)||40,mn=Math.round(on*.6);Ye.style.width=Tt,Ye.style.height=Tt,Ye.style.minWidth=Tt,Ye.style.minHeight=Tt,Ye.style.fontSize="18px",Ye.style.lineHeight="1",Ye.style.backgroundColor="transparent",Ye.style.color="var(--persona-primary, #111827)",Ye.style.border="none",Ye.style.borderRadius="6px",Ye.style.transition="background-color 0.15s ease",Ye.addEventListener("mouseenter",()=>{Ye.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ye.addEventListener("mouseleave",()=>{Ye.style.backgroundColor="transparent"});let fr=be(ct,mn,"currentColor",1.5);fr?Ye.appendChild(fr):Ye.textContent="\u{1F4CE}",Ye.addEventListener("click",Jn=>{Jn.preventDefault(),ne==null||ne.click()}),Dt.appendChild(Ye);let Tn=(ep=X.buttonTooltipText)!=null?ep:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=Tn,Dt.appendChild(Yt),rt.append(Dt),!tt&&ne&&me&&(tt=Ko.fromConfig(X),tt.setPreviewsContainer(me),ne.addEventListener("change",async()=>{tt&&(ne!=null&&ne.files)&&(await tt.handleFileSelect(ne.files),ne.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Ju(X.dropOverlay))}else{Dt.style.display="";let X=(tp=r.attachments)!=null?tp:{};ne&&(ne.accept=((np=X.allowedTypes)!=null?np:Nr).join(","),ne.multiple=((rp=X.maxFiles)!=null?rp:4)>1),tt&&tt.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Dt&&(Dt.style.display="none"),tt&&tt.clearAttachments(),(op=ce.querySelector(".persona-attachment-drop-overlay"))==null||op.remove();let Vt=(sp=r.sendButton)!=null?sp:{},vo=(ap=Vt.useIcon)!=null?ap:!1,Zr=(ip=Vt.iconText)!=null?ip:"\u2191",ht=Vt.iconName,Pn=(lp=Vt.tooltipText)!=null?lp:"Send message",Br=(cp=Vt.showTooltip)!=null?cp:!1,Sn=(dp=Vt.size)!=null?dp:"40px",In=Vt.backgroundColor,Ht=Vt.textColor;if(vo){if(ae.style.width=Sn,ae.style.height=Sn,ae.style.minWidth=Sn,ae.style.minHeight=Sn,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Ht?ae.style.color=Ht:ae.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let X=parseFloat(Sn)||24,xt=(Ht==null?void 0:Ht.trim())||"currentColor",Nt=be(ht,X,xt,2);Nt?ae.appendChild(Nt):ae.textContent=Zr}else ae.textContent=Zr;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",In?(ae.style.backgroundColor=In,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=(up=(pp=r.copy)==null?void 0:pp.sendButtonLabel)!=null?up:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",In?(ae.style.backgroundColor=In,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Ht?ae.style.color=Ht:ae.classList.add("persona-text-white");Vt.borderWidth?(ae.style.borderWidth=Vt.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),Vt.borderColor?ae.style.borderColor=Vt.borderColor:ae.style.borderColor="",Vt.paddingX?(ae.style.paddingLeft=Vt.paddingX,ae.style.paddingRight=Vt.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),Vt.paddingY?(ae.style.paddingTop=Vt.paddingY,ae.style.paddingBottom=Vt.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let Ut=Mn==null?void 0:Mn.querySelector(".persona-send-button-tooltip");if(Br&&Pn)if(Ut)Ut.textContent=Pn,Ut.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Pn,Mn==null||Mn.insertBefore(X,ae)}else Ut&&(Ut.style.display="none");let Bt=(yp=(mp=r.layout)==null?void 0:mp.contentMaxWidth)!=null?yp:O()?(hp=(fp=(gp=r.launcher)==null?void 0:gp.composerBar)==null?void 0:fp.contentMaxWidth)!=null?hp:"720px":void 0;Bt?($e.style.maxWidth=Bt,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ot&&(Ot.style.maxWidth=Bt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Et&&(Et.style.maxWidth=Bt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let Kt=(bp=r.statusIndicator)!=null?bp:{},Wn=(xp=Kt.visible)!=null?xp:!0;if(ln.style.display=Wn?"":"none",S){let X=S.getStatus();ue(ln,(Nt=>{var ct,Tt,on,mn;return Nt==="idle"?(ct=Kt.idleText)!=null?ct:gn.idle:Nt==="connecting"?(Tt=Kt.connectingText)!=null?Tt:gn.connecting:Nt==="connected"?(on=Kt.connectedText)!=null?on:gn.connected:Nt==="error"?(mn=Kt.errorText)!=null?mn:gn.error:gn[Nt]})(X),Kt,X)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Kn=Kt.align==="left"?"persona-text-left":Kt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Kn)},open(){$()&&Rt(!0,"api")},close(){$()&&Rt(!1,"api")},toggle(){$()&&Rt(!B,"api")},clearChat(){bn=!1,S.clearMessages(),dr.clear(),zr();try{localStorage.removeItem(rs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rs}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},C.syncFromMetadata(),V==null||V.clear(),le==null||le.reset(),ve==null||ve.update()},setMessage(c){return!de||S.isStreaming()?!1:(!B&&$()&&Rt(!0,"system"),de.value=c,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(S.isStreaming())return!1;let f=(c==null?void 0:c.trim())||de.value.trim();return f?(!B&&$()&&Rt(!0,"system"),de.value="",de.style.height="auto",S.sendMessage(f),!0):!1},startVoiceRecognition(){var f,y;return S.isStreaming()?!1:((y=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:y.type)==="runtype"?(S.isVoiceActive()||(!B&&$()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,Ln(),S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("user"),S.isVoiceActive()&&_()})),!0):Vn?!0:vs()?(!B&&$()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,Ln(),ho("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?S.isVoiceActive()?(S.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Ln(),nr("user"),K()}),!0):!1:Vn?(mt.manuallyDeactivated=!0,Ln(),gr("user"),!0):!1},injectMessage(c){return!B&&$()&&Rt(!0,"system"),S.injectMessage(c)},injectAssistantMessage(c){!B&&$()&&Rt(!0,"system");let f=S.injectAssistantMessage(c);return j&&(j=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)),f},injectUserMessage(c){return!B&&$()&&Rt(!0,"system"),S.injectUserMessage(c)},injectSystemMessage(c){return!B&&$()&&Rt(!0,"system"),S.injectSystemMessage(c)},injectMessageBatch(c){return!B&&$()&&Rt(!0,"system"),S.injectMessageBatch(c)},injectComponentDirective(c){return!B&&$()&&Rt(!0,"system"),S.injectComponentDirective(c)},injectTestMessage(c){!B&&$()&&Rt(!0,"system"),S.injectTestEvent(c)},async connectStream(c,f){return S.connectStream(c,f)},__pushEventStreamEvent(c){V&&(le==null||le.processEvent(c.type,c.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ge||!V||yn()},hideEventStream(){fe&&Dn()},isEventStreamVisible(){return fe},showArtifacts(){ir(r)&&(bn=!1,jn(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){ir(r)&&(bn=!0,jn())},upsertArtifact(c){return ir(r)?(bn=!1,S.upsertArtifact(c)):null},selectArtifact(c){ir(r)&&S.selectArtifact(c)},clearArtifacts(){ir(r)&&S.clearArtifacts()},getArtifacts(){var c;return(c=S==null?void 0:S.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=S==null?void 0:S.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!B&&!O()||!de?!1:(de.focus(),!0)},async resolveApproval(c,f){let b=S.getMessages().find(M=>{var D;return M.variant==="approval"&&((D=M.approval)==null?void 0:D.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){S.resolveWebMcpApproval(b.id,f);return}return S.resolveApproval(b.approval,f)},getMessages(){return S.getMessages()},getStatus(){return S.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,f){return o.on(c,f)},off(c,f){o.off(c,f)},isOpen(){return $()&&B},isVoiceActive(){return mt.active},getState(){return{open:$()&&B,launcherEnabled:T,voiceActive:mt.active,streaming:S.isStreaming()}},showCSATFeedback(c){!B&&$()&&Rt(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let y=dl({onSubmit:async(b,M)=>{var D;S.isClientTokenMode()&&await S.submitCSATFeedback(b,M),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!B&&$()&&Rt(!0,"system");let f=$e.querySelector(".persona-feedback-container");f&&f.remove();let y=pl({onSubmit:async(b,M)=>{var D;S.isClientTokenMode()&&await S.submitNPSFeedback(b,M),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return S.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return S.submitNPSFeedback(c,f)},destroy(){Cr!=null&&(clearInterval(Cr),Cr=null),gt.forEach(c=>c()),ie.remove(),Qe==null||Qe.remove(),Ee==null||Ee.destroy(),Je==null||Je.remove(),qn&&Ue.removeEventListener("click",qn)}};if((((bc=n==null?void 0:n.debugTools)!=null?bc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:y=>y?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=f,gt.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",f),gt.push(()=>{window.removeEventListener("persona:focusInput",f)}),ge){let U=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.showEventStream()},R=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",R),gt.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",R)})}let y=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&en.showArtifacts()},b=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&en.hideArtifacts()},M=U=>{let R=U.detail;R!=null&&R.instanceId&&R.instanceId!==c||R!=null&&R.artifact&&en.upsertArtifact(R.artifact)},D=U=>{let R=U.detail;R!=null&&R.instanceId&&R.instanceId!==c||typeof(R==null?void 0:R.id)=="string"&&en.selectArtifact(R.id)},F=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",F),gt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",F)})}let or=Mb(r.persistState);if(or&&$()){let c=kb(or.storage),f=`${or.keyPrefix}widget-open`,y=`${or.keyPrefix}widget-voice`,b=`${or.keyPrefix}widget-voice-mode`;if(c){let M=((xc=or.persist)==null?void 0:xc.openState)&&c.getItem(f)==="true",D=((vc=or.persist)==null?void 0:vc.voiceState)&&c.getItem(y)==="true",F=((wc=or.persist)==null?void 0:wc.voiceState)&&c.getItem(b)==="true";if(M&&setTimeout(()=>{en.open(),setTimeout(()=>{var U;if(D||F)en.startVoiceRecognition();else if((U=or.persist)!=null&&U.focusInput){let R=e.querySelector("textarea");R&&R.focus()}},100)},0),(Cc=or.persist)!=null&&Cc.openState&&(o.on("widget:opened",()=>{c.setItem(f,"true")}),o.on("widget:closed",()=>{c.setItem(f,"false")})),(Ac=or.persist)!=null&&Ac.voiceState&&(o.on("voice:state",U=>{c.setItem(y,U.active?"true":"false")}),o.on("user:message",U=>{c.setItem(b,U.viaVoice?"true":"false")})),or.clearOnChatClear){let U=()=>{c.removeItem(f),c.removeItem(y),c.removeItem(b)},R=()=>U();window.addEventListener("persona:clear-chat",R),gt.push(()=>{window.removeEventListener("persona:clear-chat",R)})}}}return p&&$()&&setTimeout(()=>{en.open()},0),Rr(),en};var Lb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Gu=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},yl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Xu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",yl(e)},gl=e=>{e.style.transition=""},fl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},hl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},mi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Pb=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Ib=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Qu=(e,t,n,r,s,o,a)=>{var v,x,C,T,H,L;let i=yr(o),d=i.reveal==="push";Pb(e,t,n,r,d),Ib(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,m=(T=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileBreakpoint)!=null?T:640,g=l!=null?l.innerWidth<=m:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),fl(t),gl(r),Xu(r),hl(n),mi(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((L=(H=o==null?void 0:o.launcher)==null?void 0:H.zIndex)!=null?L:fn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Xu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",fl(t),gl(r),hl(n),mi(s,r);let P=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":W;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=P,r.style.transform=w,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",gl(r),yl(r),mi(s,r);let P=Lb(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",I=i.side==="right"?a?`translateX(-${P}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${P}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${W+P}px`,t.style.transition=w,t.style.transform=I,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",fl(t),yl(r),hl(n),mi(s,r);let P=i.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${W}`,r.style.width=W,r.style.maxWidth=W,r.style.minWidth=W,r.style.minHeight="0",r.style.position="relative",r.style.overflow=P||I?"hidden":"visible",r.style.transition=w,P&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Wb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Gu(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Gu(n,r)},destroy(){n.remove()}}},Rb=(e,t)=>{var H,L,P,W;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),m=(L=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)==null||L?(W=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),yr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Qu(a,i,d,l,p,t,m)}),g.observe(a))},x=()=>{Qu(a,i,d,l,p,t,m),v()},C=a.ownerDocument.defaultView,T=()=>{x()};return C==null||C.addEventListener("resize",T),yr(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:p,shell:a,syncWidgetState(w){let I=w.launcherEnabled?w.open:!0;m!==I&&(m=I,x())},updateConfig(w){var I,O;t=w,((O=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)!=null?O:!0)===!1&&(m=!0),x()},destroy(){C==null||C.removeEventListener("resize",T),u(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},gi=(e,t)=>an(t)?Rb(e,t):Wb(e,t);var bl={},Yu=!1,Hb=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Bb=()=>{try{if(typeof bl!="undefined"&&bl.url)return new URL("../widget.css",bl.url).href}catch{}return null},Zu=(e,t)=>{let n=Bb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},em=e=>{let t=Hb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=gi(t,s),a,i=[],d=(C,T)=>{var W,w;let L=!((w=(W=T==null?void 0:T.launcher)==null?void 0:W.enabled)!=null?w:!0)||an(T),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),L&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let I=C.attachShadow({mode:"open"});I.appendChild(P),Zu(I,r)}else C.appendChild(P),Zu(C,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let C=d(o.host,s);a=ml(C,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(C=>C()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(Yu||(Yu=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let u=C=>{g(),o.destroy(),o=gi(t,C),s=C,m()},v={update(C){var w,I,O,$,B,j;let T={...s,...C,launcher:{...(w=s==null?void 0:s.launcher)!=null?w:{},...(I=C==null?void 0:C.launcher)!=null?I:{},dock:{...($=(O=s==null?void 0:s.launcher)==null?void 0:O.dock)!=null?$:{},...(j=(B=C==null?void 0:C.launcher)==null?void 0:B.dock)!=null?j:{}}}},H=an(s),L=an(T),P=no(s),W=no(T);if(H!==L||P!==W){u(T);return}s=T,o.updateConfig(s),a.update(C),l()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(C,T,H){if(T==="host")return o.host;if(T in C)return Reflect.get(C,T,H);let L=a[T];return typeof L=="function"?L.bind(a):L}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var sm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Db=new Set(["button","a","input","select","textarea","details","summary"]),Nb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),xl=/\b(product|card|item|listing|result)\b/i,wl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Fb=3e3,Ob=100;function am(e){let t=typeof e.className=="string"?e.className:"";if(xl.test(t)||e.id&&xl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&xl.test(r.value))return!0}return!1}function im(e){var t;return wl.test(((t=e.textContent)!=null?t:"").trim())}function lm(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function $b(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function tm(e){let t=e.match(wl);return t?t[0]:null}function nm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function _b(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var jb="commerce-card",Ub="result-card";function rm(e){return!am(e)||!im(e)||!lm(e)&&!$b(e)?0:5200}function om(e){var r;return!am(e)||im(e)||!lm(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var cm=[{id:jb,scoreElement(e){return rm(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||wl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(rm(e)===0)return null;let{title:n,href:r}=nm(e),s=(p=(l=tm(((d=e.textContent)!=null?d:"").trim()))!=null?l:tm(t.text))!=null?p:"",o=_b(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
108
|
-
`)}},{id:
|
|
109
|
-
`)}}];function
|
|
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:zb,scoreElement(e){return am(e)},formatSummary(e,t){if(am(e)===0)return null;let{title:n,href:r}=om(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
109
|
+
`)}}];function Vb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Kb(e){var p,m,g,u,v,x,C,T,H,k,P,W,A;let t=(p=e.options)!=null?p:{},n=(g=(m=t.maxElements)!=null?m:e.maxElements)!=null?g:80,r=(v=(u=t.excludeSelector)!=null?u:e.excludeSelector)!=null?v:".persona-host",s=(C=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?C:200,o=(H=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?H:!0,a=(k=t.root)!=null?k:e.root,i=(P=t.mode)!=null?P:"structured",d=(W=t.maxCandidates)!=null?W:Math.max(500,n*10),l=(A=e.rules)!=null?A:pm;return i==="simple"&&e.rules&&e.rules.length>0?(Vb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function Cl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Jb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Gb(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Fb.has(t)||n&&Ob.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function um(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Xb(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function mm(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Cl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Jb){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${Cl(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>Cl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function Qb(e){return e==="static"?_b:$b}function gm(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:mm(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Gb(e),attributes:Xb(e)}}function Yb(e,t,n,r){let s=Qb(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Zb(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function ex(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(im.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!um(l)){i=a.nextNode();continue}let m=gm(l,e.maxTextLength),g=m.text.length>0,u=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(C=>C==="role");if(!g&&!u){i=a.nextNode();continue}if(r.has(m.selector)){i=a.nextNode();continue}r.add(m.selector);let{score:v,formattingRule:x}=Yb(l,m,e.rules,n);s.push({el:l,domIndex:o,enriched:m,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;Zb(d,l)||d.push(l)}return d.sort((l,p)=>{let m=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:m===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var g;let p;if((g=l.formattingRule)!=null&&g.formatSummary){let u=l.formattingRule.formatSummary(l.el,l.enriched,n);u&&(p=u)}let m={...l.enriched};return p&&(m.formattedSummary=p),m})}function tx(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(im.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!um(d)){o=s.nextNode();continue}let p=gm(d,e.maxTextLength),m=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(u=>u==="role");if(!m&&!g){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function nx(e={}){var r;let t=Kb(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?tx(t,n):ex(t,n):[]}var hi=100;function rx(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
|
|
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,hi)}" (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,hi)}" (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,hi)}" (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,hi)}"`);r.push(`Content:
|
|
120
120
|
${a.join(`
|
|
121
121
|
`)}`)}return r.join(`
|
|
122
122
|
|
|
123
|
-
`)}var
|
|
123
|
+
`)}var fm={name:"@runtypelabs/persona",version:"3.29.1",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./codegen":{types:"./dist/codegen.d.ts",import:"./dist/codegen.js",require:"./dist/codegen.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:launcher && pnpm run build:theme-ref && pnpm run build:codegen && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:codegen":"tsup src/codegen.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var ss=fm.version;function sx(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function ax(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function ix(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Tr(e.colors.primary,.95),100:Tr(e.colors.primary,.9),200:Tr(e.colors.primary,.8),300:Tr(e.colors.primary,.7),400:Tr(e.colors.primary,.6),500:e.colors.primary,600:Tr(e.colors.primary,.8),700:Tr(e.colors.primary,.7),800:Tr(e.colors.primary,.6),900:Tr(e.colors.primary,.5),950:Tr(e.colors.primary,.45)}}),{...t,palette:n}}}}function lx(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function cx(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Tr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function dx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var px={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},hm={components:{panel:{borderRadius:"0",shadow:"none"}}},ym={id:"shop",label:"Shopping Assistant",config:{theme:px,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:sr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},bm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:hm}},xm={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:hm}},vm={shop:ym,minimal:bm,fullscreen:xm};function ux(e){return vm[e]}var mx=nm;function Fr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function gx(e){if(e)return{getHeaders:Fr(e.getHeaders),onFeedback:Fr(e.onFeedback),onCopy:Fr(e.onCopy),requestMiddleware:Fr(e.requestMiddleware),actionHandlers:Fr(e.actionHandlers),actionParsers:Fr(e.actionParsers),postprocessMessage:Fr(e.postprocessMessage),contextProviders:Fr(e.contextProviders),streamParser:Fr(e.streamParser)}}var Cm=`({ text, message }: any) => {
|
|
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
|
+
}`,wm=`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
|
+
}`,Am=`(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
|
+
}`,Sm=`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
|
+
}`,fx=`(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
|
+
}`,hx=`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 xx(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ys(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(r,"theme",e.theme," "),e.launcher&&co(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...yi(e," ")),r.push(...bi(e," ",n)),r.push(...xi(e," ")),r.push(...vi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${mx}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${xm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${xm}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${wm}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${wm}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
198
|
-
`)}function
|
|
199
|
-
`)}function
|
|
195
|
+
}`;function yx(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function yi(e){var t,n;return(n=(t=e.parserType)!=null?t:yx(e.streamParser))!=null?n:"plain"}function bi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function xi(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function vi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Ci(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Al(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Tm(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),Tm(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function co(e,t,n,r){n&&(e.push(`${r}${t}: {`),Tm(e,n,`${r} `),e.push(`${r}},`))}function ea(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function bx(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:gx(n.hooks)}:void 0;return t==="esm"?xx(r,s):t==="script-installer"?wx(r,s):t==="script-advanced"?Sx(r,s):t==="react-component"?vx(r,s):t==="react-advanced"?Cx(r,s):Ax(r,s)}function xx(e,t){let n=t==null?void 0:t.hooks,r=yi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ea(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(o,"theme",e.theme," "),e.launcher&&co(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...bi(e," ")),o.push(...xi(e," ",n)),o.push(...vi(e," ")),o.push(...Ci(e," ")),o.push(...Al(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
|
|
196
|
+
`)}function vx(e,t){let n=t==null?void 0:t.hooks,r=yi(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${ea(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(o,"theme",e.theme," "),e.launcher&&co(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...bi(e," ")),o.push(...xi(e," ",n)),o.push(...vi(e," ")),o.push(...Ci(e," ")),o.push(...Al(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
|
|
197
|
+
`)}function Cx(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${ea(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(r,"theme",e.theme," "),e.launcher&&co(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...bi(e," ")),r.push(...xi(e," ",n)),r.push(...vi(e," ")),r.push(...Ci(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${fx}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Cm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Cm}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Am}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Am}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
198
|
+
`)}function Em(e){var s;let t=yi(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([p,m])=>{p!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(l[p]=m)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function wx(e,t){let n=Em(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ss}/dist/install.global.js" data-config='${o}'></script>`}function Ax(e,t){let n=t==null?void 0:t.hooks,r=yi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ss}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ss}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${ea(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&co(o,"theme",e.theme," "),e.launcher&&co(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...bi(e," ")),o.push(...xi(e," ",n)),o.push(...vi(e," ")),o.push(...Ci(e," ")),o.push(...Al(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
|
|
199
|
+
`)}function Sx(e,t){let n=t==null?void 0:t.hooks,r=Em(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
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@${ss}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${hx});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${wm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${wm}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Sm}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Sm}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${ea(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
|
|
202
|
+
`)}var Mm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},km=.1,Lm=.15,Pm=1.5,Sl=24,Im=40,Tx=`
|
|
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: ${Sl}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 Ex(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Tx,document.head.appendChild(e)}function Mx(e,t){let n=e.clientWidth-Sl*2-Im,r=e.clientHeight-Sl*2-Im;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function kx(e,t,n,r,s){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function Lx(e,t){let{items:n,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Ex();let p=Math.max(0,Math.min(r,n.length-1)),m=s,g=o,u=null,v=1,x=!1,C=h("div","persona-dc-root"),T=h("div","persona-dc-toolbar"),H=h("div","persona-dc-toolbar-lead"),k=h("div","persona-dc-toolbar-trail"),P=qt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ce(-1)}),W=h("div");W.style.position="relative";let A=h("button","persona-dc-title-btn");A.type="button",A.setAttribute("aria-expanded","false"),A.setAttribute("aria-haspopup","listbox");let I=h("span","persona-dc-title-text"),O=h("span","persona-dc-title-chevron"),D=be("chevron-down",12,"currentColor",2);D&&O.appendChild(D),A.append(I,O);let R=h("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let _=!1;function z(){R.innerHTML="";for(let ue=0;ue<n.length;ue++){let ie=n[ue],re=h("button","persona-dc-dropdown-item");re.type="button",re.setAttribute("role","option"),re.setAttribute("aria-current",ue===p?"true":"false");let Qe=h("span");if(Qe.textContent=ie.title,re.appendChild(Qe),ie.description){let Ie=h("span","persona-dc-dropdown-desc");Ie.textContent=ie.description,re.appendChild(Ie)}re.addEventListener("click",()=>{Re(),Ve(ue)}),R.appendChild(re)}}function oe(){_=!_,R.style.display=_?"":"none",A.setAttribute("aria-expanded",_?"true":"false"),_&&z()}function Re(){_&&(_=!1,R.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",ue=>{ue.stopPropagation(),oe()});let Ue=()=>Re();document.addEventListener("click",Ue),W.append(A,R);let Fe=qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ce(1)}),ge=h("span","persona-dc-counter");H.append(P,W,Fe,ge);let ye=null;i&&(ye=Qa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:ue=>{m=ue,V.dataset.device=m,u=null,X()}}),k.appendChild(ye.element));let Le=null;if(a){let ue=h("div","persona-dc-zoom-controls"),ie=qt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ie=u!=null?u:v;u=Math.max(Lm,Ie-km),X()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{u=1,X()});let re=qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ie=u!=null?u:v;u=Math.min(Pm,Ie+km),X()}}),Qe=qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{u=null,X()}});ue.append(ie,Le,re,Qe),k.appendChild(ue)}if(d){let ue=h("div","persona-dc-separator");k.appendChild(ue);let ie=Qa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:re=>{g=re,V.dataset.colorScheme=g,ve()}});k.appendChild(ie.element)}let Be=h("div","persona-dc-separator");k.appendChild(Be);let ee=qt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(ee),T.append(H,k);let Pe=h("div","persona-dc-stage"),V=h("div","persona-dc-iframe-wrapper");V.dataset.device=m,V.dataset.colorScheme=g;let le=h("iframe","persona-dc-iframe");le.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),le.setAttribute("loading","lazy"),le.title=n[p].title,V.appendChild(le),Pe.appendChild(V),C.append(T,Pe),e.appendChild(C);function ve(){var ue;try{let ie=(ue=le.contentDocument)==null?void 0:ue.body;if(!ie)return;g==="dark"?ie.classList.add("theme-dark"):ie.classList.remove("theme-dark")}catch{}}le.addEventListener("load",()=>ve());function fe(){let ue=n[p];I.textContent=ue.title,ge.textContent=`${p+1} / ${n.length}`,le.title=ue.title}function Ce(ue){let ie=((p+ue)%n.length+n.length)%n.length;Ve(ie)}function Ve(ue){ue<0||ue>=n.length||(p=ue,le.src=n[p].url,fe(),l==null||l(p,n[p]))}function X(){var re;if(x)return;let ue=(re=Mm[m])!=null?re:Mm.desktop;v=Mx(Pe,ue);let ie=Math.max(Lm,Math.min(Pm,u!=null?u:v));kx(V,le,ue,ie,m),Le&&(Le.textContent=`${Math.round(ie*100)}%`)}let te=new ResizeObserver(()=>X());te.observe(Pe),fe(),le.src=n[p].url,requestAnimationFrame(()=>X());function se(){x||(x=!0,te.disconnect(),document.removeEventListener("click",Ue),C.remove())}return{element:C,goTo:Ve,next:()=>Ce(1),prev:()=>Ce(-1),getIndex:()=>p,setDevice(ue){m=ue,V.dataset.device=ue,ye==null||ye.setSelected(ue),u=null,X()},setColorScheme(ue){g=ue,V.dataset.colorScheme=ue},setZoom(ue){u=ue,X()},destroy:se}}export{xu as ASK_USER_QUESTION_TOOL_NAME,zo as AgentWidgetClient,Rs as AgentWidgetSession,Jo as AttachmentManager,zp as DEFAULT_COMPONENTS,Ii as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,Up as DEFAULT_PALETTE,qp as DEFAULT_SEMANTIC,Ft as DEFAULT_WIDGET_CONFIG,vm as PRESETS,xm as PRESET_FULLSCREEN,bm as PRESET_MINIMAL,ym as PRESET_SHOP,Sh as THEME_ZONES,ss as VERSION,Sa as WEBMCP_TOOL_PREFIX,Ms as WebMcpBridge,sx as accessibilityPlugin,ax as animationsPlugin,Mo as applyThemeVariables,Xo as attachHeaderToContainer,ix as brandPlugin,Ks as buildComposer,su as buildDefaultHeader,ro as buildHeader,Vs as buildHeaderWithLayout,au as buildMinimalHeader,nx as collectEnrichedPageContext,lo as componentRegistry,ui as createActionManager,gl as createAgentExperience,Ny as createAskUserQuestionBubble,Pi as createBestAvailableVoiceProvider,ay as createBubbleWithLayout,pl as createCSATFeedback,_i as createComboButton,Sb as createComponentMiddleware,il as createComponentStreamParser,Tp as createDefaultSanitizer,Lx as createDemoCarousel,Bm as createDirectivePostprocessor,ko as createDropdownMenu,Qm as createFlexibleJsonStreamParser,qt as createIconButton,ig as createImagePart,Mi as createJsonStreamParser,Xa as createLabelButton,al as createLocalStorageAdapter,wa as createMarkdownProcessor,jo as createMarkdownProcessorFromConfig,fu as createMessageActions,ul as createNPSFeedback,Ti as createPlainTextParser,dx as createPlugin,Ei as createRegexJsonParser,Js as createStandardBubble,Wa as createTextPart,Bs as createTheme,Bi as createThemeObserver,Qa as createToggleGroup,Qo as createTypingIndicator,Ko as createVoiceProvider,fi as createWidgetHostLayout,ki as createXmlParser,mx as default,rs as defaultActionHandlers,pi as defaultJsonActionParser,pm as defaultParseRules,Fa as detectColorScheme,Dm as directivePostprocessor,Xs as ensureAskUserQuestionSheet,Uo as escapeHtml,dl as extractComponentDirectiveFromMessage,lg as fileToImagePart,rx as formatEnrichedContext,Vo as generateAssistantMessageId,bx as generateCodeSnippet,ng as generateMessageId,mm as generateStableSelector,Ps as generateUserMessageId,Ds as getActiveTheme,Gp as getColorScheme,og as getDisplayText,iu as getHeaderLayout,ag as getImageParts,ux as getPreset,cl as hasComponentDirective,sg as hasImages,ji as headerLayouts,cx as highContrastPlugin,nm as initAgentWidget,oo as isAskUserQuestionMessage,Ab as isComponentDirectiveType,an as isDockedMountMode,Da as isVoiceSupported,So as isWebMcpToolName,Hh as listRegisteredStreamAnimations,wp as markdownPostprocessor,Wi as mergeWithDefaults,rg as normalizeContent,so as parseAskUserQuestionPayload,di as pluginRegistry,lx as reducedMotionPlugin,Wh as registerStreamAnimationPlugin,Po as removeAskUserQuestionSheet,ll as renderComponentDirective,gu as renderLoadingIndicatorWithFallback,be as renderLucideIcon,yr as resolveDockConfig,Es as resolveSanitizer,Ri as resolveTokens,kp as stripWebMcpPrefix,Hi as themeToCssVariables,Rh as unregisterStreamAnimationPlugin,cg as validateImageFile,Vp as validateTheme};
|
|
444
444
|
//# sourceMappingURL=index.js.map
|