@runtypelabs/persona 3.26.0 → 3.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -13
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-BZVr1YOV.d.cts → types-CxvHw0X6.d.cts} +551 -1
- package/dist/animations/{types-BZVr1YOV.d.ts → types-CxvHw0X6.d.ts} +551 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/index.cjs +35 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1230 -3
- package/dist/index.d.ts +1230 -3
- package/dist/index.global.js +34 -34
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +31 -31
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +133 -0
- package/dist/launcher.global.js.map +1 -0
- package/dist/smart-dom-reader.d.cts +551 -1
- package/dist/smart-dom-reader.d.ts +551 -1
- package/dist/theme-editor.d.cts +551 -1
- package/dist/theme-editor.d.ts +551 -1
- package/package.json +8 -4
- package/src/client.test.ts +9 -9
- package/src/generated/runtype-openapi-contract.ts +1249 -0
- package/src/index-core.ts +19 -0
- package/src/install.test.ts +442 -0
- package/src/install.ts +283 -49
- package/src/launcher-global.ts +115 -0
- package/src/runtime/init.test.ts +71 -0
- package/src/runtime/init.ts +17 -1
- package/src/types.ts +14 -8
package/dist/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{Marked as
|
|
1
|
+
import{Marked as Lm}from"marked";var Pm=e=>{if(e)return e},xa=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new Lm({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=Pm(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},$o=e=>e?xa({markedOptions:e.options,renderer:e.renderer}):xa(),Im=xa(),vp=e=>Im(e),jo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),wp=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),xp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Cp=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=xp(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=xp(n.length);return n.push({token:o,type:s}),o}),t},Wm=e=>{let n=$o(e);return t=>{let r=[],s=Cp(t,r),o=n(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="${wp(i)}"></div>`;o=o.replace(d,p)}),o}},Rm=e=>{let n=[],t=Cp(e,n),r=vp(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${wp(o)}"></div>`;r=r.replace(a,d)}),r};import Hm from"dompurify";var Bm={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"]},Dm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ap=()=>{let e=Hm(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!Dm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,Bm)},Ts=e=>e===!1?null:typeof e=="function"?e:Ap();var wa="webmcp:",va={warn(e,...n){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...n)}};function Tp(e){if(e.length===0)return"0:empty";let n=e.map(t=>{var r,s;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(s=t.origin)!=null?s:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${e.length}:${Nm(n.join(""))}`}function Sp(e,n){let t=3735928559^n,r=1103547991^n;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);t=Math.imul(t^o,2654435761),r=Math.imul(r^o,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Nm(e){let n=Sp(e,0).toString(36),t=Sp(e,2654435761).toString(36);return`${n}.${t}`}var Es=class{constructor(n){this.config=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=n.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(n){this.confirmHandler=n}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let n=this.getModelContext();if(!n)return[];let t;try{t=await n.getTools()}catch(s){return va.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return t.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Om(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(n,t,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=Ep(n),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:t,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,Um(t),{signal:l.signal});return _m(u)}catch(u){if(p)return hr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let v=u instanceof Error?u.message:String(u);return hr(v)}finally{clearTimeout(m),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(n){va.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",n),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let n=document.modelContext;if(!n||typeof n!="object")return null;let t=n;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,va.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):n}async requestConfirm(n){var r;let t=(r=this.confirmHandler)!=null?r:$m;try{return await t(n)}catch(s){return va.warn(`Confirm handler threw for WebMCP tool '${n.toolName}'; declining.`,s),!1}}passesClientAllowlist(n){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>Fm(n,r))}},Ep=e=>e.startsWith(wa)?e.slice(wa.length):e,Ca=e=>e.startsWith(wa),Fm=(e,n)=>{if(n==="*")return!0;let t=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)},Om=e=>{if(!(e===void 0||e===""))try{let n=JSON.parse(e);return n!==null&&typeof n=="object"?n:void 0}catch{return}},_m=e=>{if(e==null)return{content:[{type:"text",text:""}]};let n;try{n=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return n!==null&&typeof n=="object"&&Array.isArray(n.content)?n:{content:[{type:"text",text:typeof n=="string"?n:qm(n)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),$m=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let n=jm(e.args),t=`Allow the AI to call ${e.toolName}`+(n?`
|
|
2
2
|
|
|
3
3
|
Arguments:
|
|
4
4
|
${n}`:"")+(e.description?`
|
|
5
5
|
|
|
6
|
-
${e.description}`:"");return window.confirm(t)}
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Uo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},
|
|
6
|
+
${e.description}`:"");return window.confirm(t)},jm=e=>{if(e==null)return"";try{let n=JSON.stringify(e,null,2);return n.length>500?n.slice(0,500)+"\u2026":n}catch{return String(e)}},Um=e=>{if(e===void 0)return"{}";try{let n=JSON.stringify(e);return n===void 0?"{}":n}catch{return"{}"}},qm=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Mp,STR as kp,OBJ as Lp}from"partial-json";var Aa=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Uo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},zm=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Pp=e=>e.status==="complete"?zm(e):e.status==="pending"?"Waiting":"",Vm=e=>{var s,o,a;let t=(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 t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Ip=e=>e.status==="complete"?Vm(e):"Using tool...",Sa=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},ks=e=>{var t,r,s;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Sa(n)},Ta=e=>{var t,r,s;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Sa(n)},Ci=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=ks(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ea=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Ms(r,t.slice(o,a.index),[]),a[1]!==void 0?Ms(r,a[1],["bold"]):a[2]!==void 0?Ms(r,a[2],["italic"]):a[3]!==void 0&&Ms(r,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Ms(r,t.slice(o),[]),r},Ms=(e,n,t)=>{let r=n.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:t}),s<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},Km=()=>{let e=null,n=0,t=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<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},So=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ai=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Si=()=>{var n;let e=Vm();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Ti=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=Mp(t,kp|Lp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Aa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Aa(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Km=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Aa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Aa(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:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=Mp(o,kp|Lp),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},Ei=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Ma=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);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 ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.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 n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Jm="https://api.runtype.com/v1/dispatch",ka="https://api.runtype.com";function Gm(e){var o,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let s=n.indexOf("/");if(s>0){let i=(a=(o=n.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 Mi=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 Xm(e){switch(e){case"json":return Ti;case"regex-json":return Si;case"xml":return Ei;default:return Ai}}var Wp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Qm(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=Wp(t);if(!Wp(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=So(e);return So(n)!==null&&a===null?n:e}var qo=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,s,o;this.apiUrl=(t=n.apiUrl)!=null?t:Jm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Xm(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders,this.webMcpBridge=((o=n.webmcp)==null?void 0:o.enabled)===!0?new Es(n.webmcp):null}setSSEEventCallback(n){this.onSSEEvent=n}setWebMcpConfirmHandler(n){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(n)}isWebMcpOperational(){var n;return((n=this.webMcpBridge)==null?void 0:n.isOperational())===!0}executeWebMcpToolCall(n,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(n,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ka}/v1/client/${n}`}getClientSession(){return this.clientSession}async initSession(){var n,t;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(),(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});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 t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ka}/v1/client/feedback`}async sendFeedback(n){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(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});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(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){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:n,comment:t})}async submitNPSFeedback(n,t){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:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({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 W=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:W}),W}let l=await this.buildPayload(n.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([W])=>W!=="sessionId"&&W!=="session_id")):void 0,m={sessionId:d.sessionId,messages:n.messages.filter(Mi).map(W=>{var L,w,I;return{id:W.id,role:W.role,content:(I=(w=(L=W.contentParts)!=null?L:W.llmContent)!=null?w:W.rawContent)!=null?I:W.content}}),...n.assistantMessageId&&{assistantMessageId:n.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?Tp(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,T=u&&x&&this.lastSentClientToolsFingerprint===v,A=!1,R=null,P;for(let W=0;;W++){let w={...m,...u&&(A||!T)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:r.signal}),P.status===409&&W===0&&u){let I=await P.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){A=!0,this.lastSentClientToolsFingerprint=null;continue}R=I!=null?I:{error:"Chat request failed"}}break}if(!P.ok){let W=R!=null?R:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:w}),w}if(P.status===429){let w=new Error(W.hint||"Message limit reached for this session.");throw t({type:"error",error:w}),w}let L=new Error(W.error||"Failed to send message");throw t({type:"error",error:L}),L}if(!P.body){let W=new Error("No response body received");throw t({type:"error",error:W}),W}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(P.body,t,n.assistantMessageId)}finally{t({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")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ka}/v1/agents/${n.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:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ka}/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:n,toolOutputs:t,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(n){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Mi).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:t,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:n,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(n){var o;let r={messages:n.slice().filter(Mi).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:n,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(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);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,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var ln,Hn,Xn,Ue;let s=n.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)&&t({type:"message",message:p(N)})},u=null,v=null,x={current:null},T={current:null},A=!1,R=new Map,P=new Map,W=new Map,L=new Map,w={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},F=(N,Ae,Be="")=>`${N}::${Ae}::${Be}`,_=(N,Ae)=>`${N}::${Ae}::`,B=(N,Ae,Be,De)=>{let $e=F(N,Ae,Be),dt=W.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 W.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&&T.current?N=`${We}_${T.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)},be=(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=R.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 R.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=P.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 P.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=Qm(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 Ma((N,Ae)=>{ce.push({payloadType:N,payload:Ae}),Et()}),ae=null,Mn=new Map,Ft=(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,bt,zt,tt,Bn,Qn,bn,Dn,ut,xr,Nn,po,kn,Io,Fr,Er,yt,On,Fn,yn,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,Ys,as,Zs,Wo,mt,is,nr,Ln,ea,ta,Ro,Ir,na,mo,ls,Wr,cs,zr,Vr,ra,oa,vi,go,Kr,sa,ds,Jr,aa,ps,Gr,us,ia,Rr,la,Xr,Rt,Ho,Bo,ms,Cr,ca,gs,fs,da,Do,No,fo,pa,ua,hs,bs,ys,xs,vn,Vn,Hr,ot,vs,ho,gr,ma;for(let Qr=0;Qr<ce.length;Qr++){let Ve=ce[Qr].payloadType,C=ce[Qr].payload;if(Ve==="reason_start"){let $=(N=be(C,!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=C.startedAt)!=null?Be:C.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=be(C,!1))!=null?$e:be(C,!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=C.startedAt)!=null?At:C.timestamp);let Y=(Ye=(_t=(q=C.reasoningText)!=null?q:C.text)!=null?_t:C.delta)!=null?Ye:"";if(Y&&C.hidden!==!0){let K=typeof C.sequenceIndex=="number"?C.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=C.done?"complete":"streaming",C.done){k.reasoning.completedAt=ze((Dt=C.completedAt)!=null?Dt:C.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=be(C,!1))!=null?vt:be(C,!0))!=null?jt:`reason-${l()}`,k=R.get($);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=ze((Zt=C.completedAt)!=null?Zt:C.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(C);Y&&w.byStep.delete(Y)}else if(Ve==="tool_start"){let $=(wt=fe(C,!0))!=null?wt:`tool-${l()}`,k=(ft=C.toolName)!=null?ft:C.name;if(ve(k)){ee.add($);continue}let Y=we($),K=(bt=Y.toolCall)!=null?bt:{id:$,status:"pending"};K.name=k!=null?k:K.name,K.status="running",C.args!==void 0?K.args=C.args:C.parameters!==void 0&&(K.args=C.parameters),K.startedAt=(tt=K.startedAt)!=null?tt:ze((zt=C.startedAt)!=null?zt:C.timestamp),K.completedAt=void 0,K.durationMs=void 0,Y.toolCall=K,Y.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(Y.agentMetadata={executionId:(Bn=J==null?void 0:J.executionId)!=null?Bn:C.executionId,iteration:(Qn=J==null?void 0:J.iteration)!=null?Qn:C.iteration}),g(Y)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let $=(Dn=(bn=fe(C,!1))!=null?bn:fe(C,!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=C.startedAt)!=null?xr:C.timestamp);let K=(Io=(kn=(po=C.text)!=null?po:C.delta)!=null?kn:C.message)!=null?Io:"";K&&(Y.chunks=(Fr=Y.chunks)!=null?Fr:[],Y.chunks.push(String(K))),Y.status="running",k.toolCall=Y,k.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(k.agentMetadata=(On=k.agentMetadata)!=null?On:{executionId:(Er=J==null?void 0:J.executionId)!=null?Er:C.executionId,iteration:(yt=J==null?void 0:J.iteration)!=null?yt:C.iteration}),g(k)}else if(Ve==="tool_complete"){let $=(yn=(Fn=fe(C,!1))!=null?Fn:fe(C,!0))!=null?yn:`tool-${l()}`;if(ee.has($)){ee.delete($);continue}let k=we($),Y=(Lt=k.toolCall)!=null?Lt:{id:$,status:"running"};Y.status="complete",C.result!==void 0&&(Y.result=C.result),typeof C.duration=="number"&&(Y.duration=C.duration),Y.completedAt=ze((Yn=C.completedAt)!=null?Yn:C.timestamp);let K=(Zn=C.duration)!=null?Zn:C.executionTime;if(typeof K=="number")Y.durationMs=K;else{let Fe=(_n=Y.startedAt)!=null?_n:Date.now();Y.durationMs=Math.max(0,((_r=Y.completedAt)!=null?_r:Date.now())-Fe)}k.toolCall=Y,k.streaming=!1;let J=C.agentContext;(J||C.executionId)&&(k.agentMetadata=($n=k.agentMetadata)!=null?$n:{executionId:(Mr=J==null?void 0:J.executionId)!=null?Mr:C.executionId,iteration:($r=J==null?void 0:J.iteration)!=null?$r:C.iteration}),g(k);let Xe=oe(C);Xe&&I.byCall.delete(Xe)}else if(Ve==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,k=(Wt=$!=null?$:C.toolId)!=null?Wt:`local-${l()}`,Y=we(k),K=(xn=Y.toolCall)!=null?xn:{id:k,status:"pending"};K.name=C.toolName,K.args=C.parameters,K.status="complete",K.chunks=(er=K.chunks)!=null?er:[],K.startedAt=(kr=K.startedAt)!=null?kr:ze((jr=C.startedAt)!=null?jr:C.timestamp),K.completedAt=(Ur=K.completedAt)!=null?Ur:K.startedAt,Y.toolCall=K,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(jn=C.executionId)!=null?jn:(vr=Y.agentMetadata)==null?void 0:vr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},g(Y)}else if(Ve==="text_start"){if((lr=C.toolContext)!=null&&lr.toolId)continue;let $=C.partId;if($!==void 0&&T.current!==null&&$!==T.current){let k=u;k&&(k.streaming=!1,g(k),re=k,u=null,A=!0)}$!==void 0&&(T.current=$)}else if(Ve==="text_end"){if((gt=C.toolContext)!=null&>.toolId)continue;let $=u;$&&($.streaming=!1,g($),re=$,u=null,A=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Fe=String((Gt=(Jt=C.id)!=null?Jt:Y.stepId)!=null?Gt:`step-${l()}`),et=C.partId!==void 0&&C.partId!==null?String(C.partId):"",Ee=`${Y.toolId}::${Fe}`,Je=L.get(Ee);if(et!==""&&Je!==void 0&&Je!==""&&Je!==et){let Ct=W.get(F(Y.toolId,Fe,Je));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,g(Ct))}et!==""&&L.set(Ee,et);let Pt=B(Y.toolId,Fe,et,Y.executionId),nn=(cr=(tr=(qr=(Un=C.text)!=null?Un:C.delta)!=null?qr:C.content)!=null?tr:C.chunk)!=null?cr:"";nn&&(Pt.content+=String(nn),Pt.streaming=!0,g(Pt)),C.isComplete&&(Pt.streaming=!1,g(Pt));continue}let K=C.partId;if(K!==void 0&&T.current!==null&&K!==T.current){let Fe=u;Fe&&(Fe.streaming=!1,g(Fe),re=Fe,u=null,A=!0)}K!==void 0&&(T.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=C.text)!=null?S:C.delta)!=null?zn:C.content)!=null?dr:C.chunk)!=null?Lr:"";if(Xe){let Fe=typeof C.seq=="number"?C.seq:void 0,et=K!=null?K:J.id,Ee=Fe!==void 0?Qe(et,Fe,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=Fe!==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=Fe!==void 0?Ee:Xt.content+Xe,se.delete(Xt.id),te.delete(Xt.id),Xt.rawContent=void 0,g(Xt))}}).catch(()=>{J.content=Fe!==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=Fe!==void 0?Ee:J.content+Xe,se.delete(J.id),te.delete(J.id),J.rawContent=void 0,g(J))}}if(C.isComplete){let Fe=(ur=(pr=C.result)==null?void 0:pr.response)!=null?ur:J.content;if(Fe){let et=se.get(J.id),Ee=et!=null?et:Q(Fe);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(Fe));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 $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Fe=String((Ys=(uo=C.id)!=null?uo:Y.stepId)!=null?Ys:"");if(Fe){let et=_(Y.toolId,Fe);for(let[Ee,Je]of W)Ee.startsWith(et)&&Je.streaming!==!1&&(Je.streaming=!1,g(Je));L.delete(`${Y.toolId}::${Fe}`)}continue}let K=C.stopReason;if(A){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 Fe=(as=C.result)==null?void 0:as.response,et=re;et&&(K&&(et.stopReason=K),Fe!=null?Ie(et,Fe):(te.delete(et.id),se.delete(et.id))),re=null;continue}let J=(Zs=C.result)==null?void 0:Zs.response,Xe=Ne();if(K&&(Xe.stopReason=K),J!=null){let Fe=te.get(Xe.id),et=!1,Ee=!1;if(Fe){let Je=Fe.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=Fe.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=Fe.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=Fe.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)),Fe){let Je=(mt=Fe.close)==null?void 0:mt.call(Fe);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=C.result)==null?void 0:is.response;if(A){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 Fe=J!==k.content,et=k.streaming!==!1;Fe&&(k.content=J),k.streaming=!1,(Fe||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))}t({type:"status",status:"idle"})}else if(Ve==="agent_start")ae={executionId:C.executionId,agentId:(nr=C.agentId)!=null?nr:"virtual",agentName:(Ln=C.agentName)!=null?Ln:"",status:"running",currentIteration:0,maxTurns:(ea=C.maxTurns)!=null?ea:1,startedAt:ze(C.startedAt)};else if(Ve==="agent_iteration_start"){if(ae&&(ae.currentIteration=C.iteration),Ft==="separate"&&C.iteration>1){let $=u;$&&($.streaming=!1,g($),Mn.set(C.iteration-1,$),u=null)}}else if(Ve==="agent_turn_start")v=null;else if(Ve==="agent_turn_delta"){if(C.contentType==="text"){let $=Ne();$.content+=(ta=C.delta)!=null?ta:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:ae==null?void 0:ae.agentName},v=$,g($)}else if(C.contentType==="thinking"){let $=(Ro=C.turnId)!=null?Ro:`agent-think-${C.iteration}`,k=Le($);k.reasoning=(Ir=k.reasoning)!=null?Ir:{id:$,status:"streaming",chunks:[]},k.reasoning.chunks.push((na=C.delta)!=null?na:""),k.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},g(k)}else if(C.contentType==="tool_input"){let $=(mo=C.toolCallId)!=null?mo:I.lastId;if($){let k=P.get($);k!=null&&k.toolCall&&(k.toolCall.chunks=(ls=k.toolCall.chunks)!=null?ls:[],k.toolCall.chunks.push((Wr=C.delta)!=null?Wr:""),g(k))}}}else if(Ve==="agent_turn_complete"){let $=C.turnId;if($){let K=R.get($);if(K!=null&&K.reasoning){K.reasoning.status="complete",K.reasoning.completedAt=ze(C.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=C.stopReason,Y=u!=null?u:v;if(k&&Y!==null){let K=C.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 $=(ra=C.toolCallId)!=null?ra:`agent-tool-${l()}`;He(oe(C),$);let k=we($),Y=(oa=k.toolCall)!=null?oa:{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=(vi=C.toolName)!=null?vi:C.name)!=null?go:Y.name,Y.status="running",C.parameters!==void 0&&(Y.args=C.parameters),Y.startedAt=ze((Kr=C.startedAt)!=null?Kr:C.timestamp),k.toolCall=Y,k.streaming=!0,k.agentMetadata={executionId:C.executionId,iteration:C.iteration},g(k)}else if(Ve==="agent_tool_delta"){let $=(sa=C.toolCallId)!=null?sa:I.lastId;if($){let k=(ds=P.get($))!=null?ds:we($);k.toolCall&&(k.toolCall.chunks=(Jr=k.toolCall.chunks)!=null?Jr:[],k.toolCall.chunks.push((aa=C.delta)!=null?aa:""),k.toolCall.status="running",k.streaming=!0,g(k))}}else if(Ve==="agent_tool_complete"){let $=(ps=C.toolCallId)!=null?ps:I.lastId;if($){let k=(Gr=P.get($))!=null?Gr:we($);if(k.toolCall){k.toolCall.status="complete",C.result!==void 0&&(k.toolCall.result=C.result),typeof C.executionTime=="number"&&(k.toolCall.durationMs=C.executionTime),k.toolCall.completedAt=ze((us=C.completedAt)!=null?us:C.timestamp),k.streaming=!1,g(k);let Y=oe(C);Y&&I.byCall.delete(Y)}}}else if(Ve==="agent_media"){let $=Array.isArray(C.media)?C.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():"",Fe=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",Fe=`data:${et};base64,${Ee}`}else if(J==="image-url"){let Ee=typeof K.url=="string"?K.url:void 0;if(!Ee)continue;et=Xe,Fe=Ee}else if(J==="file-url"){let Ee=typeof K.url=="string"?K.url:void 0;if(!Ee)continue;et=Xe,Fe=Ee}else continue;if(Fe)if(J==="image-url"||et.startsWith("image/"))k.push({type:"image",image:Fe,...et?{mimeType:et}:{}});else if(et.startsWith("audio/"))k.push({type:"audio",audio:Fe,mimeType:et});else if(et.startsWith("video/"))k.push({type:"video",video:Fe,mimeType:et});else{let Ee=et||"application/octet-stream";k.push({type:"file",data:Fe,mimeType:Ee,filename:Gm(Ee)})}}if(k.length>0){let Y=l(),K=C.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:C.executionId,iteration:C.iteration}};g(Xe);let Fe=u;Fe&&(Fe.streaming=!1,g(Fe)),u=null,x.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,k={id:$,role:"assistant",content:(ia=C.reflection)!=null?ia:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:$,status:"complete",chunks:[(Rr=C.reflection)!=null?Rr:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};g(k)}else if(Ve==="agent_complete"){ae&&(ae.status=C.success?"complete":"error",ae.completedAt=ze(C.completedAt),ae.stopReason=C.stopReason);let $=u;$&&($.streaming=!1,g($)),t({type:"status",status:"idle"})}else if(Ve==="agent_error"){let $=typeof C.error=="string"?C.error:(Xr=(la=C.error)==null?void 0:la.message)!=null?Xr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):t({type:"error",error:new Error($)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let $=(Rt=C.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=C.executionId)!=null?Bo:ae==null?void 0:ae.executionId)!=null?ms:"",toolName:(Cr=C.toolName)!=null?Cr:"",toolType:C.toolType,description:(gs=C.description)!=null?gs:`Execute ${(ca=C.toolName)!=null?ca:"tool"}`,parameters:C.parameters}};g(k)}else if(Ve==="step_await"&&C.awaitReason==="approval_required"){let $=(fs=C.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:(da=ae==null?void 0:ae.agentId)!=null?da:"virtual",executionId:(No=(Do=C.executionId)!=null?Do:ae==null?void 0:ae.executionId)!=null?No:"",toolName:(fo=C.toolName)!=null?fo:"",toolType:C.toolType,description:(ua=C.description)!=null?ua:`Execute ${(pa=C.toolName)!=null?pa:"tool"}`,parameters:C.parameters}};g(k)}else if(Ve==="agent_approval_complete"){let $=C.approvalId;if($){let Y={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(hs=C.decision)!=null?hs:"approved",agentId:(bs=ae==null?void 0:ae.agentId)!=null?bs:"virtual",executionId:(xs=(ys=C.executionId)!=null?ys:ae==null?void 0:ae.executionId)!=null?xs:"",toolName:(vn=C.toolName)!=null?vn:"",description:(Vn=C.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 $=C.artifactType,k=String(C.id),Y=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:k,artifactType:$,title:Y,component:typeof C.component=="string"?C.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(C.id),k=typeof C.delta=="string"?C.delta:String((Hr=C.delta)!=null?Hr:"");t({type:"artifact_delta",id:$,artDelta:k});let Y=le.get($);Y&&(Y.markdown+=k)}else if(Ve==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(Ve==="artifact_complete"){let $=String(C.id);t({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 $=C.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),Fe=(ho=Xe==null?void 0:Xe.props)==null?void 0:ho.artifactId;typeof Fe=="string"&&V.add(Fe)}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(C.error instanceof Error)$=C.error;else if(Ve==="dispatch_error"){let k=(gr=C.message)!=null?gr:C.error;k!=null&&k!==""&&($=new Error(String(k)))}else if(Ve==="step_error"||Ve==="flow_error"){let k=C.error;typeof k=="string"&&k!==""?$=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&($=new Error(String((ma=k.message)!=null?ma:k)))}else Ve==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){t({type:"error",error:$});let k=u;k&&k.streaming&&(k.streaming=!1,g(k)),t({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<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},So=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ai=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Si=()=>{var n;let e=Km();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Ti=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=Mp(t,kp|Lp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Aa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Aa(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Jm=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Aa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Aa(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:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=Mp(o,kp|Lp),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},Ei=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Ma=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);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 ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.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 n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Gm="https://api.runtype.com/v1/dispatch",ka="https://api.runtype.com";function Xm(e){var o,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let s=n.indexOf("/");if(s>0){let i=(a=(o=n.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 Mi=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 Qm(e){switch(e){case"json":return Ti;case"regex-json":return Si;case"xml":return Ei;default:return Ai}}var Wp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Ym(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=Wp(t);if(!Wp(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=So(e);return So(n)!==null&&a===null?n:e}var qo=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,s,o;this.apiUrl=(t=n.apiUrl)!=null?t:Gm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Qm(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders,this.webMcpBridge=((o=n.webmcp)==null?void 0:o.enabled)===!0?new Es(n.webmcp):null}setSSEEventCallback(n){this.onSSEEvent=n}setWebMcpConfirmHandler(n){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(n)}isWebMcpOperational(){var n;return((n=this.webMcpBridge)==null?void 0:n.isOperational())===!0}executeWebMcpToolCall(n,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(n,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ka}/v1/client/${n}`}getClientSession(){return this.clientSession}async initSession(){var n,t;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(),(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});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 t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ka}/v1/client/feedback`}async sendFeedback(n){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(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});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(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){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:n,comment:t})}async submitNPSFeedback(n,t){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:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({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 t({type:"error",error:P}),P}let l=await this.buildPayload(n.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,m={sessionId:d.sessionId,messages:n.messages.filter(Mi).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}}),...n.assistantMessageId&&{assistantMessageId:n.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?Tp(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 t({type:"error",error:w}),w}if(L.status===429){let w=new Error(P.hint||"Message limit reached for this session.");throw t({type:"error",error:w}),w}let W=new Error(P.error||"Failed to send message");throw t({type:"error",error:W}),W}if(!L.body){let P=new Error("No response body received");throw t({type:"error",error:P}),P}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(L.body,t,n.assistantMessageId)}finally{t({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")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ka}/v1/agents/${n.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:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ka}/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:n,toolOutputs:t,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(n){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Mi).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:t,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:n,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(n){var o;let r={messages:n.slice().filter(Mi).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:n,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(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);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,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var ln,Hn,Xn,Ue;let s=n.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)&&t({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=Ym(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 Ma((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,Ys,as,Zs,Wo,mt,is,nr,Ln,ea,ta,Ro,Ir,na,mo,ls,Wr,cs,zr,Vr,ra,oa,vi,go,Kr,sa,ds,Jr,aa,ps,Gr,us,ia,Rr,la,Xr,Rt,Ho,Bo,ms,Cr,ca,gs,fs,da,Do,No,fo,pa,ua,hs,ys,bs,xs,vn,Vn,Hr,ot,vs,ho,gr,ma;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((Ys=(uo=A.id)!=null?uo:Y.stepId)!=null?Ys:"");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=(Zs=A.result)==null?void 0:Zs.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))}t({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:(ea=A.maxTurns)!=null?ea: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+=(ta=A.delta)!=null?ta:"",$.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((na=A.delta)!=null?na:""),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 $=(ra=A.toolCallId)!=null?ra:`agent-tool-${l()}`;He(oe(A),$);let k=we($),Y=(oa=k.toolCall)!=null?oa:{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=(vi=A.toolName)!=null?vi: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 $=(sa=A.toolCallId)!=null?sa: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((aa=A.delta)!=null?aa:""),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:Xm(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:(ia=A.reflection)!=null?ia:"",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($)),t({type:"status",status:"idle"})}else if(Ve==="agent_error"){let $=typeof A.error=="string"?A.error:(Xr=(la=A.error)==null?void 0:la.message)!=null?Xr:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):t({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 ${(ca=A.toolName)!=null?ca:"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:(da=ae==null?void 0:ae.agentId)!=null?da:"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:(ua=A.description)!=null?ua:`Execute ${(pa=A.toolName)!=null?pa:"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(t({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:"");t({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:{};t({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);t({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((ma=k.message)!=null?ma:k)))}else Ve==="error"&&A.error!=null&&A.error!==""&&($=new Error(String(A.error)));if($){t({type:"error",error:$});let k=u;k&&k.streaming&&(k.streaming=!1,g(k)),t({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(`
|
|
10
10
|
|
|
11
11
|
`);a=(Hn=Be.pop())!=null?Hn:"";for(let De of Be){let $e=De.split(`
|
|
12
|
-
`),dt="message",rt="";for(let q of $e)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(rt+=q.replace("data:","").trim());if(!rt)continue;let At;try{At=JSON.parse(rt)}catch(q){t({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,t,x,g,l,T);if(x.current&&x.current!==u&&(u=x.current),q)continue}de.push($t,At),_e()}}de.flushPending(),_e(),de.destroy()}};function Ym(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ls(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function zo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var La="[Image]";function Zm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function eg(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function tg(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function ng(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Pa(e){return{type:"text",text:e}}function rg(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function og(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function sg(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Rp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ag=["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=[...Rp,...ag];function ig(e){return Rp.includes(e)||e.startsWith("image/")}function Ia(e){return ig(e.type)}async function Hp(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ia(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Bp(e,n=Nr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function lg(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Dp(e,n){let t=lg(n).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]||t||"FILE"}var Wa=class{constructor(n=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=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),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 n of this.activeSources)try{n.stop(),n.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(n){this.finishedCallbacks.push(n)}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 n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ra=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.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(n){this.config=n;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 Ra;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(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,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=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.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=A=>{v||(v=!0,clearTimeout(T),u(new Error(A)))},T=setTimeout(()=>x("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(T),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!v){let R=A.code!==1006?` (code ${A.code})`:"";x("WebSocket connection failed"+R+"."+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(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.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(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Wa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("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 n,t,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=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t: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(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;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(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.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(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}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(n=>n.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(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var To=class{constructor(n={}){this.config=n;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(n=>n("connected"))}async startListening(){var n,t;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=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.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(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("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 ki(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 Ha(e){try{return ki(e),!0}catch{return!1}}function Np(e,n){let t=e instanceof Error?e:new Error(String(e));if(typeof n=="string")return n;if(typeof n=="function")return n(t);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 t.message?`${r}
|
|
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){t({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,t,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 Zm(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ls(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function zo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var La="[Image]";function eg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function tg(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function ng(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function rg(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Pa(e){return{type:"text",text:e}}function og(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function sg(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function ag(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Rp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ig=["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=[...Rp,...ig];function lg(e){return Rp.includes(e)||e.startsWith("image/")}function Ia(e){return lg(e.type)}async function Hp(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ia(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Bp(e,n=Nr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function cg(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Dp(e,n){let t=cg(n).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]||t||"FILE"}var Wa=class{constructor(n=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=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),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 n of this.activeSources)try{n.stop(),n.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(n){this.finishedCallbacks.push(n)}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 n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ra=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.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(n){this.config=n;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 Ra;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(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,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=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.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(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.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(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Wa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("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 n,t,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=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t: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(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;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(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.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(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}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(n=>n.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(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var To=class{constructor(n={}){this.config=n;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(n=>n("connected"))}async startListening(){var n,t;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=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.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(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("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 ki(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 Ha(e){try{return ki(e),!0}catch{return!1}}function Np(e,n){let t=e instanceof Error?e:new Error(String(e));if(typeof n=="string")return n;if(typeof n=="function")return n(t);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 t.message?`${r}
|
|
13
13
|
|
|
14
|
-
_Details: ${t.message}_`:r}var Is=class e{constructor(n={},t){this.config=n;this.callbacks=t;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=n=>{var t,r,s,o,a,i,d,l;if(n.type==="message"){this.upsertMessage(n.message);let p=n.message.toolCall;((t=n.message.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Ca(p.name)&&this.enqueueWebMcpAwait(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(s=n.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(n.type==="status"){if(this.setStatus(n.status),n.status==="connecting")this.setStreaming(!0);else if(n.status==="idle"||n.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"&&(n.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else n.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,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.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(n),this.wireDefaultWebMcpConfirm();for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Ha((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Vo(o);let a=(t=this.config.voiceRecognition)!=null?t:{},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 T=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(A=>A.role==="assistant"))==null?void 0:v.id;T&&this.ttsSpokenMessageIds.add(T)}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(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(p=n.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new qo(this.config),this.wireDefaultWebMcpConfirm(),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=n,u={id:a!=null?a:t==="user"?Ls():t==="assistant"?zo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,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(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){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}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=n,l={text:s,component:t,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(n,t){var l,p,m,g,u;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.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||La,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.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 T=Np(v,this.config.errorMessage);if(T){let A={id:o,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(A)}}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 n=zo();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Np(l,this.config.errorMessage);if(m){let g={id:n,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(n,t){var s,o,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.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(n,this.handleEvent,t==null?void 0:t.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 n=this.config.webmcp;(n==null?void 0:n.enabled)===!0&&!n.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(n){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,n))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:n.toolName,toolType:"webmcp",description:(a=n.description)!=null?a:`Allow the assistant to run ${n.toolName}?`,parameters:n.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(n,t){let r=this.webMcpApprovalResolvers.get(n);if(!r)return;this.webMcpApprovalResolvers.delete(n);let s=this.messages.find(o=>o.id===n);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(n,t){var d,l,p,m;let r=`approval-${n.id}`,s={...n,status:t,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:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):g=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),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}):(t==="denied"&&this.appendMessage({id:`denial-${n.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(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var p,m,g,u,v,x,T,A,R,P,W,L;let r=this.messages.find(w=>w.id===n.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=n.agentMetadata)==null?void 0:m.executionId,o=(g=n.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 t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let w=(x=n.toolCall)==null?void 0:x.args,I=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(I.length===1){let F=typeof((T=I[0])==null?void 0:T.question)=="string"?I[0].question:"";F&&(a={[F]:t})}}this.markAskUserQuestionResolved(n,a),(A=this.abortController)==null||A.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=n.toolCall.id,d=(R=n.toolCall)==null?void 0:R.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof t=="string"?t:Object.entries(t).map(([I,F])=>`${I}: ${Array.isArray(F)?F.join(", "):F}`).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,F)=>{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}-${F}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:t});if(!w.ok){let I=await w.json().catch(()=>null);throw new Error((P=I==null?void 0:I.error)!=null?P:`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||(L=(W=this.callbacks).onError)==null||L.call(W,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(n){var o,a;let t=(o=n.agentMetadata)==null?void 0:o.executionId,r=(a=n.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(n)});return}let s=this.webMcpAwaitBatches.get(t);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(n))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let n=this.webMcpEpoch;queueMicrotask(()=>{if(n===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(n){let t=this.webMcpAwaitBatches.get(n);if(!t)return;this.webMcpAwaitBatches.delete(n);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(n,r)}async resolveWebMcpToolCallBatch(n,t){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(t.map(async p=>{var R,P,W,L,w,I,F;let m=(R=p.toolCall)==null?void 0:R.name,g=(P=p.toolCall)==null?void 0:P.id;if(!m||!g)return null;let u=`${n}:${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=(L=(W=p.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?L:m,T=this.client.executeWebMcpToolCall(m,(w=p.toolCall)==null?void 0:w.args,v.signal),A;if(!T)A={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{A=await T}catch(_){return _ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"))||(F=(I=this.callbacks).onError)==null||F.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:A}}));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(n,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(n){var p,m,g,u,v,x,T,A,R,P,W,L;let t=(p=n.agentMetadata)==null?void 0:p.executionId,r=(m=n.toolCall)==null?void 0:m.name,s=(g=n.toolCall)==null?void 0:g.id;if(!t){(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=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(t,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){(T=(x=this.callbacks).onError)==null||T.call(x,I instanceof Error?I:new Error(String(I)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${t}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(A=n.toolCall)==null?void 0:A.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=(P=(R=n.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?P:r;await this.resumeWithToolOutput(t,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"))||(L=(W=this.callbacks).onError)==null||L.call(W,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(n,t,r,s){var a,i;let o=await this.client.resumeFlow(n,{[t]: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 n of this.webMcpResolveControllers)n.abort();this.webMcpResolveControllers.clear();for(let n of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(n,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.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(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(n.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(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.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,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var p,m,g,u,v,x;if(o!==r)return s;let a={...s,...t};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=t.toolCall)==null?void 0:m.name,d=(g=t.agentMetadata)==null?void 0:g.executionId,l=(u=t.toolCall)==null?void 0:u.id;if(i&&Ca(i)&&d&&l&&((v=t.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let T=`${d}:${l}`;(this.webMcpInflightKeys.has(T)||this.webMcpResolvedKeys.has(T))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},Sr=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import{Activity as cg,ArrowDown as dg,ArrowUp as pg,ArrowUpRight as ug,Bot as mg,ChevronDown as gg,ChevronUp as fg,ChevronRight as hg,ChevronLeft as bg,Check as yg,Clipboard as xg,ClipboardCopy as vg,Copy as wg,File as Cg,FileCode as Ag,FileSpreadsheet as Sg,FileText as Tg,ImagePlus as Eg,Loader as Mg,LoaderCircle as kg,Mic as Lg,Paperclip as Pg,RefreshCw as Ig,Search as Wg,Send as Rg,ShieldAlert as Hg,ShieldCheck as Bg,ShieldX as Dg,Square as Ng,ThumbsDown as Og,ThumbsUp as Fg,Upload as _g,Volume2 as $g,X as jg,User as Ug,Mail as qg,Phone as zg,Calendar as Vg,Clock as Kg,Building as Jg,MapPin as Gg,Lock as Xg,Key as Qg,CreditCard as Yg,AtSign as Zg,Hash as ef,Globe as tf,Link as nf,CircleCheck as rf,CircleX as of,TriangleAlert as sf,Info as af,Ban as lf,Shield as cf,ArrowLeft as df,ArrowRight as pf,ExternalLink as uf,Ellipsis as mf,EllipsisVertical as gf,Menu as ff,House as hf,Plus as bf,Minus as yf,Pencil as xf,Trash as vf,Trash2 as wf,Save as Cf,Download as Af,Share as Sf,Funnel as Tf,Settings as Ef,RotateCw as Mf,Maximize as kf,Minimize as Lf,ShoppingCart as Pf,ShoppingBag as If,Package as Wf,Truck as Rf,Tag as Hf,Gift as Bf,Receipt as Df,Wallet as Nf,Store as Of,DollarSign as Ff,Percent as _f,Play as $f,Pause as jf,VolumeX as Uf,Camera as qf,Image as zf,Film as Vf,Headphones as Kf,MessageCircle as Jf,MessageSquare as Gf,Bell as Xf,Heart as Qf,Star as Yf,Eye as Zf,EyeOff as eh,Bookmark as th,CalendarDays as nh,History as rh,Timer as oh,Folder as sh,FolderOpen as ah,Files as ih,Sparkles as lh,Zap as ch,Sun as dh,Moon as ph,Flag as uh,Monitor as mh,Smartphone as gh}from"lucide";var fh={activity:cg,"arrow-down":dg,"arrow-up":pg,"arrow-up-right":ug,bot:mg,"chevron-down":gg,"chevron-up":fg,"chevron-right":hg,"chevron-left":bg,check:yg,clipboard:xg,"clipboard-copy":vg,copy:wg,file:Cg,"file-code":Ag,"file-spreadsheet":Sg,"file-text":Tg,"image-plus":Eg,loader:Mg,"loader-circle":kg,mic:Lg,paperclip:Pg,"refresh-cw":Ig,search:Wg,send:Rg,"shield-alert":Hg,"shield-check":Bg,"shield-x":Dg,square:Ng,"thumbs-down":Og,"thumbs-up":Fg,upload:_g,"volume-2":$g,x:jg,user:Ug,mail:qg,phone:zg,calendar:Vg,clock:Kg,building:Jg,"map-pin":Gg,lock:Xg,key:Qg,"credit-card":Yg,"at-sign":Zg,hash:ef,globe:tf,link:nf,"circle-check":rf,"circle-x":of,"triangle-alert":sf,info:af,ban:lf,shield:cf,"arrow-left":df,"arrow-right":pf,"external-link":uf,ellipsis:mf,"ellipsis-vertical":gf,menu:ff,house:hf,plus:bf,minus:yf,pencil:xf,trash:vf,"trash-2":wf,save:Cf,download:Af,share:Sf,funnel:Tf,settings:Ef,"rotate-cw":Mf,maximize:kf,minimize:Lf,"shopping-cart":Pf,"shopping-bag":If,package:Wf,truck:Rf,tag:Hf,gift:Bf,receipt:Df,wallet:Nf,store:Of,"dollar-sign":Ff,percent:_f,play:$f,pause:jf,"volume-x":Uf,camera:qf,image:zf,film:Vf,headphones:Kf,"message-circle":Jf,"message-square":Gf,bell:Xf,heart:Qf,star:Yf,eye:Zf,"eye-off":eh,bookmark:th,"calendar-days":nh,history:rh,timer:oh,folder:sh,"folder-open":ah,files:ih,sparkles:lh,zap:ch,sun:dh,moon:ph,flag:uh,monitor:mh,smartphone:gh},ye=(e,n=24,t="currentColor",r=2)=>{let s=fh[e];return s?hh(s,n,t,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 hh(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),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 Ba={allowedTypes:Nr,maxFileSize:10*1024*1024,maxFiles:4};function bh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function yh(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(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ba.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ba.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Ba.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Ba.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let p=Bp(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 Hp(l),g=Ia(l)?URL.createObjectURL(l):null,u={id:bh(),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(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Ia(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.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=yh(n.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Dp(n.file.type,n.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=ye("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(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var Op=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ws(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];Op(o)&&Op(s)?t[r]=Ws(o,s):t[r]=s}return t}var sr="min(440px, calc(100vw - 24px))",Li="440px",Ot={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 Fp(e,n){if(!(!e&&!n))return e?n?Ws(e,n):e:n}function Pi(e){var n,t,r,s,o,a,i,d,l,p,m,g,u,v,x,T,A,R,P,W,L;return e?{...Ot,...e,theme:Fp(Ot.theme,e.theme),darkTheme:Fp(Ot.darkTheme,e.darkTheme),launcher:{...Ot.launcher,...e.launcher,dock:{...(n=Ot.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Ot.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ot.copy,...e.copy},sendButton:{...Ot.sendButton,...e.sendButton},statusIndicator:{...Ot.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ot.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Le,He,ee,Pe,V,le,ve;let w=(be=Ot.features)==null?void 0:be.artifacts,I=(Le=e.features)==null?void 0:Le.artifacts,F=(He=Ot.features)==null?void 0:He.scrollToBottom,_=(ee=e.features)==null?void 0:ee.scrollToBottom,B=(Pe=Ot.features)==null?void 0:Pe.streamAnimation,j=(V=e.features)==null?void 0:V.streamAnimation,z=(le=Ot.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=F===void 0&&_===void 0?void 0:{...F,..._},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{...Ot.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:Ot.suggestionChips,suggestionChipsConfig:{...Ot.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ot.layout,...e.layout,header:{...(a=Ot.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ot.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=Ot.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=Ot.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(A=(T=e.layout)==null?void 0:T.messages)==null?void 0:A.timestamp}},slots:{...(R=Ot.layout)==null?void 0:R.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Ot.markdown,...e.markdown,options:{...(W=Ot.markdown)==null?void 0:W.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Ot.messageActions,...e.messageActions}}:Ot}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"}},$p={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"}},jp={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:Li,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,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){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 Ii(e){let n={};function t(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&&(n[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&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function Up(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function qp(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=qp(o,s):t[r]=s}return t}function xh(e,n){return n?qp(e,n):e}function Rs(e,n={}){var s,o,a,i,d,l,p,m,g,u,v,x,T;let t={palette:_p,semantic:$p,components:jp},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:xh(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let A=Up(r);if(!A.valid)throw new Error(`Theme validation failed: ${A.errors.map(R=>R.message).join(", ")}`)}if(n.plugins)for(let A of n.plugins)r=A.transform(r);return r}function Wi(e){var x,T,A,R,P,W,L,w,I,F,_,B,j,z,oe,We,je,Ne,ge,be,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,Ft,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,bt,zt,tt,Bn,Qn,bn,Dn,ut,xr,Nn,po,kn,Io,Fr,Er,yt,On,Fn,yn,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 n=Ii(e),t={};for(let[S,zn]of Object.entries(n)){let dr=S.replace(/\./g,"-");t[`--persona-${dr}`]=zn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(A=t["--persona-semantic-colors-accent"])!=null?A:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(R=t["--persona-semantic-colors-surface"])!=null?R:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(P=t["--persona-semantic-colors-background"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(W=t["--persona-semantic-colors-container"])!=null?W:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(L=t["--persona-semantic-colors-text"])!=null?L:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(w=t["--persona-semantic-colors-text-muted"])!=null?w:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(I=t["--persona-semantic-colors-text-inverse"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(F=t["--persona-semantic-colors-border"])!=null?F:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(B=t["--persona-components-voice-recording-indicator"])!=null?B:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(j=t["--persona-components-voice-recording-background"])!=null?j:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(z=t["--persona-components-voice-processing-icon"])!=null?z:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(We=t["--persona-components-approval-requested-background"])!=null?We:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(je=t["--persona-components-approval-requested-border"])!=null?je:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ne=t["--persona-components-approval-requested-text"])!=null?Ne:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ge=t["--persona-components-approval-approve-background"])!=null?ge:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(be=t["--persona-components-approval-deny-background"])!=null?be:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Le=t["--persona-components-attachment-image-background"])!=null?Le:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(He=t["--persona-components-attachment-image-border"])!=null?He:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ee=t["--persona-semantic-typography-fontFamily"])!=null?ee:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Pe=t["--persona-semantic-typography-fontSize"])!=null?Pe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(V=t["--persona-semantic-typography-fontWeight"])!=null?V:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(le=t["--persona-semantic-typography-lineHeight"])!=null?le:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(ve=t["--persona-palette-radius-sm"])!=null?ve:"0.125rem",t["--persona-radius-md"]=(fe=t["--persona-palette-radius-md"])!=null?fe:"0.375rem",t["--persona-radius-lg"]=(we=t["--persona-palette-radius-lg"])!=null?we:"0.5rem",t["--persona-radius-xl"]=(ze=t["--persona-palette-radius-xl"])!=null?ze:"0.75rem",t["--persona-radius-full"]=(Q=t["--persona-palette-radius-full"])!=null?Q:"9999px",t["--persona-launcher-radius"]=(se=(te=t["--persona-components-launcher-borderRadius"])!=null?te:t["--persona-palette-radius-full"])!=null?se:"9999px",t["--persona-launcher-bg"]=(ue=t["--persona-components-launcher-background"])!=null?ue:t["--persona-primary"],t["--persona-launcher-fg"]=(ie=t["--persona-components-launcher-foreground"])!=null?ie:t["--persona-text-inverse"],t["--persona-launcher-border"]=(re=t["--persona-components-launcher-border"])!=null?re:t["--persona-border"],t["--persona-button-primary-bg"]=(Qe=t["--persona-components-button-primary-background"])!=null?Qe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Ie=t["--persona-components-button-primary-foreground"])!=null?Ie:t["--persona-text-inverse"],t["--persona-button-radius"]=(G=(ce=t["--persona-components-button-primary-borderRadius"])!=null?ce:t["--persona-palette-radius-full"])!=null?G:"9999px",t["--persona-panel-radius"]=(Et=(_e=t["--persona-components-panel-borderRadius"])!=null?_e:t["--persona-radius-xl"])!=null?Et:"0.75rem",t["--persona-panel-border"]=(de=t["--persona-components-panel-border"])!=null?de:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Mn=(ae=t["--persona-components-panel-shadow"])!=null?ae:t["--persona-palette-shadows-xl"])!=null?Mn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ln=(Ft=t["--persona-components-input-borderRadius"])!=null?Ft:t["--persona-radius-lg"])!=null?ln:"0.5rem",t["--persona-message-user-radius"]=(Xn=(Hn=t["--persona-components-message-user-borderRadius"])!=null?Hn:t["--persona-radius-lg"])!=null?Xn:"0.5rem",t["--persona-message-assistant-radius"]=(N=(Ue=t["--persona-components-message-assistant-borderRadius"])!=null?Ue:t["--persona-radius-lg"])!=null?N:"0.5rem",t["--persona-header-bg"]=(Ae=t["--persona-components-header-background"])!=null?Ae:t["--persona-surface"],t["--persona-header-border"]=(Be=t["--persona-components-header-border"])!=null?Be:t["--persona-divider"],t["--persona-header-icon-bg"]=(De=t["--persona-components-header-iconBackground"])!=null?De:t["--persona-primary"],t["--persona-header-icon-fg"]=($e=t["--persona-components-header-iconForeground"])!=null?$e:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(dt=t["--persona-components-header-titleForeground"])!=null?dt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(rt=t["--persona-components-header-subtitleForeground"])!=null?rt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(At=t["--persona-components-header-actionIconForeground"])!=null?At:t["--persona-muted"];let r=($t=e.components)==null?void 0:$t.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(q=e.components)==null?void 0:q.introCard;t["--persona-intro-card-bg"]=(_t=t["--persona-components-introCard-background"])!=null?_t:t["--persona-surface"],t["--persona-intro-card-radius"]=(Ye=t["--persona-components-introCard-borderRadius"])!=null?Ye:"1rem",t["--persona-intro-card-padding"]=(Dt=t["--persona-components-introCard-padding"])!=null?Dt:"1.5rem",t["--persona-intro-card-shadow"]=(me=(ne=s==null?void 0:s.shadow)!=null?ne:t["--persona-components-introCard-shadow"])!=null?me:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(vt=t["--persona-components-input-background"])!=null?vt:t["--persona-surface"],t["--persona-input-placeholder"]=(jt=t["--persona-components-input-placeholder"])!=null?jt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Zt=t["--persona-components-message-user-background"])!=null?Zt:t["--persona-accent"],t["--persona-message-user-text"]=(hn=t["--persona-components-message-user-text"])!=null?hn:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(St=t["--persona-components-message-user-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(wt=t["--persona-components-message-assistant-background"])!=null?wt:t["--persona-surface"],t["--persona-message-assistant-text"]=(ft=t["--persona-components-message-assistant-text"])!=null?ft:t["--persona-text"],t["--persona-message-assistant-border"]=(bt=t["--persona-components-message-assistant-border"])!=null?bt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(zt=t["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Bn=(tt=t["--persona-components-scrollToBottom-background"])!=null?tt:t["--persona-button-primary-bg"])!=null?Bn:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(bn=(Qn=t["--persona-components-scrollToBottom-foreground"])!=null?Qn:t["--persona-button-primary-fg"])!=null?bn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Dn=t["--persona-components-scrollToBottom-border"])!=null?Dn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(ut=t["--persona-components-scrollToBottom-size"])!=null?ut:"40px",t["--persona-scroll-to-bottom-radius"]=(po=(Nn=(xr=t["--persona-components-scrollToBottom-borderRadius"])!=null?xr:t["--persona-button-radius"])!=null?Nn:t["--persona-radius-full"])!=null?po:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Io=(kn=t["--persona-components-scrollToBottom-shadow"])!=null?kn:t["--persona-palette-shadows-sm"])!=null?Io:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Fr=t["--persona-components-scrollToBottom-padding"])!=null?Fr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Er=t["--persona-components-scrollToBottom-gap"])!=null?Er:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(On=(yt=t["--persona-components-scrollToBottom-fontSize"])!=null?yt:t["--persona-palette-typography-fontSize-sm"])!=null?On:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Fn=t["--persona-components-scrollToBottom-iconSize"])!=null?Fn:"14px",t["--persona-tool-bubble-shadow"]=(yn=t["--persona-components-toolBubble-shadow"])!=null?yn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Lt=t["--persona-components-reasoningBubble-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Yn=t["--persona-components-composer-shadow"])!=null?Yn:"none",t["--persona-md-inline-code-bg"]=(Zn=t["--persona-components-markdown-inlineCode-background"])!=null?Zn:t["--persona-container"],t["--persona-md-inline-code-color"]=(_n=t["--persona-components-markdown-inlineCode-foreground"])!=null?_n:t["--persona-text"],t["--persona-md-link-color"]=(Mr=(_r=t["--persona-components-markdown-link-foreground"])!=null?_r:t["--persona-accent"])!=null?Mr:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=($r=t["--persona-components-markdown-codeBlock-background"])!=null?$r:t["--persona-container"],t["--persona-md-code-block-border-color"]=($n=t["--persona-components-markdown-codeBlock-borderColor"])!=null?$n:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Wt=t["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",t["--persona-md-table-header-bg"]=(xn=t["--persona-components-markdown-table-headerBackground"])!=null?xn:t["--persona-container"],t["--persona-md-table-border-color"]=(er=t["--persona-components-markdown-table-borderColor"])!=null?er:t["--persona-border"],t["--persona-md-hr-color"]=(jr=t["--persona-components-markdown-hr-color"])!=null?jr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(kr=t["--persona-components-markdown-blockquote-borderColor"])!=null?kr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Ur=t["--persona-components-markdown-blockquote-background"])!=null?Ur:"transparent",t["--persona-md-blockquote-text-color"]=(vr=t["--persona-components-markdown-blockquote-textColor"])!=null?vr:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(jn=t["--persona-components-collapsibleWidget-container"])!=null?jn:t["--persona-surface"],t["--cw-surface"]=(lr=t["--persona-components-collapsibleWidget-surface"])!=null?lr:t["--persona-surface"],t["--cw-border"]=(gt=t["--persona-components-collapsibleWidget-border"])!=null?gt:t["--persona-border"],t["--persona-message-border"]=(Jt=t["--persona-components-message-border"])!=null?Jt:t["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(t["--persona-icon-btn-bg"]=m.background),m.border&&(t["--persona-icon-btn-border"]=m.border),m.color&&(t["--persona-icon-btn-color"]=m.color),m.padding&&(t["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(t["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(t["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(t["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(t["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(t["--persona-label-btn-bg"]=g.background),g.border&&(t["--persona-label-btn-border"]=g.border),g.color&&(t["--persona-label-btn-color"]=g.color),g.padding&&(t["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(t["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(t["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(t["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(t["--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&&(t["--persona-artifact-toolbar-icon-hover-color"]=S.iconHoverColor),S.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=S.iconHoverBackground),S.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=S.iconPadding),S.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=S.iconBorderRadius),S.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=S.iconBorder),S.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=S.toggleGroupGap),S.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=S.toggleBorderRadius),S.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=S.copyBackground),S.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=S.copyBorder),S.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=S.copyColor),S.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=S.copyBorderRadius),S.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=S.copyPadding),S.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=S.copyMenuBackground,t["--persona-dropdown-bg"]=(Gt=t["--persona-dropdown-bg"])!=null?Gt:S.copyMenuBackground),S.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=S.copyMenuBorder,t["--persona-dropdown-border"]=(Un=t["--persona-dropdown-border"])!=null?Un:S.copyMenuBorder),S.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=S.copyMenuShadow,t["--persona-dropdown-shadow"]=(qr=t["--persona-dropdown-shadow"])!=null?qr:S.copyMenuShadow),S.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=S.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(tr=t["--persona-dropdown-radius"])!=null?tr:S.copyMenuBorderRadius),S.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=S.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(cr=t["--persona-dropdown-item-hover-bg"])!=null?cr:S.copyMenuItemHoverBackground),S.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=S.iconBackground),S.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=S.toolbarBorder)}if(v!=null&&v.tab){let S=v.tab;S.background&&(t["--persona-artifact-tab-bg"]=S.background),S.activeBackground&&(t["--persona-artifact-tab-active-bg"]=S.activeBackground),S.activeBorder&&(t["--persona-artifact-tab-active-border"]=S.activeBorder),S.borderRadius&&(t["--persona-artifact-tab-radius"]=S.borderRadius),S.textColor&&(t["--persona-artifact-tab-color"]=S.textColor),S.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=S.hoverBackground),S.listBackground&&(t["--persona-artifact-tab-list-bg"]=S.listBackground),S.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=S.listBorderColor),S.listPadding&&(t["--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;t["--persona-artifact-toolbar-bg"]=zn}}return t}var vh={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 wh={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},zp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Da=()=>{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"},Ch=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Da()},Vp=e=>Ch(e),Ah=e=>Rs(e),Sh=e=>{var t;let n=Rs(void 0,{validate:!1});return Rs({...e,palette:{...n.palette,colors:{...wh.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Hs=e=>{let n=Vp(e),t=zp(e==null?void 0:e.theme),r=zp(e==null?void 0:e.darkTheme);return n==="dark"?Sh(Ws(t!=null?t:{},r!=null?r:{})):Ah(t)},Th=e=>Wi(e),Eo=(e,n)=>{var o;let t=Hs(n),r=Th(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Ri=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Da())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Da());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as Eh}from"idiomorph";var Na=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Eh.morph(e,n.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 Kp(e){let{direction:n,history:t,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(t.length===0)return{handled:!1,state:o};if(n==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<t.length-1){let i=o.index+1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...Oa}}}function Jp(e,n){var t,r,s,o,a,i,d,l,p,m,g,u,v,x,T,A,R,P,W,L,w,I,F,_,B,j,z,oe,We,je,Ne,ge,be,Le,He,ee,Pe,V;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.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:"",(T=(x=e.toolCall)==null?void 0:x.name)!=null?T:"",(P=(R=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:R.length)!=null?P:0,(I=(w=(L=(W=e.toolCall)==null?void 0:W.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?I:"",typeof((F=e.toolCall)==null?void 0:F.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=(be=(ge=e.reasoning)==null?void 0:ge.chunks)==null?void 0:be[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:"",n].join("\0")}function Gp(){return new Map}function Xp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Qp(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Yp(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Fa(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Bs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ds(e,n){return Bs(e)-e.scrollTop<=n}function _a(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=t-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!n&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:n&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function $a(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>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"},Mh=["pre","code","a","script","style"],ja=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Ns.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t: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}},eu=[{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"}],Os=new Map;for(let e of eu)Os.set(e.name,e);var kh=e=>{Os.set(e.name,e)},Lh=e=>{eu.some(n=>n.name===e)||Os.delete(e)},Ph=()=>Array.from(Os.keys()),Fs=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Os.get(e))!=null?r:null},Ua=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
|
|
15
|
-
`);return o<0?"":e.slice(0,o)}return e},
|
|
14
|
+
_Details: ${t.message}_`:r}var Is=class e{constructor(n={},t){this.config=n;this.callbacks=t;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=n=>{var t,r,s,o,a,i,d,l;if(n.type==="message"){this.upsertMessage(n.message);let p=n.message.toolCall;((t=n.message.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&(p!=null&&p.name)&&Ca(p.name)&&this.enqueueWebMcpAwait(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(s=n.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(n.type==="status"){if(this.setStatus(n.status),n.status==="connecting")this.setStreaming(!0);else if(n.status==="idle"||n.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"&&(n.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else n.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,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.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(n),this.wireDefaultWebMcpConfirm();for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Ha((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Vo(o);let a=(t=this.config.voiceRecognition)!=null?t:{},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(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(p=n.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new qo(this.config),this.wireDefaultWebMcpConfirm(),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=n,u={id:a!=null?a:t==="user"?Ls():t==="assistant"?zo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,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(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){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}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=n,l={text:s,component:t,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(n,t){var l,p,m,g,u;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.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||La,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.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=Np(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 n=zo();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Np(l,this.config.errorMessage);if(m){let g={id:n,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(n,t){var s,o,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.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(n,this.handleEvent,t==null?void 0:t.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 n=this.config.webmcp;(n==null?void 0:n.enabled)===!0&&!n.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(n){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,n))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:n.toolName,toolType:"webmcp",description:(a=n.description)!=null?a:`Allow the assistant to run ${n.toolName}?`,parameters:n.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(n,t){let r=this.webMcpApprovalResolvers.get(n);if(!r)return;this.webMcpApprovalResolvers.delete(n);let s=this.messages.find(o=>o.id===n);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(n,t){var d,l,p,m;let r=`approval-${n.id}`,s={...n,status:t,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:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):g=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),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}):(t==="denied"&&this.appendMessage({id:`denial-${n.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(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var p,m,g,u,v,x,C,T,H,L,P,W;let r=this.messages.find(w=>w.id===n.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=n.agentMetadata)==null?void 0:m.executionId,o=(g=n.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 t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let w=(x=n.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]:t})}}this.markAskUserQuestionResolved(n,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=n.toolCall.id,d=(H=n.toolCall)==null?void 0:H.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof t=="string"?t:Object.entries(t).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]:t});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(n){var o,a;let t=(o=n.agentMetadata)==null?void 0:o.executionId,r=(a=n.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(n)});return}let s=this.webMcpAwaitBatches.get(t);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(n))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let n=this.webMcpEpoch;queueMicrotask(()=>{if(n===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(n){let t=this.webMcpAwaitBatches.get(n);if(!t)return;this.webMcpAwaitBatches.delete(n);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(n,r)}async resolveWebMcpToolCallBatch(n,t){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(t.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=`${n}:${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(n,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(n){var p,m,g,u,v,x,C,T,H,L,P,W;let t=(p=n.agentMetadata)==null?void 0:p.executionId,r=(m=n.toolCall)==null?void 0:m.name,s=(g=n.toolCall)==null?void 0:g.id;if(!t){(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=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(t,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=`${t}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(T=n.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=n.agentMetadata)==null?void 0:H.webMcpToolCallId)!=null?L:r;await this.resumeWithToolOutput(t,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(n,t,r,s){var a,i;let o=await this.client.resumeFlow(n,{[t]: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 n of this.webMcpResolveControllers)n.abort();this.webMcpResolveControllers.clear();for(let n of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(n,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.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(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(n.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(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.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,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var p,m,g,u,v,x;if(o!==r)return s;let a={...s,...t};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=t.toolCall)==null?void 0:m.name,d=(g=t.agentMetadata)==null?void 0:g.executionId,l=(u=t.toolCall)==null?void 0:u.id;if(i&&Ca(i)&&d&&l&&((v=t.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(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},Sr=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import{Activity as dg,ArrowDown as pg,ArrowUp as ug,ArrowUpRight as mg,Bot as gg,ChevronDown as fg,ChevronUp as hg,ChevronRight as yg,ChevronLeft as bg,Check as xg,Clipboard as vg,ClipboardCopy as wg,Copy as Cg,File as Ag,FileCode as Sg,FileSpreadsheet as Tg,FileText as Eg,ImagePlus as Mg,Loader as kg,LoaderCircle as Lg,Mic as Pg,Paperclip as Ig,RefreshCw as Wg,Search as Rg,Send as Hg,ShieldAlert as Bg,ShieldCheck as Dg,ShieldX as Ng,Square as Fg,ThumbsDown as Og,ThumbsUp as _g,Upload as $g,Volume2 as jg,X as Ug,User as qg,Mail as zg,Phone as Vg,Calendar as Kg,Clock as Jg,Building as Gg,MapPin as Xg,Lock as Qg,Key as Yg,CreditCard as Zg,AtSign as ef,Hash as tf,Globe as nf,Link as rf,CircleCheck as of,CircleX as sf,TriangleAlert as af,Info as lf,Ban as cf,Shield as df,ArrowLeft as pf,ArrowRight as uf,ExternalLink as mf,Ellipsis as gf,EllipsisVertical as ff,Menu as hf,House as yf,Plus as bf,Minus as xf,Pencil as vf,Trash as wf,Trash2 as Cf,Save as Af,Download as Sf,Share as Tf,Funnel as Ef,Settings as Mf,RotateCw as kf,Maximize as Lf,Minimize as Pf,ShoppingCart as If,ShoppingBag as Wf,Package as Rf,Truck as Hf,Tag as Bf,Gift as Df,Receipt as Nf,Wallet as Ff,Store as Of,DollarSign as _f,Percent as $f,Play as jf,Pause as Uf,VolumeX as qf,Camera as zf,Image as Vf,Film as Kf,Headphones as Jf,MessageCircle as Gf,MessageSquare as Xf,Bell as Qf,Heart as Yf,Star as Zf,Eye as eh,EyeOff as th,Bookmark as nh,CalendarDays as rh,History as oh,Timer as sh,Folder as ah,FolderOpen as ih,Files as lh,Sparkles as ch,Zap as dh,Sun as ph,Moon as uh,Flag as mh,Monitor as gh,Smartphone as fh}from"lucide";var hh={activity:dg,"arrow-down":pg,"arrow-up":ug,"arrow-up-right":mg,bot:gg,"chevron-down":fg,"chevron-up":hg,"chevron-right":yg,"chevron-left":bg,check:xg,clipboard:vg,"clipboard-copy":wg,copy:Cg,file:Ag,"file-code":Sg,"file-spreadsheet":Tg,"file-text":Eg,"image-plus":Mg,loader:kg,"loader-circle":Lg,mic:Pg,paperclip:Ig,"refresh-cw":Wg,search:Rg,send:Hg,"shield-alert":Bg,"shield-check":Dg,"shield-x":Ng,square:Fg,"thumbs-down":Og,"thumbs-up":_g,upload:$g,"volume-2":jg,x:Ug,user:qg,mail:zg,phone:Vg,calendar:Kg,clock:Jg,building:Gg,"map-pin":Xg,lock:Qg,key:Yg,"credit-card":Zg,"at-sign":ef,hash:tf,globe:nf,link:rf,"circle-check":of,"circle-x":sf,"triangle-alert":af,info:lf,ban:cf,shield:df,"arrow-left":pf,"arrow-right":uf,"external-link":mf,ellipsis:gf,"ellipsis-vertical":ff,menu:hf,house:yf,plus:bf,minus:xf,pencil:vf,trash:wf,"trash-2":Cf,save:Af,download:Sf,share:Tf,funnel:Ef,settings:Mf,"rotate-cw":kf,maximize:Lf,minimize:Pf,"shopping-cart":If,"shopping-bag":Wf,package:Rf,truck:Hf,tag:Bf,gift:Df,receipt:Nf,wallet:Ff,store:Of,"dollar-sign":_f,percent:$f,play:jf,pause:Uf,"volume-x":qf,camera:zf,image:Vf,film:Kf,headphones:Jf,"message-circle":Gf,"message-square":Xf,bell:Qf,heart:Yf,star:Zf,eye:eh,"eye-off":th,bookmark:nh,"calendar-days":rh,history:oh,timer:sh,folder:ah,"folder-open":ih,files:lh,sparkles:ch,zap:dh,sun:ph,moon:uh,flag:mh,monitor:gh,smartphone:fh},be=(e,n=24,t="currentColor",r=2)=>{let s=hh[e];return s?yh(s,n,t,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 yh(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),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 Ba={allowedTypes:Nr,maxFileSize:10*1024*1024,maxFiles:4};function bh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xh(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(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ba.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ba.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Ba.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Ba.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let p=Bp(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 Hp(l),g=Ia(l)?URL.createObjectURL(l):null,u={id:bh(),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(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Ia(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.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=xh(n.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Dp(n.file.type,n.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(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var Fp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ws(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];Fp(o)&&Fp(s)?t[r]=Ws(o,s):t[r]=s}return t}var sr="min(440px, calc(100vw - 24px))",Li="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 Op(e,n){if(!(!e&&!n))return e?n?Ws(e,n):e:n}function Pi(e){var n,t,r,s,o,a,i,d,l,p,m,g,u,v,x,C,T,H,L,P,W;return e?{...Ft,...e,theme:Op(Ft.theme,e.theme),darkTheme:Op(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(n=Ft.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.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"}},$p={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"}},jp={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:Li,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,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){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 Ii(e){let n={};function t(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&&(n[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&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function Up(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function qp(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=qp(o,s):t[r]=s}return t}function vh(e,n){return n?qp(e,n):e}function Rs(e,n={}){var s,o,a,i,d,l,p,m,g,u,v,x,C;let t={palette:_p,semantic:$p,components:jp},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:vh(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let T=Up(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(H=>H.message).join(", ")}`)}if(n.plugins)for(let T of n.plugins)r=T.transform(r);return r}function Wi(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 n=Ii(e),t={};for(let[S,zn]of Object.entries(n)){let dr=S.replace(/\./g,"-");t[`--persona-${dr}`]=zn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(C=t["--persona-semantic-colors-secondary"])!=null?C:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(T=t["--persona-semantic-colors-accent"])!=null?T:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(H=t["--persona-semantic-colors-surface"])!=null?H:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(L=t["--persona-semantic-colors-background"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(P=t["--persona-semantic-colors-container"])!=null?P:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(W=t["--persona-semantic-colors-text"])!=null?W:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(w=t["--persona-semantic-colors-text-muted"])!=null?w:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(I=t["--persona-semantic-colors-text-inverse"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(O=t["--persona-semantic-colors-border"])!=null?O:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(B=t["--persona-components-voice-recording-indicator"])!=null?B:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(j=t["--persona-components-voice-recording-background"])!=null?j:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(z=t["--persona-components-voice-processing-icon"])!=null?z:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(We=t["--persona-components-approval-requested-background"])!=null?We:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(je=t["--persona-components-approval-requested-border"])!=null?je:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ne=t["--persona-components-approval-requested-text"])!=null?Ne:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ge=t["--persona-components-approval-approve-background"])!=null?ge:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ye=t["--persona-components-approval-deny-background"])!=null?ye:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Le=t["--persona-components-attachment-image-background"])!=null?Le:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(He=t["--persona-components-attachment-image-border"])!=null?He:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ee=t["--persona-semantic-typography-fontFamily"])!=null?ee:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Pe=t["--persona-semantic-typography-fontSize"])!=null?Pe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(V=t["--persona-semantic-typography-fontWeight"])!=null?V:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(le=t["--persona-semantic-typography-lineHeight"])!=null?le:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(ve=t["--persona-palette-radius-sm"])!=null?ve:"0.125rem",t["--persona-radius-md"]=(fe=t["--persona-palette-radius-md"])!=null?fe:"0.375rem",t["--persona-radius-lg"]=(we=t["--persona-palette-radius-lg"])!=null?we:"0.5rem",t["--persona-radius-xl"]=(ze=t["--persona-palette-radius-xl"])!=null?ze:"0.75rem",t["--persona-radius-full"]=(Q=t["--persona-palette-radius-full"])!=null?Q:"9999px",t["--persona-launcher-radius"]=(se=(te=t["--persona-components-launcher-borderRadius"])!=null?te:t["--persona-palette-radius-full"])!=null?se:"9999px",t["--persona-launcher-bg"]=(ue=t["--persona-components-launcher-background"])!=null?ue:t["--persona-primary"],t["--persona-launcher-fg"]=(ie=t["--persona-components-launcher-foreground"])!=null?ie:t["--persona-text-inverse"],t["--persona-launcher-border"]=(re=t["--persona-components-launcher-border"])!=null?re:t["--persona-border"],t["--persona-button-primary-bg"]=(Qe=t["--persona-components-button-primary-background"])!=null?Qe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Ie=t["--persona-components-button-primary-foreground"])!=null?Ie:t["--persona-text-inverse"],t["--persona-button-radius"]=(G=(ce=t["--persona-components-button-primary-borderRadius"])!=null?ce:t["--persona-palette-radius-full"])!=null?G:"9999px",t["--persona-panel-radius"]=(Et=(_e=t["--persona-components-panel-borderRadius"])!=null?_e:t["--persona-radius-xl"])!=null?Et:"0.75rem",t["--persona-panel-border"]=(de=t["--persona-components-panel-border"])!=null?de:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Mn=(ae=t["--persona-components-panel-shadow"])!=null?ae:t["--persona-palette-shadows-xl"])!=null?Mn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ln=(Ot=t["--persona-components-input-borderRadius"])!=null?Ot:t["--persona-radius-lg"])!=null?ln:"0.5rem",t["--persona-message-user-radius"]=(Xn=(Hn=t["--persona-components-message-user-borderRadius"])!=null?Hn:t["--persona-radius-lg"])!=null?Xn:"0.5rem",t["--persona-message-assistant-radius"]=(N=(Ue=t["--persona-components-message-assistant-borderRadius"])!=null?Ue:t["--persona-radius-lg"])!=null?N:"0.5rem",t["--persona-header-bg"]=(Ae=t["--persona-components-header-background"])!=null?Ae:t["--persona-surface"],t["--persona-header-border"]=(Be=t["--persona-components-header-border"])!=null?Be:t["--persona-divider"],t["--persona-header-icon-bg"]=(De=t["--persona-components-header-iconBackground"])!=null?De:t["--persona-primary"],t["--persona-header-icon-fg"]=($e=t["--persona-components-header-iconForeground"])!=null?$e:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(dt=t["--persona-components-header-titleForeground"])!=null?dt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(rt=t["--persona-components-header-subtitleForeground"])!=null?rt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(At=t["--persona-components-header-actionIconForeground"])!=null?At:t["--persona-muted"];let r=($t=e.components)==null?void 0:$t.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(q=e.components)==null?void 0:q.introCard;t["--persona-intro-card-bg"]=(_t=t["--persona-components-introCard-background"])!=null?_t:t["--persona-surface"],t["--persona-intro-card-radius"]=(Ye=t["--persona-components-introCard-borderRadius"])!=null?Ye:"1rem",t["--persona-intro-card-padding"]=(Dt=t["--persona-components-introCard-padding"])!=null?Dt:"1.5rem",t["--persona-intro-card-shadow"]=(me=(ne=s==null?void 0:s.shadow)!=null?ne:t["--persona-components-introCard-shadow"])!=null?me:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(vt=t["--persona-components-input-background"])!=null?vt:t["--persona-surface"],t["--persona-input-placeholder"]=(jt=t["--persona-components-input-placeholder"])!=null?jt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Zt=t["--persona-components-message-user-background"])!=null?Zt:t["--persona-accent"],t["--persona-message-user-text"]=(hn=t["--persona-components-message-user-text"])!=null?hn:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(St=t["--persona-components-message-user-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(wt=t["--persona-components-message-assistant-background"])!=null?wt:t["--persona-surface"],t["--persona-message-assistant-text"]=(ft=t["--persona-components-message-assistant-text"])!=null?ft:t["--persona-text"],t["--persona-message-assistant-border"]=(yt=t["--persona-components-message-assistant-border"])!=null?yt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(zt=t["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Bn=(tt=t["--persona-components-scrollToBottom-background"])!=null?tt:t["--persona-button-primary-bg"])!=null?Bn:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(yn=(Qn=t["--persona-components-scrollToBottom-foreground"])!=null?Qn:t["--persona-button-primary-fg"])!=null?yn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Dn=t["--persona-components-scrollToBottom-border"])!=null?Dn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(ut=t["--persona-components-scrollToBottom-size"])!=null?ut:"40px",t["--persona-scroll-to-bottom-radius"]=(po=(Nn=(xr=t["--persona-components-scrollToBottom-borderRadius"])!=null?xr:t["--persona-button-radius"])!=null?Nn:t["--persona-radius-full"])!=null?po:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Io=(kn=t["--persona-components-scrollToBottom-shadow"])!=null?kn:t["--persona-palette-shadows-sm"])!=null?Io:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Or=t["--persona-components-scrollToBottom-padding"])!=null?Or:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Er=t["--persona-components-scrollToBottom-gap"])!=null?Er:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Fn=(bt=t["--persona-components-scrollToBottom-fontSize"])!=null?bt:t["--persona-palette-typography-fontSize-sm"])!=null?Fn:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(On=t["--persona-components-scrollToBottom-iconSize"])!=null?On:"14px",t["--persona-tool-bubble-shadow"]=(bn=t["--persona-components-toolBubble-shadow"])!=null?bn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Lt=t["--persona-components-reasoningBubble-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Yn=t["--persona-components-composer-shadow"])!=null?Yn:"none",t["--persona-md-inline-code-bg"]=(Zn=t["--persona-components-markdown-inlineCode-background"])!=null?Zn:t["--persona-container"],t["--persona-md-inline-code-color"]=(_n=t["--persona-components-markdown-inlineCode-foreground"])!=null?_n:t["--persona-text"],t["--persona-md-link-color"]=(Mr=(_r=t["--persona-components-markdown-link-foreground"])!=null?_r:t["--persona-accent"])!=null?Mr:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=($r=t["--persona-components-markdown-codeBlock-background"])!=null?$r:t["--persona-container"],t["--persona-md-code-block-border-color"]=($n=t["--persona-components-markdown-codeBlock-borderColor"])!=null?$n:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Wt=t["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",t["--persona-md-table-header-bg"]=(xn=t["--persona-components-markdown-table-headerBackground"])!=null?xn:t["--persona-container"],t["--persona-md-table-border-color"]=(er=t["--persona-components-markdown-table-borderColor"])!=null?er:t["--persona-border"],t["--persona-md-hr-color"]=(jr=t["--persona-components-markdown-hr-color"])!=null?jr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(kr=t["--persona-components-markdown-blockquote-borderColor"])!=null?kr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Ur=t["--persona-components-markdown-blockquote-background"])!=null?Ur:"transparent",t["--persona-md-blockquote-text-color"]=(vr=t["--persona-components-markdown-blockquote-textColor"])!=null?vr:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(jn=t["--persona-components-collapsibleWidget-container"])!=null?jn:t["--persona-surface"],t["--cw-surface"]=(lr=t["--persona-components-collapsibleWidget-surface"])!=null?lr:t["--persona-surface"],t["--cw-border"]=(gt=t["--persona-components-collapsibleWidget-border"])!=null?gt:t["--persona-border"],t["--persona-message-border"]=(Jt=t["--persona-components-message-border"])!=null?Jt:t["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(t["--persona-icon-btn-bg"]=m.background),m.border&&(t["--persona-icon-btn-border"]=m.border),m.color&&(t["--persona-icon-btn-color"]=m.color),m.padding&&(t["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(t["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(t["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(t["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(t["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(t["--persona-label-btn-bg"]=g.background),g.border&&(t["--persona-label-btn-border"]=g.border),g.color&&(t["--persona-label-btn-color"]=g.color),g.padding&&(t["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(t["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(t["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(t["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(t["--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&&(t["--persona-artifact-toolbar-icon-hover-color"]=S.iconHoverColor),S.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=S.iconHoverBackground),S.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=S.iconPadding),S.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=S.iconBorderRadius),S.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=S.iconBorder),S.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=S.toggleGroupGap),S.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=S.toggleBorderRadius),S.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=S.copyBackground),S.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=S.copyBorder),S.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=S.copyColor),S.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=S.copyBorderRadius),S.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=S.copyPadding),S.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=S.copyMenuBackground,t["--persona-dropdown-bg"]=(Gt=t["--persona-dropdown-bg"])!=null?Gt:S.copyMenuBackground),S.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=S.copyMenuBorder,t["--persona-dropdown-border"]=(Un=t["--persona-dropdown-border"])!=null?Un:S.copyMenuBorder),S.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=S.copyMenuShadow,t["--persona-dropdown-shadow"]=(qr=t["--persona-dropdown-shadow"])!=null?qr:S.copyMenuShadow),S.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=S.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(tr=t["--persona-dropdown-radius"])!=null?tr:S.copyMenuBorderRadius),S.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=S.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(cr=t["--persona-dropdown-item-hover-bg"])!=null?cr:S.copyMenuItemHoverBackground),S.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=S.iconBackground),S.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=S.toolbarBorder)}if(v!=null&&v.tab){let S=v.tab;S.background&&(t["--persona-artifact-tab-bg"]=S.background),S.activeBackground&&(t["--persona-artifact-tab-active-bg"]=S.activeBackground),S.activeBorder&&(t["--persona-artifact-tab-active-border"]=S.activeBorder),S.borderRadius&&(t["--persona-artifact-tab-radius"]=S.borderRadius),S.textColor&&(t["--persona-artifact-tab-color"]=S.textColor),S.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=S.hoverBackground),S.listBackground&&(t["--persona-artifact-tab-list-bg"]=S.listBackground),S.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=S.listBorderColor),S.listPadding&&(t["--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;t["--persona-artifact-toolbar-bg"]=zn}}return t}var wh={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 Ch={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},zp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Da=()=>{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"},Ah=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Da()},Vp=e=>Ah(e),Sh=e=>Rs(e),Th=e=>{var t;let n=Rs(void 0,{validate:!1});return Rs({...e,palette:{...n.palette,colors:{...Ch.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Hs=e=>{let n=Vp(e),t=zp(e==null?void 0:e.theme),r=zp(e==null?void 0:e.darkTheme);return n==="dark"?Th(Ws(t!=null?t:{},r!=null?r:{})):Sh(t)},Eh=e=>Wi(e),Eo=(e,n)=>{var o;let t=Hs(n),r=Eh(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Ri=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Da())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Da());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as Mh}from"idiomorph";var Na=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Mh.morph(e,n.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 Fa={index:-1,draft:""};function Kp(e){let{direction:n,history:t,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(t.length===0)return{handled:!1,state:o};if(n==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<t.length-1){let i=o.index+1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...Fa}}}function Jp(e,n){var t,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=(t=e.content)==null?void 0:t.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:"",n].join("\0")}function Gp(){return new Map}function Xp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Qp(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Yp(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Oa(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Bs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ds(e,n){return Bs(e)-e.scrollTop<=n}function _a(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=t-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!n&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:n&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function $a(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>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"},kh=["pre","code","a","script","style"],ja=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Ns.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t: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}},eu=[{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 eu)Fs.set(e.name,e);var Lh=e=>{Fs.set(e.name,e)},Ph=e=>{eu.some(n=>n.name===e)||Fs.delete(e)},Ih=()=>Array.from(Fs.keys()),Os=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Fs.get(e))!=null?r:null},Ua=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
|
|
15
|
+
`);return o<0?"":e.slice(0,o)}return e},Wh=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},Rh=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${t}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=n,s},Hi=/\s/,Hh=(e,n)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(n.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Bh=(e,n,t)=>{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(Hi.test(o[i])){let l=i;for(;l<o.length&&Hi.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&&!Hi.test(o[p]);)l.appendChild(Wh(r,o[p],n,t.value)),t.value+=1,p+=1;a.appendChild(l),i=p}s.replaceChild(a,e)},Dh=(e,n,t)=>{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(Rh(r,l,n,t.value)),t.value+=1));s.replaceChild(a,e)},_s=(e,n,t,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:kh).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Hh(d,o)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=n==="char"?Bh:Dh;for(let u of i)p(u,t,l);return s.innerHTML},qa=(e=document)=>{let n=e.createElement("span");return n.className="persona-stream-caret",n.setAttribute("aria-hidden","true"),n.setAttribute("data-preserve-animation","stream-caret"),n},$s=(e=document)=>{let n=e.createElement("div");n.className="persona-stream-skeleton",n.setAttribute("data-preserve-animation","stream-skeleton"),n.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",n.appendChild(t),n},Zp=new WeakMap,Nh=(e,n)=>{var o;if(!e.styles)return;let t=Zp.get(n);if(t||(t=new Set,Zp.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let s=(n instanceof ShadowRoot?n.ownerDocument:(o=n.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,n.appendChild(s)},Bi=new WeakMap,Fh=(e,n)=>{if(!e.onAttach)return;let t=Bi.get(n);if(t||(t=new Map,Bi.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},tu=e=>{let n=Bi.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},Di=(e,n)=>{Nh(e,n),Fh(e,n)};function Ni(e,n=fn){let t=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(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=s}}var js=0,to=null;function Fi(e=document){var t;if(js++,js===1){let r=e.body,o=((t=e.defaultView)!=null?t: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 n=!1;return()=>{var r;if(!n&&(n=!0,js=Math.max(0,js-1),js===0&&to)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=to.originalOverflow,s.style.position=to.originalPosition,s.style.top=to.originalTop,s.style.width=to.originalWidth,o.scrollTo(0,to.scrollY),to=null}}}var za={side:"right",width:"420px",animate:!0,reveal:"resize"},an=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},no=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="composer-bar"},yr=e=>{var t,r,s,o,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:za.side,width:(s=n==null?void 0:n.width)!=null?s:za.width,animate:(o=n==null?void 0:n.animate)!=null?o:za.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:za.reveal}};var br={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Us=(e,n)=>{let t=h("button");t.type="button",t.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: ${t.message}_`:r}var Is=class e{constructor(n={},t){this.config=n;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
|
-
`,t.addEventListener("click",n);let r=o=>{var P,W,L,w,I,F,_,B,j,z,oe,We,je,Ne;let a=(P=o.launcher)!=null?P:{},i=an(o),d=t.querySelector("[data-role='launcher-title']");if(d){let ge=(W=a.title)!=null?W:"Chat Assistant";d.textContent=ge,d.setAttribute("title",ge)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let ge=(L=a.subtitle)!=null?L:"Get answers fast";l.textContent=ge,l.setAttribute("title",ge)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=t.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 be=parseFloat(ge)||24,Le=ye(a.agentIconName,be*.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=(F=a.agentIconText)!=null?F:"\u{1F4AC}",m.style.display="")}let g=t.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=t.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 be=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,be=(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-be,8),ee=ye(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&&yr[a.position]?yr[a.position]:yr["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",T="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";t.className=i?T:`${x} ${v}`,i||(t.style.zIndex=String((oe=a.zIndex)!=null?oe:fn));let A="1px solid var(--persona-border, #e5e7eb)",R="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(We=a.border)!=null?We:A,t.style.boxShadow=(je=a.shadow)!=null?je:R,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Ne=a.collapsedMaxWidth)!=null?Ne:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Oh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Va=(e,n={})=>{var x,T,A,R,P,W;let{showClose:t=!0,wrapperClassName:r=Oh,buttonSize:s,iconSize:o="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(T=s!=null?s:a.closeButtonSize)!=null?T:"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=(A=a.closeButtonTooltipText)!=null?A:"Close chat",m=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",p),l.style.display=t?"":"none";let g=(P=a.closeButtonIconName)!=null?P:"x",u=(W=a.closeButtonIconText)!=null?W:"\xD7";l.style.color=a.closeButtonColor||En.actionIconColor;let v=ye(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 L=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${L} 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 L=null,w=()=>{if(L)return;let F=l.ownerDocument,_=F.body;if(!_)return;L=Sr(F,"div","persona-clear-chat-tooltip"),L.textContent=p;let B=Sr(F,"div");B.className="persona-clear-chat-tooltip-arrow",L.appendChild(B);let j=l.getBoundingClientRect();L.style.position="fixed",L.style.zIndex=String(eo),L.style.left=`${j.left+j.width/2}px`,L.style.top=`${j.top-8}px`,L.style.transform="translate(-50%, -100%)",_.appendChild(L)},I=()=>{L&&L.parentNode&&(L.parentNode.removeChild(L),L=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}},Fh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ka=(e,n={})=>{var L,w,I,F,_,B,j,z,oe,We,je,Ne,ge;let{wrapperClassName:t=Fh,buttonSize:r,iconSize:s="20px"}=n,a=(w=((L=e==null?void 0:e.launcher)!=null?L:{}).clearChat)!=null?w:{},i=(I=r!=null?r:a.size)!=null?I:"32px",d=(F=a.iconName)!=null?F:"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:"",T=(Ne=a.tooltipText)!=null?Ne:"Clear chat",A=(ge=a.showTooltip)!=null?ge:!0,R=h("div",t),P=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");P.style.height=i,P.style.width=i,P.type="button",P.setAttribute("aria-label",T),P.style.color=l||En.actionIconColor;let W=ye(d,s,"currentColor",1);if(W&&(W.style.display="block",P.appendChild(W)),p&&(P.style.backgroundColor=p,P.classList.remove("hover:persona-bg-gray-100")),m||g){let be=m||"0px",Le=g||"transparent";P.style.border=`${be} solid ${Le}`,P.classList.remove("persona-border-none")}if(u&&(P.style.borderRadius=u,P.classList.remove("persona-rounded-full")),v&&(P.style.paddingLeft=v,P.style.paddingRight=v),x&&(P.style.paddingTop=x,P.style.paddingBottom=x),R.appendChild(P),A&&T){let be=null,Le=()=>{if(be)return;let ee=P.ownerDocument,Pe=ee.body;if(!Pe)return;be=Sr(ee,"div","persona-clear-chat-tooltip"),be.textContent=T;let V=Sr(ee,"div");V.className="persona-clear-chat-tooltip-arrow",be.appendChild(V);let le=P.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(eo),be.style.left=`${le.left+le.width/2}px`,be.style.top=`${le.top-8}px`,be.style.transform="translate(-50%, -100%)",Pe.appendChild(be)},He=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};R.addEventListener("mouseenter",Le),R.addEventListener("mouseleave",He),P.addEventListener("focus",Le),P.addEventListener("blur",He),R._cleanupTooltip=()=>{He(),R.removeEventListener("mouseenter",Le),R.removeEventListener("mouseleave",He),P.removeEventListener("focus",Le),P.removeEventListener("blur",He)}}return{button:P,wrapper:R}};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 L,w,I,F,_,B,j,z,oe,We,je,Ne,ge,be,Le,He;let{config:n,showClose:t=!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=(L=n==null?void 0:n.launcher)!=null?L:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(I=s.closeButtonPlacement)!=null?I:"inline",i=(F=s.headerIconHidden)!=null?F:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(o)||24,Pe=ye(d,ee*.6,"currentColor",1);Pe?l.replaceChildren(Pe):l.textContent=(B=(_=n==null?void 0:n.launcher)==null?void 0:_.agentIconText)!=null?B:"\u{1F4AC}"}else if((j=n==null?void 0:n.launcher)!=null&&j.iconUrl){let ee=h("img");ee.src=n.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=n==null?void 0:n.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=n==null?void 0:n.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=n==null?void 0:n.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=(be=s.clearChat)!=null?be:{},v=(Le=u.enabled)!=null?Le:!0,x=(He=u.placement)!=null?He:"inline",T=null,A=null;if(v){let Pe=Ka(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=Pe.button,A=Pe.wrapper,x==="top-right"&&(A.style.right="48px"),x==="inline"&&r.appendChild(A)}let R=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:P,wrapper:W}=Va(n,{showClose:t,wrapperClassName:R});return a!=="top-right"&&r.appendChild(W),{header:r,iconHolder:l,headerTitle:m,headerSubtitle:g,closeButton:P,closeButtonWrapper:W,clearChatButton:T,clearChatButtonWrapper:A}},Go=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.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(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Mo(e){let{items:n,onSelect:t,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 n){if(u.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}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 T=ye(u.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",T=>{T.stopPropagation(),p(),t(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:n,label:t,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",t),d.title=t;let l=ye(n,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 Ja(e){let{icon:n,label:t,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",t),n){let g=ye(n,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=h("span");if(m.textContent=t,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))p.setAttribute(g,u);return p}function Ga(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of n){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 Fi(e){var u,v;let{label:n,icon:t="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",n);let p=h("span","persona-combo-btn-label");p.textContent=n,l.appendChild(p);let m=ye(t,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,T;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(T=d.border)!=null?T:""}),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 T=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",T?"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 nu=e=>{var r;let n=ro({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function _h(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){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=ye(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=>t==null?void 0:t(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",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var ru=e=>{var R,P,W,L,w,I,F,_,B;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(R=n==null?void 0:n.launcher)!=null?R:{},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=Fi({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=En.titleColor,p=(W=l.querySelector(".persona-combo-btn-label"))!=null?W: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=(L=a.title)!=null?L:"Chat Assistant",l.appendChild(p),_h(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=(F=j.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var 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=t?"":"none",u.style.color=a.closeButtonColor||En.actionIconColor;let v=(B=a.closeButtonIconName)!=null?B:"x",x=ye(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let T=h("div");T.style.display="none";let A=h("span");return A.style.display="none",{header:i,iconHolder:T,headerTitle:p,headerSubtitle:A,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},_i={default:nu,minimal:ru},ou=e=>{var n;return(n=_i[e])!=null?n:_i.default},qs=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.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=n==null?void 0:n.layout)!=null?a:"default",o=ou(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Xa=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},Qa=e=>{var L,w,I,F,_,B,j,z,oe,We,je,Ne;let n=(L=e==null?void 0:e.sendButton)!=null?L:{},t=(w=n.useIcon)!=null?w:!1,r=(I=n.iconText)!=null?I:"\u2191",s=n.iconName,o=(F=n.stopIconName)!=null?F:"square",a=(_=n.tooltipText)!=null?_:"Send message",i=(B=n.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=n.showTooltip)!=null?je:!1,m=(Ne=n.size)!=null?Ne:"40px",g=n.backgroundColor,u=n.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",t?"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 T=null,A=null;if(t){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,be=(u==null?void 0:u.trim())||"currentColor";s?(T=ye(s,ge,be,2),T?x.appendChild(T):x.textContent=r):x.textContent=r,A=ye(o,ge,be,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");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let R=null;p&&a&&(R=h("div","persona-send-button-tooltip"),R.textContent=a,v.appendChild(R)),x.setAttribute("aria-label",a),v.appendChild(x);let P="send";return{button:x,wrapper:v,setMode:ge=>{if(ge===P)return;P=ge;let be=ge==="stop"?i:a;if(x.setAttribute("aria-label",be),R&&(R.textContent=be),t){if(T&&A){let Le=ge==="stop"?A:T;x.replaceChildren(Le)}}else x.textContent=ge==="stop"?l:d}}},Ya=e=>{var R,P,W,L,w,I,F,_,B,j,z,oe;let n=(R=e==null?void 0:e.voiceRecognition)!=null?R:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((P=n.provider)==null?void 0:P.type)==="runtype";if(!(r||s))return null;let a=(L=(W=e==null?void 0:e.sendButton)==null?void 0:W.size)!=null?L:"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=n.iconName)!=null?w:"mic",p=(I=n.iconSize)!=null?I:a,m=parseFloat(p)||24,g=(_=n.backgroundColor)!=null?_:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,u=(j=n.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=ye(l,m,u||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let T=(z=n.tooltipText)!=null?z:"Start voice recognition";if(((oe=n.showTooltip)!=null?oe:!1)&&T){let We=h("div","persona-send-button-tooltip");We.textContent=T,i.appendChild(We)}return{button:d,wrapper:i}},Za=e=>{var v,x,T,A,R,P,W,L;let n=(v=e==null?void 0:e.attachments)!=null?v:{};if(n.enabled!==!0)return null;let t=(T=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?T:"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=((A=n.allowedTypes)!=null?A:Nr).join(","),s.multiple=((R=n.maxFiles)!=null?R: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",(P=n.buttonTooltipText)!=null?P:"Attach file");let i=(W=n.buttonIconName)!=null?W:"paperclip",d=t,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=ye(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=(L=n.buttonTooltipText)!=null?L:"Attach file",u=h("div","persona-send-button-tooltip");return u.textContent=g,o.appendChild(u),{button:a,wrapper:o,input:s,previewsContainer:r}},ei=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.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},ti=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var zs=e=>{var v,x,T,A,R,P;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=ti(),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}=Xa(n);a();let i=Qa(n),d=Ya(n),l=Za(n),p=ei(n);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",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(l==null?void 0:l.button)&&W.target!==(l==null?void 0:l.wrapper)&&o.focus()}),t.append(r,s,p),{footer:t,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:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var su=()=>{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 n=h("span","persona-pill-peek__icon"),t=ye("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=ye("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},au=e=>{var v,x,T,A,R,P;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=ti();r.style.display="none";let s=ei(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=Xa(n);o.style.maxHeight="100px",a();let i=Qa(n),d=Ya(n),l=Za(n);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",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(l==null?void 0:l.button)&&W.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(m,o,g),l&&t.append(l.previewsContainer),t.append(p,r,s);let u=p;return{footer:t,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:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var iu=e=>{var p,m,g,u,v,x,T,A,R,P,W,L,w,I,F,_,B;let n=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,t=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((T=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?T: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=(A=j.expandedSize)!=null?A:"anchored",We.style.zIndex=String((P=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?P:fn),{wrapper:z,panel:oe,pillRoot:We}}if(t){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(!n){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=(L=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?L:"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&&yr[s.position]?yr[s.position]:yr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((F=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?F: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}},$h=(e,n)=>{var W,L,w,I,F,_,B,j,z;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Va(e,{showClose:n,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=(L=(W=e==null?void 0:e.launcher)==null?void 0:W.clearChat)==null?void 0:L.enabled)!=null?w:!0,a=null,i=null;if(o){let oe=Ka(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=(F=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?F:"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 T=h("div","persona-composer-overlay persona-pointer-events-none");T.setAttribute("data-persona-composer-overlay",""),T.style.position="absolute",T.style.left="0",T.style.right="0",T.style.bottom="0",T.style.zIndex="20";let A=au({config:e}),{root:R,textNode:P}=su();return t.append(d,s,l,T),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:u,composerOverlay:T,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.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:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:R,peekTextNode:P}},lu=(e,n=!0)=>{var T,A,R,P,W,L,w,I,F;if(no(e))return $h(e,n);let t=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");t.setAttribute("data-persona-theme-zone","container");let r=(T=e==null?void 0:e.layout)==null?void 0:T.header,s=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,o=r?qs(e,r,{showClose:n}):ro({config:e,showClose:n}),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=(P=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?P:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(L=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?L:"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=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;s?Go(t,o,e):(o.header.style.display="none",Go(t,o,e)),t.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"),t.append(u.footer),t.append(x),{container:t,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 jh=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}},Uh=(e,n)=>{if(!e)return null;let t=jh(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},qh=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},zh=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},$i=e=>{let n=e.toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:text/html")||n.startsWith("data:text/javascript")||n.startsWith("data:text/xml")||n.startsWith("data:application/xhtml")||n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:")||!e.includes(":"))},ji=320,du=320,Vh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Kh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),Jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),Gh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),Xh=(e,n,t)=>{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"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};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=`${ji}px`,l.style.maxHeight=`${du}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}),zh(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 t==null||t(),null}},Qh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(r=>{if(!$i(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=`${ji}px`,n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Yh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","video");let t=0;return e.forEach(r=>{if(!$i(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=`${ji}px`,s.style.maxHeight=`${du}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Zh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","files");let t=0;return e.forEach(r=>{if(!$i(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",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}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 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="0ms";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="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(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},pu=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Xo};if(n){let s=n(r);if(s!==null)return s}return Xo()},eb=(e,n)=>{let t=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=n==="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=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},cu=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},tb=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.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 t},uu=(e,n,t)=>{var u,v,x,T,A,R;let r=(u=n.showCopy)!=null?u:!0,s=(v=n.showUpvote)!=null?v:!0,o=(x=n.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let P=h("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let a=(T=n.visibility)!=null?T:"hover",i=(A=n.align)!=null?A:"right",d=(R=n.layout)!=null?R:"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=(P,W,L)=>{let w=qt({icon:P,label:W,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",L),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,n,t,r,s,o)=>{var ee,Pe,V,le,ve,fe,we,ze,Q,te,se,ue,ie,re,Qe,Ie,ce;let a=t!=null?t:{},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=tb(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 T=Vh(e),A=(we=(fe=e.content)==null?void 0:fe.trim())!=null?we:"",P=T.length>0&&A===La,W=ja((Q=(ze=o==null?void 0:o.widgetConfig)==null?void 0:ze.features)==null?void 0:Q.streamAnimation),L=(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"&&W.type!=="none"?Fs(W.type,L):null,I=e.role==="assistant"&&((ie=w==null?void 0:w.isAnimating)==null?void 0:ie.call(w,e))===!0,F=e.role==="assistant"&&w!==null&&(!!e.streaming||I);F&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),F&&w&&(w.containerClass&&_.classList.add(w.containerClass),_.style.setProperty("--persona-stream-step",`${W.speed}ms`),_.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let B=F?Ua((re=e.content)!=null?re:"",W.buffer,w,e,!!e.streaming):(Qe=e.content)!=null?Qe:"",j=n({text:B,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=j;F&&(w==null?void 0:w.wrap)==="char"?z=_s(j,"char",e.id,{skipTags:w.skipTags}):F&&(w==null?void 0:w.wrap)==="word"&&(z=_s(j,"word",e.id,{skipTags:w.skipTags}));let oe=null;if(P?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",_.appendChild(oe)):_.innerHTML=z,F&&(w!=null&&w.useCaret)&&!P&&A){let G=qa(),_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=cu(e,l);G.classList.add("persona-ml-2","persona-inline"),_.appendChild(G)}if(T.length>0){let G=Xh(T,!P&&!!A,()=>{P&&oe&&(oe.style.display="")});G?x.appendChild(G):P&&oe&&(oe.style.display="")}let We=Kh(e);if(We.length>0){let G=Qh(We);G&&x.appendChild(G)}let je=Jh(e);if(je.length>0){let G=Yh(je);G&&x.appendChild(G)}let Ne=Gh(e);if(Ne.length>0){let G=Zh(Ne);G&&x.appendChild(G)}if(x.appendChild(_),m&&u==="below"&&e.createdAt){let G=cu(e,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let ge=e.role==="assistant"?Uh(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=W.placeholder==="skeleton",Et=_e&&W.buffer==="line"&&G;if(G)Et&&x.appendChild($s());else if(_e)x.appendChild($s());else{let de=pu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);de&&x.appendChild(de)}}if(ge&&e.stopReason&&!e.streaming&&(A||(_.style.display="none"),x.appendChild(qh(e.stopReason,ge))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let G=uu(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=eb(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},nb=(e,n,t,r,s,o)=>{let a=t!=null?t:{};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,n,t,r,s,o)};var Qo=new Set,rb=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),ob=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
|
|
24
|
-
`):""},mu=(e,n)=>{let t=Qo.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"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=
|
|
23
|
+
`,t.addEventListener("click",n);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=t.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=t.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=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=t.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=t.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=t.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";t.className=i?C:`${x} ${v}`,i||(t.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))";t.style.border=(We=a.border)!=null?We:T,t.style.boxShadow=(je=a.shadow)!=null?je:H,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Ne=a.collapsedMaxWidth)!=null?Ne:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Oh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Va=(e,n={})=>{var x,C,T,H,L,P;let{showClose:t=!0,wrapperClassName:r=Oh,buttonSize:s,iconSize:o="28px"}=n,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=t?"":"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",Ka=(e,n={})=>{var W,w,I,O,_,B,j,z,oe,We,je,Ne,ge;let{wrapperClassName:t=_h,buttonSize:r,iconSize:s="20px"}=n,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",t),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:n,showClose:t=!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=n==null?void 0:n.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=(_=n==null?void 0:n.launcher)==null?void 0:_.agentIconText)!=null?B:"\u{1F4AC}"}else if((j=n==null?void 0:n.launcher)!=null&&j.iconUrl){let ee=h("img");ee.src=n.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=n==null?void 0:n.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=n==null?void 0:n.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=n==null?void 0:n.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=Ka(n,{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}=Va(n,{showClose:t,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,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.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(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Mo(e){let{items:n,onSelect:t,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 n){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(),t(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:n,label:t,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",t),d.title=t;let l=be(n,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 Ja(e){let{icon:n,label:t,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",t),n){let g=be(n,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=h("span");if(m.textContent=t,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))p.setAttribute(g,u);return p}function Ga(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of n){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 Oi(e){var u,v;let{label:n,icon:t="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",n);let p=h("span","persona-combo-btn-label");p.textContent=n,l.appendChild(p);let m=be(t,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 nu=e=>{var r;let n=ro({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function $h(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){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=>t==null?void 0:t(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",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var ru=e=>{var H,L,P,W,w,I,O,_,B;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(H=n==null?void 0:n.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=Oi({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),$h(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=t?"":"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:nu,minimal:ru},ou=e=>{var n;return(n=_i[e])!=null?n:_i.default},qs=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.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=n==null?void 0:n.layout)!=null?a:"default",o=ou(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Xa=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},Qa=e=>{var W,w,I,O,_,B,j,z,oe,We,je,Ne;let n=(W=e==null?void 0:e.sendButton)!=null?W:{},t=(w=n.useIcon)!=null?w:!1,r=(I=n.iconText)!=null?I:"\u2191",s=n.iconName,o=(O=n.stopIconName)!=null?O:"square",a=(_=n.tooltipText)!=null?_:"Send message",i=(B=n.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=n.showTooltip)!=null?je:!1,m=(Ne=n.size)!=null?Ne:"40px",g=n.backgroundColor,u=n.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",t?"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(t){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");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.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),t){if(C&&T){let Le=ge==="stop"?T:C;x.replaceChildren(Le)}}else x.textContent=ge==="stop"?l:d}}},Ya=e=>{var H,L,P,W,w,I,O,_,B,j,z,oe;let n=(H=e==null?void 0:e.voiceRecognition)!=null?H:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((L=n.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=n.iconName)!=null?w:"mic",p=(I=n.iconSize)!=null?I:a,m=parseFloat(p)||24,g=(_=n.backgroundColor)!=null?_:(O=e==null?void 0:e.sendButton)==null?void 0:O.backgroundColor,u=(j=n.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),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let C=(z=n.tooltipText)!=null?z:"Start voice recognition";if(((oe=n.showTooltip)!=null?oe:!1)&&C){let We=h("div","persona-send-button-tooltip");We.textContent=C,i.appendChild(We)}return{button:d,wrapper:i}},Za=e=>{var v,x,C,T,H,L,P,W;let n=(v=e==null?void 0:e.attachments)!=null?v:{};if(n.enabled!==!0)return null;let t=(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=n.allowedTypes)!=null?T:Nr).join(","),s.multiple=((H=n.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=n.buttonTooltipText)!=null?L:"Attach file");let i=(P=n.buttonIconName)!=null?P:"paperclip",d=t,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=n.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}},ei=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.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},ti=()=>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:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=ti(),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}=Xa(n);a();let i=Qa(n),d=Ya(n),l=Za(n),p=ei(n);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()}),t.append(r,s,p),{footer:t,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 su=()=>{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 n=h("span","persona-pill-peek__icon"),t=be("message-square",16,"currentColor",1.5);t&&n.appendChild(t);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(n,r,s),{root:e,textNode:r}},au=e=>{var v,x,C,T,H,L;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=ti();r.style.display="none";let s=ei(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=Xa(n);o.style.maxHeight="100px",a();let i=Qa(n),d=Ya(n),l=Za(n);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&&t.append(l.previewsContainer),t.append(p,r,s);let u=p;return{footer:t,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 iu=e=>{var p,m,g,u,v,x,C,T,H,L,P,W,w,I,O,_,B;let n=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,t=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(t){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(!n){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}},jh=(e,n)=>{var P,W,w,I,O,_,B,j,z;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Va(e,{showClose:n,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=Ka(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=au({config:e}),{root:H,textNode:L}=su();return t.append(d,s,l,C),i&&t.appendChild(i),{container:t,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}},lu=(e,n=!0)=>{var C,T,H,L,P,W,w,I,O;if(no(e))return jh(e,n);let t=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");t.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:n}):ro({config:e,showClose:n}),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(t,o,e):(o.header.style.display="none",Go(t,o,e)),t.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"),t.append(u.footer),t.append(x),{container:t,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 Uh=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}},qh=(e,n)=>{if(!e)return null;let t=Uh(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},zh=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},Vh=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},$i=e=>{let n=e.toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:text/html")||n.startsWith("data:text/javascript")||n.startsWith("data:text/xml")||n.startsWith("data:application/xhtml")||n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:")||!e.includes(":"))},ji=320,du=320,Kh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),Gh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),Xh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),Qh=(e,n,t)=>{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"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};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=`${ji}px`,l.style.maxHeight=`${du}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}),Vh(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 t==null||t(),null}},Yh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(r=>{if(!$i(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=`${ji}px`,n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Zh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","video");let t=0;return e.forEach(r=>{if(!$i(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=`${ji}px`,s.style.maxHeight=`${du}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},ey=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","files");let t=0;return e.forEach(r=>{if(!$i(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",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}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 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="0ms";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="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(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},pu=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Xo};if(n){let s=n(r);if(s!==null)return s}return Xo()},ty=(e,n)=>{let t=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=n==="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=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},cu=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},ny=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.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 t},uu=(e,n,t)=>{var u,v,x,C,T,H;let r=(u=n.showCopy)!=null?u:!0,s=(v=n.showUpvote)!=null?v:!0,o=(x=n.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=n.visibility)!=null?C:"hover",i=(T=n.align)!=null?T:"right",d=(H=n.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,n,t,r,s,o)=>{var ee,Pe,V,le,ve,fe,we,ze,Q,te,se,ue,ie,re,Qe,Ie,ce;let a=t!=null?t:{},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=ny(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=Kh(e),T=(we=(fe=e.content)==null?void 0:fe.trim())!=null?we:"",L=C.length>0&&T===La,P=ja((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?Ua((re=e.content)!=null?re:"",P.buffer,w,e,!!e.streaming):(Qe=e.content)!=null?Qe:"",j=n({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=qa(),_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=cu(e,l);G.classList.add("persona-ml-2","persona-inline"),_.appendChild(G)}if(C.length>0){let G=Qh(C,!L&&!!T,()=>{L&&oe&&(oe.style.display="")});G?x.appendChild(G):L&&oe&&(oe.style.display="")}let We=Jh(e);if(We.length>0){let G=Yh(We);G&&x.appendChild(G)}let je=Gh(e);if(je.length>0){let G=Zh(je);G&&x.appendChild(G)}let Ne=Xh(e);if(Ne.length>0){let G=ey(Ne);G&&x.appendChild(G)}if(x.appendChild(_),m&&u==="below"&&e.createdAt){let G=cu(e,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let ge=e.role==="assistant"?qh(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=pu("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(zh(e.stopReason,ge))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let G=uu(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=ty(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},ry=(e,n,t,r,s,o)=>{let a=t!=null?t:{};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,n,t,r,s,o)};var Qo=new Set,oy=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),sy=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
|
|
24
|
+
`):""},mu=(e,n)=>{let t=Qo.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"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(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Ui=(e,n)=>{var je,Ne,ge,ye,Le,He,ee,Pe,V,le,ve;let t=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),!t)return r;let s=(Ne=(je=n==null?void 0:n.features)==null?void 0:je.reasoningDisplay)!=null?Ne:{},o=s.expandable!==!1,a=o&&Qo.has(e.id),i=t.status!=="complete",d=sy(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=n==null?void 0:n.reasoning)!=null?ye:{},v=String((Le=t.startedAt)!=null?Le:Date.now()),x=()=>{let fe=h("span","");return fe.setAttribute("data-tool-elapsed",v),fe.textContent=Ta(t),fe},C=(He=u.renderCollapsedSummary)==null?void 0:He.call(u,{message:e,reasoning:t,defaultSummary:g,previewText:d,isActive:i,config:n!=null?n:{},elapsed:Ta(t),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=Pp(t),p.appendChild(T);let H=(ee=s.loadingAnimation)!=null?ee:"none",L=u.activeTextTemplate,P=u.completeTextTemplate,W=i?L:P,w=C instanceof HTMLElement,I=(fe,we,ze)=>{let Q=ze;for(let te of we){let se=h("span","persona-tool-char");se.style.setProperty("--char-index",String(Q)),se.textContent=te===" "?"\xA0":te,fe.appendChild(se),Q++}return Q},O=(fe,we)=>{m.textContent="";let ze=Ea(fe,""),Q=0;for(let te of ze){let se=te.styles.length>0?(()=>{let ue=h("span",te.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(ue),ue})():m;if(te.isDuration&&i)se.appendChild(x());else{let ue=te.isDuration?Ta(t):te.text;we?Q=I(se,ue,Q):se.appendChild(document.createTextNode(ue))}}};if(!w&&W)if(T.style.display="none",m.style.display="",i&&H!=="none"){let fe=(Pe=u.loadingAnimationDuration)!=null?Pe:2e3;m.setAttribute("data-preserve-animation","true"),H==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),O(W,!1)):(m.classList.add(`persona-tool-loading-${H}`),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),H==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),O(W,!0))}else O(W,!1);else if(!w&&i&&H!=="none"){m.style.display="";let fe=(V=u.loadingAnimationDuration)!=null?V:2e3;if(m.setAttribute("data-preserve-animation","true"),H==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`);else{m.classList.add(`persona-tool-loading-${H}`),m.style.setProperty("--persona-tool-anim-duration",`${fe}ms`),H==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let we=m.textContent||g;m.textContent="",I(m,we,0)}t.status==="complete"&&(m.style.display="none")}else w||(t.status==="complete"?m.style.display="none":m.style.display="");let _=null;if(o){_=h("div","persona-flex persona-items-center");let we=be(a?"chevron-up":"chevron-down",16,"currentColor",2);we?_.appendChild(we):_.textContent=a?"Hide":"Show";let ze=h("div","persona-flex persona-items-center persona-ml-auto");ze.append(_),l.append(p,ze)}else l.append(p);let B=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","reasoning"),B.style.display="none",B.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let fe=(ve=(le=n==null?void 0:n.reasoning)==null?void 0:le.renderCollapsedPreview)==null?void 0:ve.call(le,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});oy(B,fe)||(B.textContent=d),B.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,B),r;let j=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let z=t.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=z||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),_){_.innerHTML="";let we=be(a?"chevron-up":"chevron-down",16,"currentColor",2);we?_.appendChild(we):_.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",B.style.display=a?"none":B.textContent||B.childNodes.length?"":"none"})(),r.append(l,B,j),r};var Yo=new Set,ay=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),iy=(e,n)=>{var o;let t=e.toolCall;if(!t)return"";let r=((o=t.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
|
|
25
25
|
`);let s=Uo(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
|
|
26
|
-
`):""},ib=(e,n)=>{var p,m,g,u,v;let t=e.toolCall,r=(p=n==null?void 0:n.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=ab(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=t?Ip(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(u=n==null?void 0:n.toolCall)!=null?u:{},l=a;return s==="tool-name"?l=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Ci(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ci(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},gu=(e,n,t)=>{var p;let r=Yo.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.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=ye(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")},qi=(e,n)=>{var z,oe,We,je,Ne,ge,be,Le,He;let t=e.toolCall,r=(z=n==null?void 0:n.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),!t)return s;let o=(We=(oe=n==null?void 0:n.features)==null?void 0:oe.toolCallDisplay)!=null?We:{},a=o.expandable!==!1,i=a&&Yo.has(e.id),{summary:d,previewText:l,isActive:p}=ib(e,n),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=t.startedAt)!=null?je:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",v),ee.textContent=ks(t),ee},T=(ge=r.renderCollapsedSummary)==null?void 0:ge.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Ne=o.collapsedMode)!=null?Ne:"tool-call",isActive:p,config:n!=null?n:{},elapsed:ks(t),createElapsedElement:x});typeof T=="string"&&T.trim()?(u.textContent=T,g.appendChild(u)):T instanceof HTMLElement?g.appendChild(T):(u.textContent=d,g.appendChild(u));let A=(be=o.loadingAnimation)!=null?be:"none",R=r.activeTextTemplate,P=r.completeTextTemplate,W=p?R:P,L=T 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=t.name)==null?void 0:fe.trim())||"tool",le=Ea(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(t):we.text;Pe?ve=w(ze,Q,ve):ze.appendChild(document.createTextNode(Q))}}};if(!L)if(p&&A!=="none"){let ee=(Le=r.loadingAnimationDuration)!=null?Le:2e3;if(u.setAttribute("data-preserve-animation","true"),A==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),W&&I(W,!1);else if(u.classList.add(`persona-tool-loading-${A}`),u.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),A==="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)),W)I(W,!0);else{let Pe=u.textContent||d;u.textContent="",w(u,Pe,0)}}else W&&I(W,!1);let F=null;if(a){F=h("div","persona-flex persona-items-center");let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Pe=ye(i?"chevron-up":"chevron-down",16,ee,2);Pe?F.appendChild(Pe):F.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append(F),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:t,defaultPreview:l,isActive:p,config:n!=null?n:{}});sb(_,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),t.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=t.name,B.appendChild(ee)}if(t.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(t.args),ee.append(Pe,V),B.appendChild(ee)}if(t.chunks&&t.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=t.chunks.join(""),ee.append(Pe,V),B.appendChild(ee)}if(t.status==="complete"&&t.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(t.result),ee.append(Pe,V),B.appendChild(ee)}if(t.status==="complete"&&typeof t.duration=="number"){let ee=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ee.style.color=r.contentTextColor),ee.textContent=`Duration: ${t.duration}ms`,B.appendChild(ee)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Pe=ye(i?"chevron-up":"chevron-down",16,ee,2);Pe?F.appendChild(Pe):F.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 lb,ARR as cb,OBJ as db,STR as pb}from"partial-json";var hu="ask_user_question",zi=8,Zo="data-persona-ask-sheet-for",ub="Other",mb="Other\u2026",bu="Type your own answer here",yu="Send",gb="Next",fb="Back",hb="Submit all",bb="Skip",yb=3,Vi="data-ask-current-index",Ki="data-ask-question-count",xu="data-ask-answers",Ji="data-ask-grouped",vu="data-ask-layout",xb=e=>e.layout==="pills"?"pills":"rows",vb=e=>e.getAttribute(vu)==="pills"?"pills":"rows",fu=!1,wu=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===hu,ni=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},so=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=lb(s,pb|db|cb);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},Ks=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>zi&&!fu&&(fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${zi}.`)),n.slice(0,zi)},wb=e=>{var n;return(n=Ks(e)[0])!=null?n:null},Cb=(e,n)=>{var t;return(t=Ks(e)[n])!=null?t:null},Cu=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Au=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},Ab=(e,n,t,r)=>{let o=h("button",t==="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(n)),o.setAttribute("data-option-label",e.label),t==="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=Au(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Sb=e=>{let t=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 t.setAttribute("aria-hidden","true"),t},Tb=(e,n,t,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&&!t){for(let u=0;u<yb;u++)o.appendChild(Sb(r));return o}if(d.forEach((u,v)=>{o.appendChild(Ab(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?ub:mb;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"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(p=n.freeTextPlaceholder)!=null?p:bu,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(m=n.freeTextLabel)!=null?m:u),x.appendChild(T),v.appendChild(x);let A=Au(r,a,d.length);A&&v.appendChild(A),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=n.freeTextLabel)!=null?g:u,o.appendChild(v)}}return o},Su=(e,n)=>{var o,a;let r=h("div",n==="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),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:yu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Eb=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:yu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},Mb=(e,n,t)=>{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=t.backLabel)!=null?l:fb,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=t.skipLabel)!=null?p:bb,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===n-1;return i.textContent=d?(m=t.submitAllLabel)!=null?m:hb:(g=t.nextLabel)!=null?g:gb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},ko=e=>{let n=e.getAttribute(xu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Tu=(e,n)=>{e.setAttribute(xu,JSON.stringify(n))},ar=e=>{var t;let n=Number((t=e.getAttribute(Vi))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},kb=(e,n)=>{e.setAttribute(Vi,String(Math.max(0,Math.floor(n))))},es=e=>{var t;let n=Number((t=e.getAttribute(Ki))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},ao=e=>e.getAttribute(Ji)==="true",Lb=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Pb=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},ri=(e,n)=>{let{payload:t}=so(n),r=Ks(t),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},Eu=e=>{let n=ko(e),t=ar(e),r=n[t],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=""},Mu=e=>{if(!ao(e))return;let n=ko(e),t=ar(e),r=n[t],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}},Gi=(e,n,t)=>{let r=ni(t),s=vb(e),{payload:o,complete:a}=so(n),i=ao(e),d=ar(e),l=es(e),p=i?Cb(o,d):wb(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 R=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=R,v.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let R=Tb(p,r,a,s);x.replaceWith(R)}if(s!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Su(r,s))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!T?e.appendChild(Eb(r)):(!m||i)&&T&&T.remove(),e.setAttribute("data-multi-select",m?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=Mb(d,l,r);A?A.replaceWith(R):e.appendChild(R)}else A&&A.remove();Eu(e),Mu(e)},Ib=(e,n,t)=>{let r=ni(n),s=xb(r),o=e.toolCall.id,a=Ks(t),i=Math.max(1,a.length),d=i>1,l=Lb(e,a),p=d?Pb(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(Ki,String(i)),m.setAttribute(Vi,String(p)),m.setAttribute(Ji,d?"true":"false"),m.setAttribute(vu,s),Tu(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`),Cu(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 T=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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),m.appendChild(T),s!=="rows"&&m.appendChild(Su(r,s)),Gi(m,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Wb=(e,n,t)=>{let{payload:r}=so(n),s=Math.max(1,Ks(r).length);s>es(e)&&(e.setAttribute(Ki,String(s)),s>1&&!ao(e)&&e.setAttribute(Ji,"true")),Gi(e,n,t)},Rb=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=ni(n);Cu(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=so(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},Js=(e,n,t)=>{if(!t||!oo(e)||ni(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${Zo}]`).forEach(l=>{l.getAttribute(Zo)!==s&&l.remove()});let a=t.querySelector(`[${Zo}="${wu(s)}"]`);if(a){Wb(a,e,n);return}let{payload:i}=so(e),d=Ib(e,n,i);t.appendChild(d)},Lo=(e,n)=>{if(!e)return;let t=n?`[${Zo}="${wu(n)}"]`:`[${Zo}]`;e.querySelectorAll(t).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)})},Xi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),io=(e,n)=>{let t=ko(e),r=ar(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,Tu(e,t),Eu(e),Mu(e)},oi=(e,n,t,r)=>{let s=es(e),o=Math.max(0,Math.min(s-1,r));kb(e,o),Gi(e,n,t)};var Qi=(e,n)=>{var x,T,A,R,P,W,L,w,I,F,_,B;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.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=(T=r==null?void 0:r.borderColor)!=null?T:"var(--persona-approval-border, #fef08a)",!t)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=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(A=r==null?void 0:r.titleColor)!=null?A:"currentColor",p=ye(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=(R=r==null?void 0:r.title)!=null?R:"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",t.status),t.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"):t.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"):t.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=t.description,m.appendChild(v),t.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(t.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=(P=r==null?void 0:r.approveButtonColor)!=null?P:"var(--persona-approval-approve-bg, #22c55e)",z.style.color=(W=r==null?void 0:r.approveButtonTextColor)!=null?W:"#ffffff",z.setAttribute("data-approval-action","approve");let oe=ye("shield-check",14,(L=r==null?void 0:r.approveButtonTextColor)!=null?L:"#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=(F=r==null?void 0:r.denyButtonTextColor)!=null?F:"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=ye("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 ku=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.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),n.push(v)}),e.appendChild(p)}}};var Gs=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}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 n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)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=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{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,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};var Hb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Bb=new Set(["step_start","execution_start"]),Db=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Nb=new Set(["step_complete","agent_turn_complete"]),Ob=new Set(["flow_complete","agent_complete"]),Lu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Iu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Po=(e,n)=>{let t=e[n];return Iu(t)?t:void 0};function Yi(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function si(e,n){if(!(e<=0||n===void 0||n<250))return e/(n/1e3)}function Fb(e,n){return typeof n.type=="string"?n.type:e}function _b(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 $b(e,n){return e==="step_delta"||e==="step_chunk"?n.stepType!=="tool"&&n.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof n.contentType=="string"?n.contentType:typeof n.content_type=="string"?n.content_type:void 0)==="text"}function Pu(e){var r,s,o,a,i;let n=Po(e,"result"),t=[Po(e,"tokens"),Po(e,"totalTokens"),n?Po(n,"tokens"):void 0,Po(e,"usage"),n?Po(n,"usage"):void 0];for(let d of t){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:n?(a=Gn(n.outputTokens))!=null?a:Gn(n.completionTokens):void 0}function jb(e){var t,r,s,o,a;let n=Po(e,"result");return(a=(s=(r=(t=Gn(e.executionTime))!=null?t:Gn(e.executionTimeMs))!=null?r:Gn(e.execution_time))!=null?s:Gn(e.duration))!=null?a:n?(o=Gn(n.executionTime))!=null?o:Gn(n.executionTimeMs):void 0}function Ub(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(n=Ub){this.metric={status:"idle"};this.run=null;this.now=n}getMetric(){let n=this.run;if(n&&this.metric.status==="running"&&n.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-n.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:si(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(n){this.run={startedAt:n,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(n,t){var o;if(!Iu(t)){Lu.has(n)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Fb(n,t),s=this.now();if(Hb.has(r)){this.startRun(s);return}if(Bb.has(r)){this.run||this.startRun(s);return}if(Db.has(r)){if(!$b(r,t))return;let a=_b(t);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+Yi(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:si(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Nb.has(r)){if(!this.run)return;let a=this.run,i=Pu(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Yi(a.visibleCharCount),p=this.resolveDuration(a,t,s);this.metric={status:"running",tokensPerSecond:si(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Ob.has(r)){if(!this.run)return;let a=this.run,i=Pu(t),d=i!=null?i:a.exactOutputTokens+Yi(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,t,s);this.metric={status:"complete",tokensPerSecond:si(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Lu.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(n,t,r){let s=n.firstDeltaAt!==void 0?r-n.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=jb(t);return o!=null?o:r-n.startedAt}};function ts(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var qb={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)"}},zb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Vb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Kb=100;function Jb(e,n){let t={...qb,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return zb}function Gb(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Xb(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function Qb(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;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 Yb(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{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),t()})}function Zb(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function ey(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function ty(e){let n=[];return e.outputTokens!==void 0&&n.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&n.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&n.push(e.source),n.join(" \xB7 ")}function ny(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,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 Zi(e,n,t,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:n,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"),T=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&x.appendChild(T);let A=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),R=(z=r.timestampFormat)!=null?z:"relative";A.textContent=R==="relative"?Gb(e.timestamp,t):Xb(e.timestamp);let P=null;r.showSequenceNumbers!==!1&&(P=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(n+1));let W=Jb(e.type,r.badgeColors),L=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");L.style.backgroundColor=W.bg,L.style.color=W.text,L.style.borderColor=W.text+"50",L.textContent=e.type;let w=(oe=r.descriptionFields)!=null?oe:Vb,I=Qb(e.payload,w),F=null;I&&(F=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.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=ye("clipboard","12px","currentColor",1.5);return j&&B.appendChild(j),B.addEventListener("click",async We=>{We.stopPropagation(),await Yb(Zb(e)),B.innerHTML="";let je=ye("check","12px","currentColor",1.5);je&&B.appendChild(je),setTimeout(()=>{B.innerHTML="";let Ne=ye("clipboard","12px","currentColor",1.5);Ne&&B.appendChild(Ne)},1500)}),v.appendChild(x),v.appendChild(A),P&&v.appendChild(P),v.appendChild(L),F&&v.appendChild(F),v.appendChild(_),v.appendChild(B),u.appendChild(v),d&&u.appendChild(ny(e,a,i)),u}}function Wu(e){var v,x,T,A,R;let{buffer:n,getFullHistory:t,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=(T=i==null?void 0:i.label)!=null?T:"",m=(R=(A=s==null?void 0:s.features)==null?void 0:A.eventStream)!=null?R:{},g=o.find(P=>P.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let P=g.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>u().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return u();function u(){let P=m.classNames,W=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ts(W,P==null?void 0:P.panel);let L=[],w="",I="",F=null,_=[],B={},j=0,z=Fa(),oe=0,We=0,je=!1,Ne=null,ge=!1,be=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,P==null?void 0:P.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,bn=se,Dn=()=>{if(!bn.textContent)return;let xr=Qn.getBoundingClientRect(),Nn=ne.getBoundingClientRect();bn.style.left=`${xr.left-Nn.left}px`,bn.style.top=`${xr.bottom-Nn.top+4}px`,bn.style.display="block"},ut=()=>{bn.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=ye("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,P==null?void 0:P.searchBar);let bt=ye("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");bt&&zt.appendChild(bt),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,P==null?void 0:P.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=ye("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:n.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=ey(ne);let me=ty(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,P==null?void 0:P.scrollIndicator),_e.style.display="none",_e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Et=ye(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),W.setAttribute("tabindex","0"),W.appendChild(ie),W.appendChild(Qe),W.appendChild(ce);function Mn(){let ne=n.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 Ft(){let ne=n.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=n.getEvictedCount();ne>0?(Qe.textContent=`${ne.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",L=Ft();let me=L.length,vt=n.getSize()>0;le&&(le.textContent=String(n.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=n.getAll(),Zt=jt.length>0?jt[0].timestamp:0,hn=new Set(L.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&&L.length>0;if(St||wt||L.length===0){G.innerHTML="",He.clear();let ft=document.createDocumentFragment();for(let bt=0;bt<L.length;bt++){let zt=Zi(L[bt],bt,Zt,m,Le,Xn,o,s);He.set(L[bt].id,zt),ft.appendChild(zt)}G.appendChild(ft),ee=w,Pe=I,V=null}else{if(V!==null){let bt=He.get(V);if(bt&&bt.parentNode===G){let zt=L.findIndex(tt=>tt.id===V);if(zt>=0){let tt=Zi(L[zt],zt,Zt,m,Le,Xn,o,s);G.insertBefore(tt,bt),bt.remove(),He.set(V,tt)}}V=null}let ft=new Set(L.map(bt=>bt.id));for(let[bt,zt]of He)ft.has(bt)||(zt.remove(),He.delete(bt));for(let bt=0;bt<L.length;bt++){let zt=L[bt];if(!He.has(zt.id)){let tt=Zi(zt,bt,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>=Kb){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=ye(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=ye("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=L:t?(ne=await t(),ne.length===0&&(ne=n.getAll())):ne=n.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",F&&clearTimeout(F),F=setTimeout(()=>{I=we.value,Hn(),N()},150))},rt=()=>{!we||!ze||(we.value="",I="",ze.style.display="none",F&&clearTimeout(F),Hn(),N())},At=()=>{if(ge)return;let ne=G.scrollTop,{action:me,nextLastScrollTop:vt}=_a({following:z.isFollowing(),currentScrollTop:ne,lastScrollTop:be,nearBottom:Ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=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=$a({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(),W.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),W.addEventListener("keydown",Ye);function Dt(){F&&clearTimeout(F),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),W.removeEventListener("keydown",Ye)}return{element:W,update:Ae,destroy:Dt}}}function Ru(e,n){let t=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 ${t} 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=t;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 ${t}`,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 Hu=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){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=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>Ru(e,n)});if(p)return p}return Ru(e,n)};var el=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},lo=new el;lo.register("PersonaArtifactCard",Hu);function ry(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.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),n.appendChild(t),n.appendChild(r),n}function Bu(e,n){var ve,fe,we,ze;let t=(fe=(ve=e.features)==null?void 0:ve.artifacts)==null?void 0:fe.layout,s=((we=t==null?void 0:t.toolbarPreset)!=null?we:"default")==="document",o=(ze=t==null?void 0:t.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=n.onDismiss)==null||Q.call(n)});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=n.onDismiss)==null||Q.call(n)});let x="rendered",T=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),A=s?qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):qt({icon:"eye",label:"Rendered view"}),R=s?qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):qt({icon:"code-2",label:"Source"}),P=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),W=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,I=!!(L&&w&&w.length>0),F=null,_,B=null,j=null;if(s&&(W||L)&&!I){if(_=W?Ja({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let Q=ye("chevron-down",14,"currentColor",2);Q&&_.appendChild(Q)}}else s&&I?(F=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=W?Ja({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"}}),F.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=t==null?void 0:t.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=t==null?void 0:t.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:F!=null?F: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=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:Q.call(t))}catch{}V()}),oe.addEventListener("click",()=>{var Q;p(),(Q=n.onDismiss)==null||Q.call(n)});let Ne=()=>{s&&(A.setAttribute("aria-pressed",x==="rendered"?"true":"false"),R.setAttribute("aria-pressed",x==="source"?"true":"false"))};A.addEventListener("click",()=>{x="rendered",Ne(),V()}),R.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(),T.append(A,R),F?P.append(F,z,oe):P.append(_,z,oe),g.append(T,ge,P),Ne()):(g.appendChild(u),g.appendChild(v)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let be=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&&(be.style.paddingLeft=o,be.style.paddingRight=o,Le.style.padding=o),m.appendChild(g),m.appendChild(be),m.appendChild(Le);let He=[],ee=null,Pe=!1,V=()=>{var ue,ie,re,Qe;let Q=s&&He.length<=1;be.classList.toggle("persona-hidden",Q),be.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",()=>n.onSelect(Ie.id)),be.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(ry(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 n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function Du(e,n){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(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.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 oy(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 ai(e,n){var d,l,p,m,g,u,v,x,T,A;if(!ir(n)){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"),oy(e),Du(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=t==null?void 0:t.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=t==null?void 0:t.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=t==null?void 0:t.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=t==null?void 0:t.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=(T=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(A=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:A.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Du(e,n)}var Nu=["panel","seamless"];function ii(e,n){var i,d,l,p,m,g;for(let u of Nu)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(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=Nu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=t==null?void 0:t.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Ou(e,n){var t,r,s;return!n||!ir(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function sy(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function ay(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function iy(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function ly(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function Fu(e,n){var a;let r=(a=(n.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,n,t,r,s,o){let a=sy(s,200),i=ly(n,t,r,200);i=Math.max(a,i);let d=ay(o);return d!==null&&(i=Math.min(i,d)),iy(e,a,i)}var $u={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"}},tl=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,T;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=$u[a])!=null?x:$u.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 A=h("p","persona-text-sm persona-text-persona-muted");A.textContent=i.description,d.appendChild(A)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(A=>{var w,I;let R=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${n.id}-${a}-${A.name}`;let P=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=A.label,R.appendChild(P);let W=(w=A.type)!=null?w:"text",L;W==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=W),L.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",L.id=`${n.id}-${a}-${A.name}`,L.name=A.name,L.placeholder=(I=A.placeholder)!=null?I:"",A.required&&(L.required=!0),R.appendChild(L),p.appendChild(R)});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=(T=i.submitLabel)!=null?T:"Submit",m.appendChild(g),m.appendChild(u),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async A=>{var L,w;A.preventDefault();let R=(L=t.formEndpoint)!=null?L:"/form",P=new FormData(p),W={};P.forEach((I,F)=>{W[F]=I}),W.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let I=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let F=await I.json();g.textContent=(w=F.message)!=null?w:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(I){g.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var nl=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},li=new nl;var ju=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,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 cy=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},dy=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},ci=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=cy(e),t=dy(n);if(!t)return null;let r=JSON.parse(t);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}},rl=e=>typeof e=="string"?e:e==null?"":String(e),ns={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:rl(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=rl(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:rl(t.text)}}},Uu=e=>Array.isArray(e)?e.map(n=>String(n)):[],di=e=>{let n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.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;n.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:t}};var py=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},uy=e=>e.map(n=>({...n,streaming:!1})),my=e=>e.map(n=>({...n,status:"complete"})),ol=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?py(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?uy(t.messages):void 0,artifacts:t.artifacts?my(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as gy,STR as fy,OBJ as hy}from"partial-json";function by(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function yy(e,n){if(!by(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function sl(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=gy(t,fy|hy),o=yy(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function xy(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function al(e,n){let{config:t,message:r,onPropsUpdate:s}=n,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:t,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 vy(){let e=sl();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function qu(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function il(e){let n=qu(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function ll(e){let n=qu(e);if(!n)return null;try{let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:n}}}catch{}return null}var wy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function cl(e){let{onSubmit:n,onDismiss:t,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=wy}=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 T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];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=`
|
|
26
|
+
`):""},ly=(e,n)=>{var p,m,g,u,v;let t=e.toolCall,r=(p=n==null?void 0:n.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=iy(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=t?Ip(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(u=n==null?void 0:n.toolCall)!=null?u:{},l=a;return s==="tool-name"?l=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=Ci(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ci(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},gu=(e,n,t)=>{var p;let r=Yo.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.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")},qi=(e,n)=>{var z,oe,We,je,Ne,ge,ye,Le,He;let t=e.toolCall,r=(z=n==null?void 0:n.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),!t)return s;let o=(We=(oe=n==null?void 0:n.features)==null?void 0:oe.toolCallDisplay)!=null?We:{},a=o.expandable!==!1,i=a&&Yo.has(e.id),{summary:d,previewText:l,isActive:p}=ly(e,n),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=t.startedAt)!=null?je:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",v),ee.textContent=ks(t),ee},C=(ge=r.renderCollapsedSummary)==null?void 0:ge.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Ne=o.collapsedMode)!=null?Ne:"tool-call",isActive:p,config:n!=null?n:{},elapsed:ks(t),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=t.name)==null?void 0:fe.trim())||"tool",le=Ea(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(t):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:t,defaultPreview:l,isActive:p,config:n!=null?n:{}});ay(_,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),t.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=t.name,B.appendChild(ee)}if(t.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(t.args),ee.append(Pe,V),B.appendChild(ee)}if(t.chunks&&t.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=t.chunks.join(""),ee.append(Pe,V),B.appendChild(ee)}if(t.status==="complete"&&t.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(t.result),ee.append(Pe,V),B.appendChild(ee)}if(t.status==="complete"&&typeof t.duration=="number"){let ee=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ee.style.color=r.contentTextColor),ee.textContent=`Duration: ${t.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 cy,ARR as dy,OBJ as py,STR as uy}from"partial-json";var hu="ask_user_question",zi=8,Zo="data-persona-ask-sheet-for",my="Other",gy="Other\u2026",yu="Type your own answer here",bu="Send",fy="Next",hy="Back",yy="Submit all",by="Skip",xy=3,Vi="data-ask-current-index",Ki="data-ask-question-count",xu="data-ask-answers",Ji="data-ask-grouped",vu="data-ask-layout",vy=e=>e.layout==="pills"?"pills":"rows",wy=e=>e.getAttribute(vu)==="pills"?"pills":"rows",fu=!1,wu=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===hu,ni=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},so=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=cy(s,uy|py|dy);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},Ks=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>zi&&!fu&&(fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${zi}.`)),n.slice(0,zi)},Cy=e=>{var n;return(n=Ks(e)[0])!=null?n:null},Ay=(e,n)=>{var t;return(t=Ks(e)[n])!=null?t:null},Cu=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Au=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},Sy=(e,n,t,r)=>{let o=h("button",t==="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(n)),o.setAttribute("data-option-label",e.label),t==="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=Au(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Ty=e=>{let t=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 t.setAttribute("aria-hidden","true"),t},Ey=(e,n,t,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&&!t){for(let u=0;u<xy;u++)o.appendChild(Ty(r));return o}if(d.forEach((u,v)=>{o.appendChild(Sy(u,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=r==="rows"?my:gy;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=n.freeTextPlaceholder)!=null?p:yu,C.setAttribute("data-ask-free-text-input","true"),C.setAttribute("aria-label",(m=n.freeTextLabel)!=null?m:u),x.appendChild(C),v.appendChild(x);let T=Au(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=n.freeTextLabel)!=null?g:u,o.appendChild(v)}}return o},Su=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:yu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:bu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},My=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:bu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},ky=(e,n,t)=>{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=t.backLabel)!=null?l:hy,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=t.skipLabel)!=null?p:by,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===n-1;return i.textContent=d?(m=t.submitAllLabel)!=null?m:yy:(g=t.nextLabel)!=null?g:fy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},ko=e=>{let n=e.getAttribute(xu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Tu=(e,n)=>{e.setAttribute(xu,JSON.stringify(n))},ar=e=>{var t;let n=Number((t=e.getAttribute(Vi))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},Ly=(e,n)=>{e.setAttribute(Vi,String(Math.max(0,Math.floor(n))))},es=e=>{var t;let n=Number((t=e.getAttribute(Ki))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},ao=e=>e.getAttribute(Ji)==="true",Py=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Iy=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},ri=(e,n)=>{let{payload:t}=so(n),r=Ks(t),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},Eu=e=>{let n=ko(e),t=ar(e),r=n[t],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=""},Mu=e=>{if(!ao(e))return;let n=ko(e),t=ar(e),r=n[t],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}},Gi=(e,n,t)=>{let r=ni(t),s=wy(e),{payload:o,complete:a}=so(n),i=ao(e),d=ar(e),l=es(e),p=i?Ay(o,d):Cy(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=Ey(p,r,a,s);x.replaceWith(H)}if(s!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(Su(r,s))}let C=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!C?e.appendChild(My(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=ky(d,l,r);T?T.replaceWith(H):e.appendChild(H)}else T&&T.remove();Eu(e),Mu(e)},Wy=(e,n,t)=>{let r=ni(n),s=vy(r),o=e.toolCall.id,a=Ks(t),i=Math.max(1,a.length),d=i>1,l=Py(e,a),p=d?Iy(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(Ki,String(i)),m.setAttribute(Vi,String(p)),m.setAttribute(Ji,d?"true":"false"),m.setAttribute(vu,s),Tu(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`),Cu(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(Su(r,s)),Gi(m,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Ry=(e,n,t)=>{let{payload:r}=so(n),s=Math.max(1,Ks(r).length);s>es(e)&&(e.setAttribute(Ki,String(s)),s>1&&!ao(e)&&e.setAttribute(Ji,"true")),Gi(e,n,t)},Hy=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=ni(n);Cu(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=so(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},Js=(e,n,t)=>{if(!t||!oo(e)||ni(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${Zo}]`).forEach(l=>{l.getAttribute(Zo)!==s&&l.remove()});let a=t.querySelector(`[${Zo}="${wu(s)}"]`);if(a){Ry(a,e,n);return}let{payload:i}=so(e),d=Wy(e,n,i);t.appendChild(d)},Lo=(e,n)=>{if(!e)return;let t=n?`[${Zo}="${wu(n)}"]`:`[${Zo}]`;e.querySelectorAll(t).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)})},Xi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),io=(e,n)=>{let t=ko(e),r=ar(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,Tu(e,t),Eu(e),Mu(e)},oi=(e,n,t,r)=>{let s=es(e),o=Math.max(0,Math.min(s-1,r));Ly(e,o),Gi(e,n,t)};var Qi=(e,n)=>{var x,C,T,H,L,P,W,w,I,O,_,B;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.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)",!t)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=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.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",t.status),t.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"):t.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"):t.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=t.description,m.appendChild(v),t.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(t.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 ku=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.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),n.push(v)}),e.appendChild(p)}}};var Gs=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}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 n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)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=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{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,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};var By=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Dy=new Set(["step_start","execution_start"]),Ny=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Fy=new Set(["step_complete","agent_turn_complete"]),Oy=new Set(["flow_complete","agent_complete"]),Lu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Iu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Po=(e,n)=>{let t=e[n];return Iu(t)?t:void 0};function Yi(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function si(e,n){if(!(e<=0||n===void 0||n<250))return e/(n/1e3)}function _y(e,n){return typeof n.type=="string"?n.type:e}function $y(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 jy(e,n){return e==="step_delta"||e==="step_chunk"?n.stepType!=="tool"&&n.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof n.contentType=="string"?n.contentType:typeof n.content_type=="string"?n.content_type:void 0)==="text"}function Pu(e){var r,s,o,a,i;let n=Po(e,"result"),t=[Po(e,"tokens"),Po(e,"totalTokens"),n?Po(n,"tokens"):void 0,Po(e,"usage"),n?Po(n,"usage"):void 0];for(let d of t){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:n?(a=Gn(n.outputTokens))!=null?a:Gn(n.completionTokens):void 0}function Uy(e){var t,r,s,o,a;let n=Po(e,"result");return(a=(s=(r=(t=Gn(e.executionTime))!=null?t:Gn(e.executionTimeMs))!=null?r:Gn(e.execution_time))!=null?s:Gn(e.duration))!=null?a:n?(o=Gn(n.executionTime))!=null?o:Gn(n.executionTimeMs):void 0}function qy(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(n=qy){this.metric={status:"idle"};this.run=null;this.now=n}getMetric(){let n=this.run;if(n&&this.metric.status==="running"&&n.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-n.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:si(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(n){this.run={startedAt:n,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(n,t){var o;if(!Iu(t)){Lu.has(n)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=_y(n,t),s=this.now();if(By.has(r)){this.startRun(s);return}if(Dy.has(r)){this.run||this.startRun(s);return}if(Ny.has(r)){if(!jy(r,t))return;let a=$y(t);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+Yi(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:si(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Fy.has(r)){if(!this.run)return;let a=this.run,i=Pu(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Yi(a.visibleCharCount),p=this.resolveDuration(a,t,s);this.metric={status:"running",tokensPerSecond:si(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Oy.has(r)){if(!this.run)return;let a=this.run,i=Pu(t),d=i!=null?i:a.exactOutputTokens+Yi(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,t,s);this.metric={status:"complete",tokensPerSecond:si(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Lu.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(n,t,r){let s=n.firstDeltaAt!==void 0?r-n.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=Uy(t);return o!=null?o:r-n.startedAt}};function ts(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var zy={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)"}},Vy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ky=["flowName","stepName","reasoningText","text","name","tool","toolName"],Jy=100;function Gy(e,n){let t={...zy,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Vy}function Xy(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Qy(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function Yy(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;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 Zy(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{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),t()})}function eb(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function tb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function nb(e){let n=[];return e.outputTokens!==void 0&&n.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&n.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&n.push(e.source),n.join(" \xB7 ")}function rb(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,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 Zi(e,n,t,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:n,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"?Xy(e.timestamp,t):Qy(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(n+1));let P=Gy(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:Ky,I=Yy(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 Zy(eb(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(rb(e,a,i)),u}}function Wu(e){var v,x,C,T,H;let{buffer:n,getFullHistory:t,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:n.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=Oa(),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:n.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=tb(ne);let me=nb(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=n.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=n.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=n.getEvictedCount();ne>0?(Qe.textContent=`${ne.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",W=Ot();let me=W.length,vt=n.getSize()>0;le&&(le.textContent=String(n.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=n.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=Zi(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=Zi(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=Zi(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>=Jy){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:t?(ne=await t(),ne.length===0&&(ne=n.getAll())):ne=n.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=$a({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 Ru(e,n){let t=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 ${t} 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=t;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 ${t}`,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 Hu=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){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=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>Ru(e,n)});if(p)return p}return Ru(e,n)};var el=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},lo=new el;lo.register("PersonaArtifactCard",Hu);function ob(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.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),n.appendChild(t),n.appendChild(r),n}function Bu(e,n){var ve,fe,we,ze;let t=(fe=(ve=e.features)==null?void 0:ve.artifacts)==null?void 0:fe.layout,s=((we=t==null?void 0:t.toolbarPreset)!=null?we:"default")==="document",o=(ze=t==null?void 0:t.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=n.onDismiss)==null||Q.call(n)});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=n.onDismiss)==null||Q.call(n)});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=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,W=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,I=!!(W&&w&&w.length>0),O=null,_,B=null,j=null;if(s&&(P||W)&&!I){if(_=P?Ja({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?Ja({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=t==null?void 0:t.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=t==null?void 0:t.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=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:Q.call(t))}catch{}V()}),oe.addEventListener("click",()=>{var Q;p(),(Q=n.onDismiss)==null||Q.call(n)});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",()=>n.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(ob(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 n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function Du(e,n){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(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.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 sb(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 ai(e,n){var d,l,p,m,g,u,v,x,C,T;if(!ir(n)){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"),sb(e),Du(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=t==null?void 0:t.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=t==null?void 0:t.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=t==null?void 0:t.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=t==null?void 0:t.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=t==null?void 0:t.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=t==null?void 0:t.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"),Du(e,n)}var Nu=["panel","seamless"];function ii(e,n){var i,d,l,p,m,g;for(let u of Nu)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(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=Nu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=t==null?void 0:t.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Fu(e,n){var t,r,s;return!n||!ir(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function ab(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function ib(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function lb(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function cb(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function Ou(e,n){var a;let r=(a=(n.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,n,t,r,s,o){let a=ab(s,200),i=cb(n,t,r,200);i=Math.max(a,i);let d=ib(o);return d!==null&&(i=Math.min(i,d)),lb(e,a,i)}var $u={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"}},tl=(e,n,t,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=$u[a])!=null?x:$u.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=`${n.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=`${n.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=t.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 nl=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},li=new nl;var ju=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,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 db=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},pb=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},ci=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=db(e),t=pb(n);if(!t)return null;let r=JSON.parse(t);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}},rl=e=>typeof e=="string"?e:e==null?"":String(e),ns={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:rl(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=rl(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:rl(t.text)}}},Uu=e=>Array.isArray(e)?e.map(n=>String(n)):[],di=e=>{let n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.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;n.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:t}};var ub=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},mb=e=>e.map(n=>({...n,streaming:!1})),gb=e=>e.map(n=>({...n,status:"complete"})),ol=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?ub(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?mb(t.messages):void 0,artifacts:t.artifacts?gb(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as fb,STR as hb,OBJ as yb}from"partial-json";function bb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function xb(e,n){if(!bb(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function sl(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=fb(t,hb|yb),o=xb(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function vb(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function al(e,n){let{config:t,message:r,onPropsUpdate:s}=n,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:t,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 wb(){let e=sl();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function qu(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function il(e){let n=qu(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function ll(e){let n=qu(e);if(!n)return null;try{let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:n}}}catch{}return null}var Cb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function cl(e){let{onSubmit:n,onDismiss:t,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=Cb}=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=`
|
|
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,A.forEach((F,_)=>{let B=_<w;F.classList.toggle("selected",B),F.setAttribute("aria-checked",_===w-1?"true":"false")})}),A.push(I),T.appendChild(I)}g.appendChild(T);let R=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=o,R.rows=3,R.setAttribute("aria-label","Additional comments"),w.appendChild(R),g.appendChild(w)}let P=document.createElement("div");P.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{t==null||t(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(m===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=(R==null?void 0:R.value.trim())||void 0;await n(m,w),p.remove()}catch(w){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),P.appendChild(W),P.appendChild(L),g.appendChild(P),p.appendChild(g),p}function dl(e){let{onSubmit:n,onDismiss:t,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 T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,v.appendChild(T),u.appendChild(v);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=p,R.appendChild(P),R.appendChild(W);let L=document.createElement("div");L.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),L.appendChild(z)}A.appendChild(R),A.appendChild(L),u.appendChild(A);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 F=document.createElement("div");F.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=i,_.addEventListener("click",()=>{t==null||t(),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){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.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 n(g,j),m.remove()}catch(j){B.disabled=!1,B.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),F.appendChild(_),F.appendChild(B),u.appendChild(F),m.appendChild(u),m}var rs="persona-chat-history",Cy=30*1e3,Ay={"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 Sy(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=Ay[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function pi(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function Ty(e){var n,t,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:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"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 Ey(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var pl=e=>!e||typeof e!="object"?{}:{...e},zu=e=>e.map(n=>({...n,streaming:!1})),Vu=(e,n,t)=>{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(n){let g=n.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&&t&&t())}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 Ku(e){var i,d,l,p;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(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=ye(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let m=h("span","persona-drop-overlay-label");m.textContent=e.label,n.appendChild(m)}return n}var ul=(e,n,t)=>{var Ll,Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Ol,Fl,_l,$l,jl,Ul,ql,zl,Vl,Kl,Jl,Gl,Xl,Ql,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,xc,vc,wc,Cc;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=Pi(n),s=li.getForInstance(r.plugins);r.components&&lo.registerAll(r.components);let o=ju(),i=r.persistState===!1?null:(Ll=r.storageAdapter)!=null?Ll:ol(),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:b,open:y}=f;return y&&(p=!0),b}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 b=f!=null?f:{messages:[],metadata:{}};return m(b)});else{let f=c!=null?c:{messages:[],metadata:{}},b=m(f);b.metadata&&(d=pl(b.metadata)),(Pl=b.messages)!=null&&Pl.length&&(r={...r,initialMessages:b.messages}),(Il=b.artifacts)!=null&&Il.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Wl=b.selectedArtifactId)!=null?Wl: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:{}});(Rl=c.messages)!=null&&Rl.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,u=c=>{var b;d=(b=c({...d}))!=null?b:{},Ro()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ci],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick],T=di({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let A=(Bl=(Hl=r.launcher)==null?void 0:Hl.enabled)!=null?Bl:!0,R=(Nl=(Dl=r.launcher)==null?void 0:Dl.autoExpand)!=null?Nl:!1,P=(Ol=r.autoFocusInput)!=null?Ol:!1,W=R,L=A,w=(_l=(Fl=r.layout)==null?void 0:Fl.header)==null?void 0:_l.layout,I=!1,F=()=>no(r),_=()=>A||F(),B=F()?!1:A?R:!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=Vu(r,T,oe),je=(jl=($l=r.features)==null?void 0:$l.showReasoning)!=null?jl:!0,Ne=(ql=(Ul=r.features)==null?void 0:Ul.showToolCalls)!=null?ql:!0,ge=(Vl=(zl=r.features)==null?void 0:zl.showEventStreamToggle)!=null?Vl:!1,be=(Jl=(Kl=r.features)==null?void 0:Kl.scrollToBottom)!=null?Jl:{},He=`${(Xl=typeof r.persistState=="object"?(Gl=r.persistState)==null?void 0:Gl.keyPrefix:void 0)!=null?Xl:"persona-"}event-stream`,ee=ge?new Xs(He):null,Pe=(Zl=(Yl=(Ql=r.features)==null?void 0:Ql.eventStream)==null?void 0:Yl.maxEvents)!=null?Zl: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,b;o.emit("message:copy",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(b=(f=r.messageActions)==null?void 0:f.onCopy)==null||b.call(f,c)},onFeedback:c=>{var f,b;o.emit("message:feedback",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.messageId,c.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(b=(f=r.messageActions)==null?void 0:f.onFeedback)==null||b.call(f,c)}},te=(ec=r.statusIndicator)!=null?ec:{},se=c=>{var f,b,y,M;return c==="idle"?(f=te.idleText)!=null?f:gn.idle:c==="connecting"?(b=te.connectingText)!=null?b:gn.connecting:c==="connected"?(y=te.connectedText)!=null?y:gn.connected:c==="error"?(M=te.errorText)!=null?M:gn.error:gn[c]};function ue(c,f,b,y){if(y==="idle"&&b.idleLink){c.textContent="";let M=document.createElement("a");M.href=b.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}=iu(r),Ie=lu(r,_()),{container:ce,body:G,messagesWrapper:_e,suggestions:Et,textarea:de,sendButton:ae,sendButtonWrapper:Mn,composerForm:Ft,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=be.label)!=null?c:""},Zt=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},hn=()=>be.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 bt=()=>{let f=$e.style.display==="none"?0:$e.offsetHeight;St.style.bottom=`${f+vt}px`};bt();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=ye(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 bn=()=>{var f,b,y,M;if(!V)return;if(fe=!0,!ve&&V&&(ve=Wu({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=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:M.toggleButtonActive;D&&D.split(/\s+/).forEach(O=>O&&ut.classList.add(O))}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,b;if(fe){if(fe=!1,ve&&ve.element.remove(),G.style.display="",ut){ut.style.boxShadow="";let y=(b=(f=(c=r.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:b.toggleButtonActive;y&&y.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=(nc=(tc=r.features)==null?void 0:tc.eventStream)==null?void 0:nc.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 b=ye("activity","18px","currentColor",1.5);b&&ut.appendChild(b);let y=Ie.clearChatButtonWrapper,M=Ie.closeButtonWrapper,D=y||M;D&&D.parentNode===De?De.insertBefore(ut,D):De.appendChild(ut),ut.addEventListener("click",()=>{fe?Dn():bn()})}let xr=c=>{var y,M,D;let f=r.attachments;if(!(f!=null&&f.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(b,O):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=h("input");O.type="file",O.accept=((y=f.allowedTypes)!=null?y:Nr).join(","),O.multiple=((M=f.maxFiles)!=null?M:4)>1,O.style.display="none",O.setAttribute("aria-label",(D=f.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(O)}},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:b=>{var O;if(!S||S.isStreaming())return;let y=b.trim(),M=(O=tt==null?void 0:tt.hasAttachments())!=null?O:!1;if(!y&&!M)return;gs();let D;M&&(D=[],D.push(...tt.getContentParts()),y&&D.push(Pa(y))),S.sendMessage(y,{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:b=>{r.composer={...r.composer,selectedModelId:b},r.agent&&(r.agent={...r.agent,model:b})},onVoiceToggle:((rc=r.voiceRecognition)==null?void 0:rc.enabled)===!0?()=>{Bn==null||Bn()}:void 0});f&&($e.replaceWith(f),$e=f)}let po=c=>{let f=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");f&&(Ft=f),b&&(de=b),y&&(ae=y),M&&(q=M,_t=M.parentElement),D&&(ln=D);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Et=O);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 H=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");H&&(dt=H)};xr($e),po($e);let kn=(lc=(oc=r.layout)==null?void 0:oc.contentMaxWidth)!=null?lc:F()?(ic=(ac=(sc=r.launcher)==null?void 0:sc.composerBar)==null?void 0:ac.contentMaxWidth)!=null?ic:"720px":void 0;if(kn&&(_e.style.maxWidth=kn,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%"),kn&&Ft&&!F()&&(Ft.style.maxWidth=kn,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),kn&&Et&&!F()&&(Et.style.maxWidth=kn,Et.style.marginLeft="auto",Et.style.marginRight="auto"),kn&&me&&!F()&&(me.style.maxWidth=kn,me.style.marginLeft="auto",me.style.marginRight="auto"),(cc=r.attachments)!=null&&cc.enabled&&ne&&me){tt=Ko.fromConfig(r.attachments),tt.setPreviewsContainer(me),ne.addEventListener("change",b=>{let y=b.target;tt==null||tt.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,f=Ku(c);ce.appendChild(f)}(()=>{var y,M;let c=(M=(y=r.layout)==null?void 0:y.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 Ft;case"footer-bottom":return ln;default:return null}},b=(D,O)=>{var U;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")De.insertBefore(O,De.firstChild);else if(D==="header-right")De.appendChild(O);else{let H=De.querySelector(".persona-flex-col");H?(U=H.parentNode)==null||U.insertBefore(O,H.nextSibling):De.appendChild(O)}break;case"body-top":{let H=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(O):G.insertBefore(O,G.firstChild);break}case"body-bottom":G.appendChild(O);break;case"footer-top":Et.replaceWith(O);break;case"footer-bottom":ln.replaceWith(O);break;default:break}};for(let[D,O]of Object.entries(c))if(O)try{let U=O({config:r,defaultContent:()=>f(D)});U&&b(D,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,U)}})();let Fr=c=>{let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let y=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let D=b.getAttribute("data-bubble-type");D==="reasoning"?(Qo.has(M)?Qo.delete(M):Qo.add(M),mu(M,y)):D==="tool"&&(Yo.has(M)?Yo.delete(M):Yo.add(M),gu(M,y,r)),dr.delete(M)};_e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Fr(c))}),_e.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Fr(c))});let Er=new Map;_e.addEventListener("click",c=>{var O;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest("[data-actions-for]");if(!y)return;let M=y.getAttribute("data-actions-for");if(!M)return;let D=b.getAttribute("data-action");if(D==="copy"){let H=S.getMessages().find(Ce=>Ce.id===M);if(H&&Q.onCopy){let Ce=H.content||"";navigator.clipboard.writeText(Ce).then(()=>{b.classList.add("persona-message-action-success");let pe=ye("check",14,"currentColor",2);pe&&(b.innerHTML="",b.appendChild(pe)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let Z=ye("copy",14,"currentColor",2);Z&&(b.innerHTML="",b.appendChild(Z))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),Q.onCopy(H)}}else if(D==="upvote"||D==="downvote"){let H=((O=Er.get(M))!=null?O:null)===D,Ce=D==="upvote"?"thumbs-up":"thumbs-down";if(H){Er.delete(M),b.classList.remove("persona-message-action-active");let pe=ye(Ce,14,"currentColor",2);pe&&(b.innerHTML="",b.appendChild(pe))}else{let pe=D==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${pe}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Ge=ye(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(Z.innerHTML="",Z.appendChild(Ge))}Er.set(M,D),b.classList.add("persona-message-action-active");let he=ye(Ce,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(he)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Oe=S.getMessages().find(nt=>nt.id===M);Oe&&Q.onFeedback&&Q.onFeedback({type:D,messageId:Oe.id,message:Oe})}}}),_e.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest(".persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let D=b.getAttribute("data-approval-action");if(!D)return;let O=D==="approve"?"approved":"denied",H=S.getMessages().find(pe=>pe.id===M);if(!(H!=null&&H.approval))return;let Ce=y.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?S.resolveWebMcpApproval(M,O):S.resolveApproval(H.approval,O)});let yt=null,On=null,Fn={artifacts:[],selectedId:null},yn=!1,Lt={current:null};_e.addEventListener("click",c=>{var Z,he,Se,Oe,nt;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||((Se=(he=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Se.call(he,{type:"download",artifactId:y}))===!0)return;let D=S.getArtifactById(y),O=D==null?void 0:D.markdown,U=(D==null?void 0:D.title)||"artifact";if(!O){let Ge=b.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);O=(Oe=qe==null?void 0:qe.props)==null?void 0:Oe.markdown,U=((nt=qe==null?void 0:qe.props)==null?void 0:nt.title)||U}catch{}}}if(!O)return;let H=new Blob([O],{type:"text/markdown"}),Ce=URL.createObjectURL(H),pe=document.createElement("a");pe.href=Ce,pe.download=`${U}.md`,pe.click(),URL.revokeObjectURL(Ce)}),_e.addEventListener("click",c=>{var D,O,U;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((U=(O=(D=r.features)==null?void 0:D.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:U.call(O,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),yn=!1,S.selectArtifact(y),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,b)=>{var U,H,Ce,pe;let y=f.trim();if(!y||!Lt.current)return;let M=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",D=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:y,answers:b.structured,values:(H=b.values)!=null?H:b.source==="multi"?y.split(", "):[y],isFreeText:D,source:b.source},bubbles:!0,composed:!0})),Lo(Yn,M);let O=Lt.current.getMessages().find(Z=>{var he;return((he=Z.toolCall)==null?void 0:he.id)===M});(Ce=O==null?void 0:O.agentMetadata)!=null&&Ce.awaitingLocalTool?Lt.current.resolveAskUserQuestion(O,(pe=b.structured)!=null?pe:y):Lt.current.sendMessage(y)},_n=c=>{var M;let f=Lt.current;if(!f)return;let b=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",y=f.getMessages().find(D=>{var O;return((O=D.toolCall)==null?void 0:O.id)===b});y&&f.persistAskUserQuestionProgress(y,{answers:ri(c,y),currentIndex:ar(c)})},_r=c=>Object.entries(c).map(([f,b])=>`${f}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Mr=c=>{var M,D,O;if(((D=(M=r.features)==null?void 0:M.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let f=ar(c),b=es(c);if(f>=b-1)return;let y=(O=Lt.current)==null?void 0:O.getMessages().find(U=>{var H;return((H=U.toolCall)==null?void 0:H.id)===c.getAttribute("data-tool-call-id")});y&&(oi(c,y,r,f+1),_n(c))};Yn.addEventListener("click",c=>{var D,O,U,H,Ce,pe,Z,he,Se,Oe,nt,Ge,at,it;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;let M=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let ke=(D=y.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=(O=Lt.current)==null?void 0:O.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&&((H=Lt.current)==null||H.markAskUserQuestionResolved(Me),(Ce=Lt.current)==null||Ce.resolveAskUserQuestion(Me,"(dismissed)"));return}if(M==="pick"){let ke=b.getAttribute("data-option-label");if(!ke)return;let Me=y.getAttribute("data-multi-select")==="true",qe=ao(y);if(qe&&Me){let E=ko(y)[ar(y)],Te=new Set(Array.isArray(E)?E:[]);Te.has(ke)?Te.delete(ke):Te.add(ke),io(y,Array.from(Te)),_n(y);return}if(qe){io(y,ke),_n(y),Mr(y);return}if(Me){let E=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",E?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!E);let Te=y.querySelector('[data-ask-user-action="submit-multi"]');Te&&(Te.disabled=Xi(y).length===0);return}Zn(y,ke,{source:"pick",values:[ke]});return}if(M==="submit-multi"){let ke=Xi(y);if(ke.length===0)return;Zn(y,ke.join(", "),{source:"multi",values:ke});return}if(M==="open-free-text"){let ke=y.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=y.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus();return}if(M==="submit-free-text"){let ke=y.querySelector('[data-ask-free-text-input="true"]'),Me=(pe=ke==null?void 0:ke.value)!=null?pe:"";if(!Me.trim())return;if(ao(y)){io(y,Me.trim()),_n(y),Mr(y);return}Zn(y,Me,{source:"free-text"});return}if(M==="next"||M==="back"){if(!Lt.current)return;let ke=(Z=y.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=y.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(y)[ar(y)];(typeof Ke!="string"||Ke!==E)&&io(y,E)}let Te=M==="next"?1:-1,Re=ar(y)+Te;oi(y,Me,r,Re),_n(y);return}if(M==="submit-all"){if(!Lt.current)return;let ke=(Oe=y.getAttribute("data-tool-call-id"))!=null?Oe:"",Me=Lt.current.getMessages().find(Ke=>{var xe;return((xe=Ke.toolCall)==null?void 0:xe.id)===ke});if(!Me)return;let qe=y.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(y,E);let Te=ri(y,Me);Lt.current.persistAskUserQuestionProgress(Me,{answers:Te,currentIndex:ar(y)});let Re=_r(Te);Zn(y,Re||"(submitted)",{source:"submit-all",structured:Te});return}if(M==="skip"){if(!Lt.current)return;let ke=(at=y.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(y),E=ar(y),Te=es(y),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(y,"");let Ke=y.querySelector('[data-ask-free-text-input="true"]');if(Ke&&(Ke.value=""),Re){let xe=ri(y,Me),kt=_r(xe);Zn(y,kt||"(skipped)",{source:"submit-all",structured:xe});return}oi(y,Me,r,E+1),_n(y);return}}),Yn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let b=c.target;if(!((D=b.matches)!=null&&D.call(b,'[data-ask-free-text-input="true"]')))return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let M=b.value;if(M.trim()){if(ao(y)){io(y,M.trim()),_n(y),Mr(y);return}Zn(y,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 b=Yn.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),D=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",$r);let $n=null,Wt=null,xn=null,er=null,jr=()=>{};function kr(){er==null||er(),er=null}let Ur=()=>{var O;if(!$n||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((O=e.ownerDocument.defaultView)!=null?O:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){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 y=$n.firstElementChild;if(!y||y===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=y.offsetWidth-M/2;Wt.style.left=`${Math.max(0,D)}px`},vr=()=>{},jn=()=>{var b,y,M,D,O;if(!yt||!ir(r))return;ai(e,r),ii(e,r),vr();let c=(D=(M=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.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),yt.update(Fn),yn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(O=yt.backdrop)==null||O.classList.add("persona-hidden")):Fn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.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),yt=Bu(r,{onSelect:b=>{var y;return(y=Lt.current)==null?void 0:y.selectArtifact(b)},onDismiss:()=>{yn=!0,jn()}}),yt.element.classList.add("persona-hidden"),$n=f,f.appendChild(c),f.appendChild(yt.element),yt.backdrop&&re.appendChild(yt.backdrop),re.appendChild(f),jr=()=>{var y,M,D,O;if(!$n||!yt)return;if(!(((D=(M=(y=r.features)==null?void 0:y.artifacts)==null?void 0:M.layout)==null?void 0:D.resizable)===!0)){xn==null||xn(),xn=null,kr(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.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 H=e.ownerDocument,Ce=(O=H.defaultView)!=null?O:window,pe=Z=>{var at,it;if(!yt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;Z.preventDefault(),kr();let he=Z.clientX,Se=yt.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,qe=e.classList.contains("persona-artifact-appearance-seamless"),E=qe?0:Fu($n,Ce),Te=qe?0:U.getBoundingClientRect().width||6,Re=Se-(ke.clientX-he),Ke=_u(Re,Me,E,Te,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);yt.element.style.width=`${Ke}px`,yt.element.style.maxWidth="none",Ur()},Ge=()=>{H.removeEventListener("pointermove",nt),H.removeEventListener("pointerup",Ge),H.removeEventListener("pointercancel",Ge),er=null;try{U.releasePointerCapture(Z.pointerId)}catch{}};er=Ge,H.addEventListener("pointermove",nt),H.addEventListener("pointerup",Ge),H.addEventListener("pointercancel",Ge);try{U.setPointerCapture(Z.pointerId)}catch{}};U.addEventListener("pointerdown",pe),Wt=U,$n.insertBefore(U,yt.element),xn=()=>{U.removeEventListener("pointerdown",pe)}}if(Wt){let U=Fn.artifacts.length>0&&!yn;Wt.classList.toggle("persona-hidden",!U),Ur()}},vr=()=>{var Ce,pe,Z,he,Se,Oe,nt,Ge,at,it,ke,Me,qe,E;if(!A||!yt||((pe=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?pe:!1)||an(r)&&br(r).reveal==="emerge")return;let y=(Z=e.ownerDocument.defaultView)!=null?Z:window,M=(Se=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?Se:!0,D=(nt=(Oe=r.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?nt:640;if(M&&y.innerWidth<=D||!Ou(r,A))return;let O=(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))";Fn.artifacts.length>0&&!yn?(re.style.width=U,re.style.maxWidth=U):(re.style.width=O,re.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(On=new ResizeObserver(()=>{jn()}),On.observe(re))}else re.appendChild(ce),F()&&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,bo,yo,xo,Fo,_o,Vt,vo,Zr,ht,Pn,Br,Sn,In,Ht,Ut;if(F()){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,ya)=>{var Cs;return wo==null||wo===""?ya:(Cs=Jo(Ar,wo))!=null?Cs:wo},fa="1px solid var(--persona-border)",ha="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,fa),ce.style.borderRadius=Dr(tn==null?void 0:tn.borderRadius,ba),ce.style.boxShadow=Dr(tn==null?void 0:tn.shadow,ha),ce.style.overflow="hidden";return}let c=an(r),f=(It=(cn=r.launcher)==null?void 0:cn.sidebarMode)!=null?It:!1,b=c||f||((dn=(Cn=r.launcher)==null?void 0:Cn.fullHeight)!=null?dn:!1),y=((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),O=(Bt,Kt)=>{var Wn;return Bt==null||Bt===""?Kt:(Wn=Jo(D,Bt))!=null?Wn:Bt},U=(un=e.ownerDocument.defaultView)!=null?un:window,H=(yo=(bo=r.launcher)==null?void 0:bo.mobileFullscreen)!=null?yo:!0,Ce=(Fo=(xo=r.launcher)==null?void 0:xo.mobileBreakpoint)!=null?Fo:640,pe=U.innerWidth<=Ce,Z=H&&pe&&A,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||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=O(M==null?void 0:M.border,nt),ke=O(M==null?void 0:M.shadow,Ge),Me=O(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=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",()=>{t==null||t(),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 n(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 dl(e){let{onSubmit:n,onDismiss:t,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",()=>{t==null||t(),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 n(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",Ab=30*1e3,Sb={"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 Tb(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=Sb[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function pi(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function Eb(e){var n,t,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:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"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 Mb(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var pl=e=>!e||typeof e!="object"?{}:{...e},zu=e=>e.map(n=>({...n,streaming:!1})),Vu=(e,n,t)=>{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(n){let g=n.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&&t&&t())}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 Ku(e){var i,d,l,p;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(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(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let m=h("span","persona-drop-overlay-label");m.textContent=e.label,n.appendChild(m)}return n}var ul=(e,n,t)=>{var Ll,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;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=Pi(n),s=li.getForInstance(r.plugins);r.components&&lo.registerAll(r.components);let o=ju(),i=r.persistState===!1?null:(Ll=r.storageAdapter)!=null?Ll:ol(),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=pl(y.metadata)),(Pl=y.messages)!=null&&Pl.length&&(r={...r,initialMessages:y.messages}),(Il=y.artifacts)!=null&&Il.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Wl=y.selectedArtifactId)!=null?Wl: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:{}});(Rl=c.messages)!=null&&Rl.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:[ci],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick],C=di({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let T=(Bl=(Hl=r.launcher)==null?void 0:Hl.enabled)!=null?Bl:!0,H=(Nl=(Dl=r.launcher)==null?void 0:Dl.autoExpand)!=null?Nl:!1,L=(Fl=r.autoFocusInput)!=null?Fl:!1,P=H,W=T,w=(_l=(Ol=r.layout)==null?void 0:Ol.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=Vu(r,C,oe),je=(jl=($l=r.features)==null?void 0:$l.showReasoning)!=null?jl:!0,Ne=(ql=(Ul=r.features)==null?void 0:Ul.showToolCalls)!=null?ql:!0,ge=(Vl=(zl=r.features)==null?void 0:zl.showEventStreamToggle)!=null?Vl:!1,ye=(Jl=(Kl=r.features)==null?void 0:Kl.scrollToBottom)!=null?Jl:{},He=`${(Xl=typeof r.persistState=="object"?(Gl=r.persistState)==null?void 0:Gl.keyPrefix:void 0)!=null?Xl:"persona-"}event-stream`,ee=ge?new Xs(He):null,Pe=(Zl=(Yl=(Ql=r.features)==null?void 0:Ql.eventStream)==null?void 0:Yl.maxEvents)!=null?Zl: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=(ec=r.statusIndicator)!=null?ec:{},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}=iu(r),Ie=lu(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=Wu({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=(nc=(tc=r.features)==null?void 0:tc.eventStream)==null?void 0:nc.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(Pa(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:((rc=r.voiceRecognition)==null?void 0:rc.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=(lc=(oc=r.layout)==null?void 0:oc.contentMaxWidth)!=null?lc:O()?(ic=(ac=(sc=r.launcher)==null?void 0:sc.composerBar)==null?void 0:ac.contentMaxWidth)!=null?ic:"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"),(cc=r.attachments)!=null&&cc.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=Ku(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),mu(M,b)):D==="tool"&&(Yo.has(M)?Yo.delete(M):Yo.add(M),gu(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:ri(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&&(oi(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=Xi(b).length===0);return}Zn(b,ke,{source:"pick",values:[ke]});return}if(M==="submit-multi"){let ke=Xi(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;oi(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=ri(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=ri(b,Me),kt=_r(xe);Zn(b,kt||"(skipped)",{source:"submit-all",structured:xe});return}oi(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;ai(e,r),ii(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=Bu(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:Ou($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||!Fu(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,ba)=>{var Cs;return wo==null||wo===""?ba:(Cs=Jo(Ar,wo))!=null?Cs:wo},fa="1px solid var(--persona-border)",ha="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ya="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,fa),ce.style.borderRadius=Dr(tn==null?void 0:tn.borderRadius,ya),ce.style.boxShadow=Dr(tn==null?void 0:tn.shadow,ha),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=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -37,7 +37,7 @@ _Details: ${t.message}_`:r}var Is=class e{constructor(n={},t){this.config=n;this
|
|
|
37
37
|
padding: 0 !important;
|
|
38
38
|
display: flex !important;
|
|
39
39
|
flex-direction: column !important;
|
|
40
|
-
z-index: ${
|
|
40
|
+
z-index: ${Fe} !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: ${t.message}_`:r}var Is=class e{constructor(n={},t){this.config=n;this
|
|
|
63
63
|
overflow: hidden !important;
|
|
64
64
|
border-radius: 0 !important;
|
|
65
65
|
border: none !important;
|
|
66
|
-
`,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",$e.style.flexShrink="0",I=!0,E();return}let Te=(Pn=(ht=r==null?void 0:r.launcher)==null?void 0:ht.width)!=null?Pn:r==null?void 0:r.launcherWidth,Re=Te!=null?Te:sr;if(!f&&!c)y
|
|
66
|
+
`,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",$e.style.flexShrink="0",I=!0,E();return}let Te=(Pn=(ht=r==null?void 0:r.launcher)==null?void 0:ht.width)!=null?Pn:r==null?void 0:r.launcherWidth,Re=Te!=null?Te:sr;if(!f&&!c)b&&y?(re.style.width="100%",re.style.maxWidth="100%"):(re.style.width=Re,re.style.maxWidth=Re);else if(c)if(yr(r).reveal==="emerge"){let Kt=yr(r).width;re.style.width=Kt,re.style.maxWidth=Kt}else re.style.width="100%",re.style.maxWidth="100%";if(vr(),re.style.boxShadow=ke,re.style.borderRadius=Me,ce.style.border=it,ce.style.borderRadius=Me,c&&!Z&&(M==null?void 0:M.border)===void 0&&(ce.style.border="none",yr(r).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.height="100%",b&&(ie.style.overflow="hidden"),re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.height="100%",re.style.overflow="hidden",ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",$e.style.flexShrink="0"),ie.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!b&&!c&&((Br=br[he])!=null?Br:br["bottom-right"]).split(" ").forEach(Kt=>ie.classList.add(Kt)),f){let Bt=(In=(Sn=r.launcher)==null?void 0:Sn.sidebarWidth)!=null?In:"420px";ie.style.cssText=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
@@ -74,7 +74,7 @@ _Details: ${t.message}_`:r}var Is=class e{constructor(n={},t){this.config=n;this
|
|
|
74
74
|
padding: 0 !important;
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
|
-
z-index: ${
|
|
77
|
+
z-index: ${Fe} !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;
|
|
@@ -104,9 +104,9 @@ _Details: ${t.message}_`:r}var Is=class e{constructor(n={},t){this.config=n;this
|
|
|
104
104
|
flex-shrink: 0 !important;
|
|
105
105
|
border-top: none !important;
|
|
106
106
|
padding: 8px 16px 12px 16px !important;
|
|
107
|
-
`}if(!y&&!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),ai(e,r),ii(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}),On&>.push(()=>{On==null||On.disconnect(),On=null}),gt.push(()=>{xn==null||xn(),xn=null,kr(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.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=Ri(()=>{Eo(e,r)}))};qr(),gt.push(()=>{Un&&(Un(),Un=null)});let tr=(dc=r.features)==null?void 0:dc.streamAnimation;if(tr!=null&&tr.type&&tr.type!=="none"){let c=Fs(tr.type,tr.plugins);c&&(Di(c,e),gt.push(()=>tu(e)))}let cr=ku(Et),qn=null,S,zn=!1,dr=Gp(),Lr=new Map,wr=new Map,ss=0,pr=Fa(),ur=0,mr=null,Pr=!1,uo=!1,Ys=4,as=24,Zs=80,Wo=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=(uc=(pc=r.voiceRecognition)==null?void 0:pc.autoResume)!=null?uc:!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}}))},ea=()=>{var y,M;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=pl(d.voiceState),f=!!c.active,b=Number((M=c.timestamp)!=null?M:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-b<Cy&&setTimeout(()=>{var D,O;mt.active||(mt.manuallyDeactivated=!1,((O=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:O.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("restore"),S.isVoiceActive()&&$()}):ho("restore"))},1e3)},ta=()=>S?zu(S.getMessages()).filter(c=>!c.__skipPersist):[];function Ro(c){if(!(i!=null&&i.save))return;let b={messages:c?zu(c):S?ta():[],metadata:d,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let y=i.save(b);y instanceof Promise&&y.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Ir=null,na=()=>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),bt();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()&&ra(na(),c?220:140)})))},ra=(c,f=500)=>{let b=c.scrollTop,y=Bs(c),M=y-b;if(Math.abs(M)<1){ur=c.scrollTop;return}if(Math.abs(M)>=Zs){mo(),Pr=!0,c.scrollTop=y,ur=c.scrollTop,Pr=!1;return}mo();let D=performance.now();Pr=!0;let O=H=>1-Math.pow(1-H,3),U=H=>{if(!pr.isFollowing()){mo();return}let Ce=Bs(c);Ce!==y&&(y=Ce,M=y-b);let pe=H-D,Z=Math.min(pe/f,1),he=O(Z),Se=b+M*he;c.scrollTop=Se,ur=c.scrollTop,Z<1?Ir=requestAnimationFrame(U):(c.scrollTop=y,ur=c.scrollTop,Ir=null,Pr=!1)};Ir=requestAnimationFrame(U)},oa=c=>{let f=new Map;c.forEach(b=>{let y=Wo.get(b.id);f.set(b.id,{streaming:b.streaming,role:b.role}),!y&&b.role==="assistant"&&o.emit("assistant:message",b),b.role==="assistant"&&(y!=null&&y.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(y?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),Wo.clear(),f.forEach((b,y)=>{Wo.set(y,b)})},go=(c,f,b)=>{var Ge,at,it,ke,Me,qe;let y=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})(),O=(E,Te)=>Te==null?!1:typeof Te=="string"?(E.textContent=Te,!0):(E.appendChild(Te),!0),U=new Set,H=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,bo,yo,xo,Fo,_o,Vt,vo,Zr;U.add(E.id);let Te=Ce&&oo(E),Re=!Te&&E.role==="assistant"&&!E.variant&&he&&il(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=Jp(E,ss)+Ke,kt=Te||Re?null:Xp(dr,E.id,xe);if(kt){y.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)&&(H.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)&&((bo=E.agentMetadata)==null?void 0:bo.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=(yo=r.features)==null?void 0:yo.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){((Fo=E.agentMetadata)==null?void 0:Fo.awaitingLocalTool)===!0&&!((_o=E.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(H.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"),y.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)&&(H.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:()=>Ui(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Qt.renderToolCall){if(!Ne)return;st=Qt.renderToolCall({message:E,defaultRenderer:()=>qi(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Qt.renderApproval){if(r.approval===!1)return;st=Qt.renderApproval({message:E,defaultRenderer:()=>Qi(E,r),config:r})}else Qt.renderMessage&&(st=Qt.renderMessage({message:E,defaultRenderer:()=>{let ht=Vs(E,b,cn,r.messageActions,Q,{loadingIndicatorRenderer:D,widgetConfig:r});return E.role!=="user"&&tl(ht,E,r,S),ht},config:r}));if(!st&&Re){let ht=ll(E);if(ht){let Pn=wr.get(E.id),Br=Pn!==xe,Sn=r.wrapComponentDirectiveInBubble!==!1,In=null;if(Br){let Ht=al(ht,{config:r,message:E,transform:b});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=b({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=b({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"),y.appendChild(Ht),Z.push({messageId:E.id,fingerprint:xe,bubble:In});return}}}if(!st)if(E.variant==="reasoning"&&E.reasoning){if(!je)return;st=Ui(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!Ne)return;st=qi(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;st=Qi(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,b,ht,r.messageActions,Q,{loadingIndicatorRenderer:D,widgetConfig:r}),E.role!=="user"&&st&&tl(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),Qp(dr,E.id,xe,It),y.appendChild(It)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let Re=Te.getAttribute("data-persona-ask-sheet-for");Re&&!H.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(y.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});O(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)})})}Yp(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: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),y.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),y.appendChild(st)}}if(Na(c,y),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,sa=()=>{var b;if(Kr)return;let c=y=>{let M=y.composedPath();M.includes(ie)||Qe&&M.includes(Qe)||Rt(!1,"user")};Kr=c,((b=e.ownerDocument)!=null?b: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,aa=()=>{var b;if(Jr)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Rt(!1,"user"))};Jr=c,((b=e.ownerDocument)!=null?b: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,ia=()=>{var f,b,y,M;let c=(y=(b=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:b.peek)==null?void 0:y.streamAnimation;return c||((M=r.features)==null?void 0:M.streamAnimation)},Rr=()=>{var at,it,ke,Me;if(!F())return;let c=Ie.peekBanner,f=Ie.peekTextNode;if(!c||!f)return;if(B){c.classList.remove("persona-pill-peek--visible");return}let b=(at=S==null?void 0:S.getMessages())!=null?at:[],y;for(let qe=b.length-1;qe>=0;qe--){let E=b[qe];if(E.role==="assistant"&&E.content){y=E;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let M=y.content,D=!!y.streaming,O=ia(),U=ja(O),H=U.type!=="none"?Fs(U.type,O==null?void 0:O.plugins):null,Ce=((it=H==null?void 0:H.isAnimating)==null?void 0:it.call(H,y))===!0,pe=H!==null&&(D||Ce);pe&&H&&!us.has(H.name)&&(Di(H,e),us.add(H.name));let Z=pe&&(H!=null&&H.containerClass)?H.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?Ua(M,U.buffer,H,y,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),Na(f,qe)}else{let qe=Math.max(0,Se.length-100),E=Se.length>100?Se.slice(-100):Se,Te=jo(E);if(!pe||!H){let Re=Se.length>100?`\u2026${E}`:E;f.textContent!==Re&&(f.textContent=Re)}else{let Re=Te;(H.wrap==="char"||H.wrap==="word")&&(Re=_s(Te,H.wrap,`peek-${y.id}`,{skipTags:H.skipTags,startIndex:qe}));let Ke=document.createElement("div");if(Ke.innerHTML=Re,H.useCaret&&E.length>0){let xe=qa(),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)}Na(f,Ke),(Me=H.onAfterRender)==null||Me.call(H,{container:f,bubble:c,messageId:y.id,message:y,speed:U.speed,duration:U.duration})}}let Ge=zn||Gr;c.classList.toggle("persona-pill-peek--visible",Ge)};if(F()){let c=Ie.peekBanner;if(c){let y=M=>{M.preventDefault(),M.stopPropagation(),Rt(!0,"user")};c.addEventListener("pointerdown",y),gt.push(()=>{c.removeEventListener("pointerdown",y)})}let f=()=>{Gr||(Gr=!0,Rr())},b=()=>{Gr&&(Gr=!1,Rr())};re.addEventListener("pointerenter",f),re.addEventListener("pointerleave",b),gt.push(()=>{re.removeEventListener("pointerenter",f),re.removeEventListener("pointerleave",b)}),Qe&&(Qe.addEventListener("pointerenter",f),Qe.addEventListener("pointerleave",b),gt.push(()=>{Qe.removeEventListener("pointerenter",f),Qe.removeEventListener("pointerleave",b)}))}let la=c=>{var he,Se,Oe,nt,Ge,at,it,ke;let f=(Se=(he=r.launcher)==null?void 0:he.composerBar)!=null?Se:{},b=(Oe=f.expandedSize)!=null?Oe:"anchored",y=(nt=f.bottomOffset)!=null?nt:"16px",M=f.collapsedMaxWidth,D=(Ge=f.expandedMaxWidth)!=null?Ge:"880px",O=(at=f.expandedTopOffset)!=null?at:"5vh",U=(it=f.modalMaxWidth)!=null?it:"880px",H=(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=y,Me.width=M!=null?M:""}if(c&&b!=="fullscreen"){if(b==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=U,Z.maxWidth=Ce,Z.maxHeight=H,Z.height=H;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${pe})`,Z.top=O,Z.width=D,Z.maxWidth=Ce}},Xr=()=>{var H,Ce,pe,Z,he,Se,Oe,nt;if(!_())return;if(F()){let at=(pe=((Ce=(H=r.launcher)==null?void 0:H.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"),la(B),ce.style.display=B?"flex":"none",lr(),B?(sa(),aa()):(ds(),ps()),Rr();return}let c=an(r),f=(Z=e.ownerDocument.defaultView)!=null?Z:window,b=(Se=(he=r.launcher)==null?void 0:he.mobileBreakpoint)!=null?Se:640,y=(nt=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?nt:!0,M=f.innerWidth<=b,D=y&&M&&A,O=br(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&&(O==="overlay"||O==="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,O;if(!_()||B===c)return;let b=B;B=c,Xr();let y=(()=>{var Oe,nt,Ge,at,it,ke,Me,qe,E,Te;let U=(nt=(Oe=r.launcher)==null?void 0:Oe.sidebarMode)!=null?nt:!1,H=(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=H.innerWidth<=pe,he=an(r)&&Ce&&Z,Se=F()&&((Te=(E=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:E.expandedSize)!=null?Te:"fullscreen")==="fullscreen";return U||Ce&&Z&&A||he||Se})();if(B&&y){if(!Jt){let U=e.getRootNode(),H=U instanceof ShadowRoot?U.host:e.closest(".persona-host");H&&(Jt=Ni(H,(O=(D=r.launcher)==null?void 0:D.zIndex)!=null?O: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&&!b?o.emit("widget:opened",M):!B&&b&&o.emit("widget:closed",M),o.emit("widget:state",{open:B,launcherEnabled:A,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 b,y,M,D,O,U,H,Ce,pe,Z,he;Hn.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"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=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?U:"How can I help...";let c=G.querySelector("[data-persona-intro-card]");if(c){let Se=((H=r.copy)==null?void 0:H.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,ca=()=>{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(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=Sa(f-y))})},100))};if(S=new Is(r,{onMessagesChanged(c){go(_e,c,We),ca(),S&&(c.some(M=>M.role==="user")?cr.render([],S,de,c):cr.render(r.suggestionChips,S,de,c,r.suggestionChipsConfig)),Vr(!zn),oa(c);let f=[...c].reverse().find(y=>y.role==="user"),b=mt.lastUserMessageId;f&&f.id!==b&&(mt.lastUserMessageId=f.id,o.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Ro(c),Rr()},onStatusChanged(c){var y;let f=(y=r.statusIndicator)!=null?y:{};ue(ln,(M=>{var D,O,U,H;return M==="idle"?(D=f.idleText)!=null?D:gn.idle:M==="connecting"?(O=f.connectingText)!=null?O:gn.connecting:M==="connected"?(U=f.connectedText)!=null?U:gn.connected:M==="error"?(H=f.errorText)!=null?H: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,b;if(((b=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:b.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){Fn=c,jn(),Ro()}}),Lt.current=S,((gc=(mc=r.voiceRecognition)==null?void 0:mc.provider)==null?void 0:gc.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 b;(b=r.onSSEEvent)==null||b.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,b,y;c&&(c.metadata&&(d=pl(c.metadata),T.syncFromMetadata()),(f=c.messages)!=null&&f.length&&S.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&S.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var f,b,y;!F()||B||!((y=(b=(f=r.launcher)==null?void 0:f.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||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(),b=(M=tt==null?void 0:tt.hasAttachments())!=null?M:!1;if(!f&&!b)return;gs();let y;b&&(y=[],y.push(...tt.getContentParts()),f&&y.push(Pa(f))),de.value="",de.style.height="auto",fo(),S.sendMessage(f,{contentParts:y}),b&&tt.clearAttachments()},da=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Do={...Oa},No=!1,fo=()=>{Do={...Oa}},pa=()=>S.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),ua=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()},bs=c=>{if(de){if(da()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=de.selectionStart===0&&de.selectionEnd===0,b=Kp({direction:c.key==="ArrowUp"?"up":"down",history:pa(),currentValue:de.value,atStart:f,state:Do});if(Do=b.state,b.handled){c.preventDefault(),b.value!==void 0&&ua(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(S.isStreaming()){c.preventDefault();return}fo(),c.preventDefault(),ae.click()}}},ys=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 b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!tt)return;let f=Sy(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,O,U,H,Ce,pe,Z;if(Vn||S.isStreaming())return;let f=vs();if(!f)return;vn=new f;let y=(O=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?O:2e3;vn.continuous=!0,vn.interimResults=!0,vn.lang="en-US";let M=de.value;vn.onresult=he=>{let Se="",Oe="";for(let Ge=0;Ge<he.results.length;Ge++){let at=he.results[Ge],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 Ge=de.value.trim();Ge&&vn&&Vn&&(gr(),de.value="",de.style.height="auto",S.sendMessage(Ge,{viaVoice:!0}))},y))},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:(H=he.iconName)!=null?H:"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,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 Ge=q.querySelector("svg");Ge&&Ge.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")}}},ma=(c,f)=>{var at,it,ke,Me,qe,E,Te,Re;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((at=c==null?void 0:c.provider)==null?void 0:at.type)==="runtype";if(!(b||y))return null;let D=h("div","persona-send-button-wrapper"),O=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let U=(it=c==null?void 0:c.iconName)!=null?it:"mic",H=(ke=f==null?void 0:f.size)!=null?ke:"40px",Ce=(Me=c==null?void 0:c.iconSize)!=null?Me:H,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;O.style.width=Ce,O.style.height=Ce,O.style.minWidth=Ce,O.style.minHeight=Ce,O.style.fontSize="18px",O.style.lineHeight="1",he?O.style.color=he:O.style.color="var(--persona-text, #111827)";let Oe=ye(U,pe,he||"currentColor",1.5);Oe?O.appendChild(Oe):O.textContent="\u{1F3A4}",Z?O.style.backgroundColor=Z:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),D.appendChild(O);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:O,micButtonWrapper:D}},Qr=()=>{var f,b,y,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:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((D=(M=c.iconSize)!=null?M:(y=r.sendButton)==null?void 0:y.size)!=null?D:"40")||24}},Ve=(c,f)=>{var D,O,U,H,Ce;if(!q)return;let b=q.querySelector("svg");b&&b.remove();let y=(Ce=ot==null?void 0:ot.iconSize)!=null?Ce:parseFloat((H=(U=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?U:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,M=ye(c,y,f,1.5);M&&q.appendChild(M)},C=()=>{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,b=c.recordingIconColor,y=c.recordingBorderColor;if(C(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let D=q.querySelector("svg");D&&D.setAttribute("stroke",b)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},k=()=>{var U,H,Ce,pe,Z,he,Se,Oe;if(!q)return;Qr();let c=(U=r.voiceRecognition)!=null?U:{},f=S.getVoiceInterruptionMode(),b=(H=c.processingIconName)!=null?H:"loader",y=(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=(Oe=(Se=c.processingBorderColor)!=null?Se:ot==null?void 0:ot.borderColor)!=null?Oe:"";C(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=M,q.style.borderColor=D;let O=y||"currentColor";q.style.color=O,Ve(b,O),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},Y=()=>{var Ce,pe,Z,he,Se,Oe,nt,Ge,at,it,ke,Me;if(!q)return;Qr();let c=(Ce=r.voiceRecognition)!=null?Ce:{},f=S.getVoiceInterruptionMode(),b=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",y=(pe=c.speakingIconName)!=null?pe:b,M=(Oe=c.speakingIconColor)!=null?Oe: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:"",O=(Me=c.speakingBorderColor)!=null?Me:f==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(ke=ot==null?void 0:ot.borderColor)!=null?ke:"";C(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=D,q.style.borderColor=O;let U=M||"currentColor";q.style.color=U,Ve(y,U);let H=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",H),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},K=()=>{var c,f,b;q&&(C(),ot&&(q.style.backgroundColor=(c=ot.backgroundColor)!=null?c:"",q.style.color=(f=ot.color)!=null?f:"",q.style.borderColor=(b=ot.borderColor)!=null?b:"",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 b=S.getVoiceStatus(),y=S.getVoiceInterruptionMode();if(y==="none"&&(b==="processing"||b==="speaking"))return;if(y==="cancel"&&(b==="processing"||b==="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 b=de.value.trim();mt.manuallyDeactivated=!0,Ln(),gr("user"),b&&(de.value="",de.style.height="auto",S.sendMessage(b))}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 Fe=o.on("action:resubmit",()=>{setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)});gt.push(Fe);let et=()=>{Rt(!B,"user")},Ee=null,Je=null;if(A&&!F()){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),ea(),P&&(!A||F()?setTimeout(()=>Bo(),0):B&&setTimeout(()=>Bo(),200));let Pt=()=>{var H,Ce,pe,Z,he,Se,Oe,nt,Ge,at,it,ke,Me,qe,E,Te,Re,Ke,xe,kt,st,Qt;if(F()){bt(),Xr();return}let c=an(r),f=(Ce=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?Ce:!1,b=c||f||((Z=(pe=r.launcher)==null?void 0:pe.fullHeight)!=null?Z:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,M=(Oe=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?Oe:!0,D=(Ge=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?Ge:640,O=y.innerWidth<=D,U=M&&O&&A;try{if(U){lr(),Eo(e,r);return}if(I&&(I=!1,lr(),Eo(e,r)),!A&&!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(),!b){let cn=y.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(bt(),Xr(),B&&A){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&&A||Ze;if(lt&&!Gt){let An=e.getRootNode(),un=An instanceof ShadowRoot?An.host:e.closest(".persona-host");un&&!Jt&&(Jt=Ni(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=(fc=e.ownerDocument.defaultView)!=null?fc:window;if(nn.addEventListener("resize",Pt),gt.push(()=>nn.removeEventListener("resize",Pt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe($e),gt.push(()=>c.disconnect())}ur=G.scrollTop;let Ct=G.scrollHeight,Mt=()=>{let c=G.scrollTop,f=G.scrollHeight,b=f<Ct;Ct=f;let{action:y,nextLastScrollTop:M}=_a({following:pr.isFollowing(),currentScrollTop:c,lastScrollTop:ur,nearBottom:Ds(G,as),userScrollThreshold:Ys,isAutoScrolling:Pr||uo||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ur=M,y==="resume"){zr();return}y==="pause"&&cs()};G.addEventListener("scroll",Mt,{passive:!0}),gt.push(()=>G.removeEventListener("scroll",Mt));let rn=c=>{let f=$a({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(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},T.syncFromMetadata(),V==null||V.clear(),le==null||le.reset(),ve==null||ve.update()})})(),Ft&&Ft.addEventListener("submit",fs),de==null||de.addEventListener("keydown",bs),de==null||de.addEventListener("input",hs),de==null||de.addEventListener("paste",xs);let Xt=(hc=e.ownerDocument)!=null?hc:document;Xt.addEventListener("keydown",ys,!0);let rr="persona-attachment-drop-active",ws=0,wi=()=>{ws=0,ce.classList.remove(rr)},Oo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&tt!==null},Al=c=>{!pi(c.dataTransfer)||!Oo()||(ws++,ws===1&&ce.classList.add(rr))},Sl=c=>{!pi(c.dataTransfer)||!Oo()||(ws--,ws<=0&&wi())},Tl=c=>{!pi(c.dataTransfer)||!Oo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},El=c=>{var b;if(!pi(c.dataTransfer)||!Oo())return;c.preventDefault(),c.stopPropagation(),wi();let f=Array.from((b=c.dataTransfer.files)!=null?b:[]);f.length!==0&&tt.handleFiles(f)},Yr=!0;ce.addEventListener("dragenter",Al,Yr),ce.addEventListener("dragleave",Sl,Yr),e.addEventListener("dragover",Tl,Yr),e.addEventListener("drop",El,Yr);let ga=e.ownerDocument,Ml=c=>{Oo()&&c.preventDefault()},kl=c=>{Oo()&&c.preventDefault()};ga.addEventListener("dragover",Ml),ga.addEventListener("drop",kl),gt.push(()=>{Ft&&Ft.removeEventListener("submit",fs),de==null||de.removeEventListener("keydown",bs),de==null||de.removeEventListener("input",hs),de==null||de.removeEventListener("paste",xs),Xt.removeEventListener("keydown",ys,!0)}),gt.push(()=>{ce.removeEventListener("dragenter",Al,Yr),ce.removeEventListener("dragleave",Sl,Yr),e.removeEventListener("dragover",Tl,Yr),e.removeEventListener("drop",El,Yr),ga.removeEventListener("dragover",Ml),ga.removeEventListener("drop",kl),wi()}),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,fa,ha,ba,wo,ya,Cs,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp;let f=r.toolCall,b=r.messageActions,y=(tn=r.layout)==null?void 0:tn.messages,M=r.colorScheme,D=r.loadingIndicator,O=r.iterationDisplay,U=(Ar=r.features)==null?void 0:Ar.showReasoning,H=(Dr=r.features)==null?void 0:Dr.showToolCalls,Ce=(fa=r.features)==null?void 0:fa.toolCallDisplay,pe=(ha=r.features)==null?void 0:ha.reasoningDisplay;r={...r,...c},lr(),Eo(e,r),ai(e,r),ii(e,r),jn(),r.colorScheme!==M&&qr();let Z=li.getForInstance(r.plugins);s.length=0,s.push(...Z),A=(wo=(ba=r.launcher)==null?void 0:ba.enabled)!=null?wo:!0,R=(Cs=(ya=r.launcher)==null?void 0:ya.autoExpand)!=null?Cs:!1,je=(Sc=(Ac=r.features)==null?void 0:Ac.showReasoning)!=null?Sc:!0,Ne=(Ec=(Tc=r.features)==null?void 0:Tc.showToolCalls)!=null?Ec:!0,be=(kc=(Mc=r.features)==null?void 0:Mc.scrollToBottom)!=null?kc:{},zt(),Wr();let he=ge;if(ge=(Pc=(Lc=r.features)==null?void 0:Lc.showEventStreamToggle)!=null?Pc:!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=(Wc=(Ic=r.features)==null?void 0:Ic.eventStream)==null?void 0:Wc.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=ye("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():bn()})}}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(((Rc=r.launcher)==null?void 0:Rc.enabled)===!1&&Ee&&(Ee.destroy(),Ee=null),((Hc=r.launcher)==null?void 0:Hc.enabled)===!1&&Je&&(Je.remove(),Je=null),((Bc=r.launcher)==null?void 0:Bc.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&&((Dc=r.launcher)==null?void 0:Dc.title)!==void 0&&(Ae.textContent=r.launcher.title),Be&&((Nc=r.launcher)==null?void 0:Nc.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=((Fc=r.layout)==null?void 0:Fc.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"),bt(),Wr(),A!==L?A?Rt(R,"auto"):(B=!0,Xr()):R!==W&&Rt(R,"auto"),W=R,L=A,Pt(),pn();let ke=JSON.stringify(c.toolCall)!==JSON.stringify(f),Me=JSON.stringify(r.messageActions)!==JSON.stringify(b),qe=JSON.stringify(($c=r.layout)==null?void 0:$c.messages)!==JSON.stringify(y),E=((jc=r.loadingIndicator)==null?void 0:jc.render)!==(D==null?void 0:D.render)||((Uc=r.loadingIndicator)==null?void 0:Uc.renderIdle)!==(D==null?void 0:D.renderIdle)||((qc=r.loadingIndicator)==null?void 0:qc.showBubble)!==(D==null?void 0:D.showBubble),Te=r.iterationDisplay!==O,Re=((Vc=(zc=r.features)==null?void 0:zc.showReasoning)!=null?Vc:!0)!==(U!=null?U:!0)||((Jc=(Kc=r.features)==null?void 0:Kc.showToolCalls)!=null?Jc:!0)!==(H!=null?H:!0)||JSON.stringify((Gc=r.features)==null?void 0:Gc.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Xc=r.features)==null?void 0:Xc.reasoningDisplay)!==JSON.stringify(pe);(ke||Me||qe||E||Te||Re)&&S&&(ss++,go(_e,S.getMessages(),We));let xe=(Qc=r.launcher)!=null?Qc:{},kt=(Yc=xe.headerIconHidden)!=null?Yc:!1,st=(ed=(Zc=r.layout)==null?void 0:Zc.header)==null?void 0:ed.showIcon,Qt=kt||st===!1,cn=xe.headerIconName,It=(td=xe.headerIconSize)!=null?td:"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=ye(cn,ct*.6,"#ffffff",2);Tt?N.replaceChildren(Tt):N.textContent=(nd=xe.agentIconText)!=null?nd:"\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=(rd=xe.agentIconText)!=null?rd:"\u{1F4AC}"}let Nt=N.querySelector("img");Nt&&(Nt.style.height=It,Nt.style.width=It)}}let Cn=(sd=(od=r.layout)==null?void 0:od.header)==null?void 0:sd.showTitle,dn=(id=(ad=r.layout)==null?void 0:ad.header)==null?void 0:id.showSubtitle;if(Ae&&(Ae.style.display=Cn===!1?"none":""),Be&&(Be.style.display=dn===!1?"none":""),Ue){((cd=(ld=r.layout)==null?void 0:ld.header)==null?void 0:cd.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let xt=(dd=xe.closeButtonSize)!=null?dd:"32px",Nt=(pd=xe.closeButtonPlacement)!=null?pd:"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=(md=(ud=xe.clearChat)==null?void 0:ud.placement)!=null?md:"inline",sn=(fd=(gd=xe.clearChat)==null?void 0:gd.enabled)!=null?fd:!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=(hd=xe.closeButtonIconName)!=null?hd:"x",fr=(bd=xe.closeButtonIconText)!=null?bd:"\xD7";Ue.innerHTML="";let Tn=ye(mn,"28px","currentColor",1);Tn?Ue.appendChild(Tn):Ue.textContent=fr;let Yt=(yd=xe.closeButtonTooltipText)!=null?yd:"Close chat",Jn=(xd=xe.closeButtonShowTooltip)!=null?xd:!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=(vd=xe.clearChat)!=null?vd:{},xt=(wd=X.enabled)!=null?wd:!0,Nt=(Ad=(Cd=r.layout)==null?void 0:Cd.header)==null?void 0:Ad.showClearChat,ct=Nt!==void 0?Nt:xt,Tt=(Sd=X.placement)!=null?Sd:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:on}=Ie;!F()&&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(!F()&&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(!F()){let pt=(Td=X.size)!=null?Td:"32px";Ze.style.height=pt,Ze.style.width=pt}let on=(Ed=X.iconName)!=null?Ed:"refresh-cw",mn=(Md=X.iconColor)!=null?Md:"";Ze.style.color=mn||En.actionIconColor,Ze.innerHTML="";let fr=F()?"14px":"20px",Tn=ye(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=(kd=X.tooltipText)!=null?kd:"Clear chat",Jn=(Ld=X.showTooltip)!=null?Ld:!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:[ci],un=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick];T=di({parsers:An,handlers:un,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),We=Vu(r,T,oe),S.updateConfig(r),go(_e,S.getMessages(),We),cr.render(r.suggestionChips,S,de,void 0,r.suggestionChipsConfig),ms(),Ho(S.isStreaming());let bo=((Pd=r.voiceRecognition)==null?void 0:Pd.enabled)===!0,yo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),xo=((Wd=(Id=r.voiceRecognition)==null?void 0:Id.provider)==null?void 0:Wd.type)==="runtype";if(bo&&(yo||xo))if(!q||!_t){let X=ma(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=(Rd=r.voiceRecognition)!=null?Rd:{},xt=(Hd=r.sendButton)!=null?Hd:{},Nt=(Bd=X.iconName)!=null?Bd:"mic",ct=(Dd=xt.size)!=null?Dd:"40px",Tt=(Nd=X.iconSize)!=null?Nd:ct,on=parseFloat(Tt)||24;q.style.width=Tt,q.style.height=Tt,q.style.minWidth=Tt,q.style.minHeight=Tt;let mn=(Fd=(Od=X.iconColor)!=null?Od:xt.textColor)!=null?Fd:"currentColor";q.innerHTML="";let fr=ye(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=($d=X.tooltipText)!=null?$d:"Start voice recognition";if(((jd=X.showTooltip)!=null?jd:!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",((qd=(Ud=r.voiceRecognition)==null?void 0:Ud.provider)==null?void 0:qd.type)==="runtype"?S.isVoiceActive()&&S.toggleVoice():Vn&&gr());if(((zd=r.attachments)==null?void 0:zd.enabled)===!0)if(!Dt||!Ye){let X=(Vd=r.attachments)!=null?Vd:{},Nt=(Jd=((Kd=r.sendButton)!=null?Kd:{}).size)!=null?Jd:"40px";me||(me=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),me.style.display="none",Ft.insertBefore(me,de)),ne||(ne=document.createElement("input"),ne.type="file",ne.accept=((Gd=X.allowedTypes)!=null?Gd:Nr).join(","),ne.multiple=((Xd=X.maxFiles)!=null?Xd:4)>1,ne.style.display="none",ne.setAttribute("aria-label","Attach files"),Ft.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",(Qd=X.buttonTooltipText)!=null?Qd:"Attach file");let ct=(Yd=X.buttonIconName)!=null?Yd:"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=ye(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=(Zd=X.buttonTooltipText)!=null?Zd:"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(Ku(X.dropOverlay))}else{Dt.style.display="";let X=(ep=r.attachments)!=null?ep:{};ne&&(ne.accept=((tp=X.allowedTypes)!=null?tp:Nr).join(","),ne.multiple=((np=X.maxFiles)!=null?np:4)>1),tt&&tt.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Dt&&(Dt.style.display="none"),tt&&tt.clearAttachments(),(rp=ce.querySelector(".persona-attachment-drop-overlay"))==null||rp.remove();let Vt=(op=r.sendButton)!=null?op:{},vo=(sp=Vt.useIcon)!=null?sp:!1,Zr=(ap=Vt.iconText)!=null?ap:"\u2191",ht=Vt.iconName,Pn=(ip=Vt.tooltipText)!=null?ip:"Send message",Br=(lp=Vt.showTooltip)!=null?lp:!1,Sn=(cp=Vt.size)!=null?cp:"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=ye(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=(pp=(dp=r.copy)==null?void 0:dp.sendButtonLabel)!=null?pp:"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=(hp=(up=r.layout)==null?void 0:up.contentMaxWidth)!=null?hp:F()?(fp=(gp=(mp=r.launcher)==null?void 0:mp.composerBar)==null?void 0:gp.contentMaxWidth)!=null?fp:"720px":void 0;Bt?(_e.style.maxWidth=Bt,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%",Ft&&(Ft.style.maxWidth=Bt,Ft.style.marginLeft="auto",Ft.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="",Ft&&(Ft.style.maxWidth="",Ft.style.marginLeft="",Ft.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let Kt=(bp=r.statusIndicator)!=null?bp:{},Wn=(yp=Kt.visible)!=null?yp:!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(){yn=!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(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},T.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,b;return S.isStreaming()?!1:((b=(f=r.voiceRecognition)==null?void 0:f.provider)==null?void 0:b.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||bn()},hideEventStream(){fe&&Dn()},isEventStreamVisible(){return fe},showArtifacts(){ir(r)&&(yn=!1,jn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){ir(r)&&(yn=!0,jn())},upsertArtifact(c){return ir(r)?(yn=!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 A&&!B&&!F()||!de?!1:(de.focus(),!0)},async resolveApproval(c,f){let y=S.getMessages().find(M=>{var D;return M.variant==="approval"&&((D=M.approval)==null?void 0:D.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){S.resolveWebMcpApproval(y.id,f);return}return S.resolveApproval(y.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:A,voiceActive:mt.active,streaming:S.isStreaming()}},showCSATFeedback(c){!B&&_()&&Rt(!0,"system");let f=_e.querySelector(".persona-feedback-container");f&&f.remove();let b=cl({onSubmit:async(y,M)=>{var D;S.isClientTokenMode()&&await S.submitCSATFeedback(y,M),(D=c==null?void 0:c.onSubmit)==null||D.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!B&&_()&&Rt(!0,"system");let f=_e.querySelector(".persona-feedback-container");f&&f.remove();let b=dl({onSubmit:async(y,M)=>{var D;S.isClientTokenMode()&&await S.submitNPSFeedback(y,M),(D=c==null?void 0:c.onSubmit)==null||D.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(b),b.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=t==null?void 0:t.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:b=>b?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 H=U.detail;(!(H!=null&&H.instanceId)||H.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()},H=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",H),gt.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",H)})}let b=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&en.showArtifacts()},y=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&en.hideArtifacts()},M=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&en.upsertArtifact(H.artifact)},D=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&en.selectArtifact(H.id)},O=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",O),gt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",O)})}let or=Ty(r.persistState);if(or&&_()){let c=Ey(or.storage),f=`${or.keyPrefix}widget-open`,b=`${or.keyPrefix}widget-voice`,y=`${or.keyPrefix}widget-voice-mode`;if(c){let M=((yc=or.persist)==null?void 0:yc.openState)&&c.getItem(f)==="true",D=((xc=or.persist)==null?void 0:xc.voiceState)&&c.getItem(b)==="true",O=((vc=or.persist)==null?void 0:vc.voiceState)&&c.getItem(y)==="true";if(M&&setTimeout(()=>{en.open(),setTimeout(()=>{var U;if(D||O)en.startVoiceRecognition();else if((U=or.persist)!=null&&U.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(wc=or.persist)!=null&&wc.openState&&(o.on("widget:opened",()=>{c.setItem(f,"true")}),o.on("widget:closed",()=>{c.setItem(f,"false")})),(Cc=or.persist)!=null&&Cc.voiceState&&(o.on("voice:state",U=>{c.setItem(b,U.active?"true":"false")}),o.on("user:message",U=>{c.setItem(y,U.viaVoice?"true":"false")})),or.clearOnChatClear){let U=()=>{c.removeItem(f),c.removeItem(b),c.removeItem(y)},H=()=>U();window.addEventListener("persona:clear-chat",H),gt.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&_()&&setTimeout(()=>{en.open()},0),Rr(),en};var My=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},Ju=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},hl=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=""},Gu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",hl(e)},ml=e=>{e.style.transition=""},gl=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=""},fl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ui=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},ky=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Ly=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Xu=(e,n,t,r,s,o,a)=>{var v,x,T,A,R,P;let i=br(o),d=i.reveal==="push";ky(e,n,t,r,d),Ly(e,n,t,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",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.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=(A=(T=o==null?void 0:o.launcher)==null?void 0:T.mobileBreakpoint)!=null?A:640,g=l!=null?l.innerWidth<=m:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),gl(n),ml(r),Gu(r),fl(t),ui(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.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((P=(R=o==null?void 0:o.launcher)==null?void 0:R.zIndex)!=null?P:fn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Gu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",gl(n),ml(r),fl(t),ui(s,r);let W=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":L;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=W,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",ml(r),hl(r),ui(s,r);let W=My(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",I=i.side==="right"?a?`translateX(-${W}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${W}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${L+W}px`,n.style.transition=w,n.style.transform=I,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}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="",gl(n),hl(r),fl(t),ui(s,r);let W=i.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=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 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",r.style.position="relative",r.style.overflow=W||I?"hidden":"visible",r.style.transition=w,W&&(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")}},Py=(e,n)=>{let t=e.ownerDocument.createElement("div");return Ju(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Ju(t,r)},destroy(){t.remove()}}},Iy=(e,n)=>{var R,P,W,L;let{ownerDocument:t}=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=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),p=t.createElement("div"),m=(P=(R=n==null?void 0:n.launcher)==null?void 0:R.enabled)==null||P?(L=(W=n==null?void 0:n.launcher)==null?void 0:W.autoExpand)!=null?L:!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(),br(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Xu(a,i,d,l,p,n,m)}),g.observe(a))},x=()=>{Xu(a,i,d,l,p,n,m),v()},T=a.ownerDocument.defaultView,A=()=>{x()};return T==null||T.addEventListener("resize",A),br(n).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,F;n=w,((F=(I=n==null?void 0:n.launcher)==null?void 0:I.enabled)!=null?F:!0)===!1&&(m=!0),x()},destroy(){T==null||T.removeEventListener("resize",A),u(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},mi=(e,n)=>an(n)?Iy(e,n):Py(e,n);var bl={},Wy=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 n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},Ry=()=>{try{if(typeof bl!="undefined"&&bl.url)return new URL("../widget.css",bl.url).href}catch{}return null},Qu=(e,n)=>{let t=Ry(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},Yu=e=>{var T;let n=Wy(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=mi(n,s),a,i=[],d=(A,R)=>{var w,I;let W=!((I=(w=R==null?void 0:R.launcher)==null?void 0:w.enabled)!=null?I:!0)||an(R),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),W&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let F=A.attachShadow({mode:"open"});F.appendChild(L),Qu(F,r)}else A.appendChild(L),Qu(A,r);return n.id&&L.setAttribute("data-persona-instance",n.id),L},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},m=()=>{let A=d(o.host,s);a=ul(A,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(A=>A()),i=[],a.destroy()};m(),(T=e.onReady)==null||T.call(e);let u=A=>{g(),o.destroy(),o=mi(n,A),s=A,m()},v={update(A){var I,F,_,B,j,z;let R={...s,...A,launcher:{...(I=s==null?void 0:s.launcher)!=null?I:{},...(F=A==null?void 0:A.launcher)!=null?F:{},dock:{...(B=(_=s==null?void 0:s.launcher)==null?void 0:_.dock)!=null?B:{},...(z=(j=A==null?void 0:A.launcher)==null?void 0:j.dock)!=null?z:{}}}},P=an(s),W=an(R),L=no(s),w=no(R);if(P!==W||L!==w){u(R);return}s=R,o.updateConfig(s),a.update(A),l()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(A,R,P){if(R==="host")return o.host;if(R in A)return Reflect.get(A,R,P);let W=a[R];return typeof W=="function"?W.bind(a):W}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var rm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Hy=new Set(["button","a","input","select","textarea","details","summary"]),By=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),yl=/\b(product|card|item|listing|result)\b/i,vl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Dy=3e3,Ny=100;function om(e){let n=typeof e.className=="string"?e.className:"";if(yl.test(n)||e.id&&yl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&yl.test(r.value))return!0}return!1}function sm(e){var n;return vl.test(((n=e.textContent)!=null?n:"").trim())}function am(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Oy(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Zu(e){let n=e.match(vl);return n?n[0]:null}function em(e){var r,s,o;let n=(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(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Fy(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var _y="commerce-card",$y="result-card";function tm(e){return!om(e)||!sm(e)||!am(e)&&!Oy(e)?0:5200}function nm(e){var r;return!om(e)||sm(e)||!am(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 im=[{id:_y,scoreElement(e){return tm(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||vl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,p;if(tm(e)===0)return null;let{title:t,href:r}=em(e),s=(p=(l=Zu(((d=e.textContent)!=null?d:"").trim()))!=null?l:Zu(n.text))!=null?p:"",o=Fy(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.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(),Eo(e,r),ai(e,r),ii(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=Ri(()=>{Eo(e,r)}))};qr(),gt.push(()=>{Un&&(Un(),Un=null)});let tr=(dc=r.features)==null?void 0:dc.streamAnimation;if(tr!=null&&tr.type&&tr.type!=="none"){let c=Os(tr.type,tr.plugins);c&&(Di(c,e),gt.push(()=>tu(e)))}let cr=ku(Et),qn=null,S,zn=!1,dr=Gp(),Lr=new Map,wr=new Map,ss=0,pr=Oa(),ur=0,mr=null,Pr=!1,uo=!1,Ys=4,as=24,Zs=80,Wo=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=(uc=(pc=r.voiceRecognition)==null?void 0:pc.autoResume)!=null?uc:!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}}))},ea=()=>{var b,M;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=pl(d.voiceState),f=!!c.active,y=Number((M=c.timestamp)!=null?M:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-y<Ab&&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)},ta=()=>S?zu(S.getMessages()).filter(c=>!c.__skipPersist):[];function Ro(c){if(!(i!=null&&i.save))return;let y={messages:c?zu(c):S?ta():[],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,na=()=>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()&&ra(na(),c?220:140)})))},ra=(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)>=Zs){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)},oa=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&&il(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=Jp(E,ss)+Ke,kt=Te||Re?null:Xp(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:()=>Ui(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Qt.renderToolCall){if(!Ne)return;st=Qt.renderToolCall({message:E,defaultRenderer:()=>qi(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Qt.renderApproval){if(r.approval===!1)return;st=Qt.renderApproval({message:E,defaultRenderer:()=>Qi(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"&&tl(ht,E,r,S),ht},config:r}));if(!st&&Re){let ht=ll(E);if(ht){let Pn=wr.get(E.id),Br=Pn!==xe,Sn=r.wrapComponentDirectiveInBubble!==!1,In=null;if(Br){let Ht=al(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=Ui(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!Ne)return;st=qi(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;st=Qi(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&&tl(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),Qp(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)})})}Yp(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(Na(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,sa=()=>{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,aa=()=>{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,ia=()=>{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=ia(),U=ja(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)&&(Di(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?Ua(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),Na(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=qa(),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)}Na(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 la=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"),la(B),ce.style.display=B?"flex":"none",lr(),B?(sa(),aa()):(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=Ni(R,(F=(D=r.launcher)==null?void 0:D.zIndex)!=null?F:fn))}Gt||(Gt=Fi(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,ca=()=>{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=Sa(f-b))})},100))};if(S=new Is(r,{onMessagesChanged(c){go(_e,c,We),ca(),S&&(c.some(M=>M.role==="user")?cr.render([],S,de,c):cr.render(r.suggestionChips,S,de,c,r.suggestionChipsConfig)),Vr(!zn),oa(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,((gc=(mc=r.voiceRecognition)==null?void 0:mc.provider)==null?void 0:gc.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=pl(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(Pa(f))),de.value="",de.style.height="auto",fo(),S.sendMessage(f,{contentParts:b}),y&&tt.clearAttachments()},da=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Do={...Fa},No=!1,fo=()=>{Do={...Fa}},pa=()=>S.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),ua=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(da()&&(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=Kp({direction:c.key==="ArrowUp"?"up":"down",history:pa(),currentValue:de.value,atStart:f,state:Do});if(Do=y.state,y.handled){c.preventDefault(),y.value!==void 0&&ua(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=Tb(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")}}},ma=(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),ea(),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=Ni(un,(Qt=(st=r.launcher)==null?void 0:st.zIndex)!=null?Qt:fn)),Gt=Fi(e.ownerDocument)}else lt||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null)}}};Pt();let nn=(fc=e.ownerDocument.defaultView)!=null?fc: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:Ys,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=$a({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=(hc=e.ownerDocument)!=null?hc:document;Xt.addEventListener("keydown",bs,!0);let rr="persona-attachment-drop-active",ws=0,wi=()=>{ws=0,ce.classList.remove(rr)},Fo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&tt!==null},Al=c=>{!pi(c.dataTransfer)||!Fo()||(ws++,ws===1&&ce.classList.add(rr))},Sl=c=>{!pi(c.dataTransfer)||!Fo()||(ws--,ws<=0&&wi())},Tl=c=>{!pi(c.dataTransfer)||!Fo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},El=c=>{var y;if(!pi(c.dataTransfer)||!Fo())return;c.preventDefault(),c.stopPropagation(),wi();let f=Array.from((y=c.dataTransfer.files)!=null?y:[]);f.length!==0&&tt.handleFiles(f)},Yr=!0;ce.addEventListener("dragenter",Al,Yr),ce.addEventListener("dragleave",Sl,Yr),e.addEventListener("dragover",Tl,Yr),e.addEventListener("drop",El,Yr);let ga=e.ownerDocument,Ml=c=>{Fo()&&c.preventDefault()},kl=c=>{Fo()&&c.preventDefault()};ga.addEventListener("dragover",Ml),ga.addEventListener("drop",kl),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",Al,Yr),ce.removeEventListener("dragleave",Sl,Yr),e.removeEventListener("dragover",Tl,Yr),e.removeEventListener("drop",El,Yr),ga.removeEventListener("dragover",Ml),ga.removeEventListener("drop",kl),wi()}),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,fa,ha,ya,wo,ba,Cs,Ac,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;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=(fa=r.features)==null?void 0:fa.toolCallDisplay,pe=(ha=r.features)==null?void 0:ha.reasoningDisplay;r={...r,...c},lr(),Eo(e,r),ai(e,r),ii(e,r),jn(),r.colorScheme!==M&&qr();let Z=li.getForInstance(r.plugins);s.length=0,s.push(...Z),T=(wo=(ya=r.launcher)==null?void 0:ya.enabled)!=null?wo:!0,H=(Cs=(ba=r.launcher)==null?void 0:ba.autoExpand)!=null?Cs:!1,je=(Sc=(Ac=r.features)==null?void 0:Ac.showReasoning)!=null?Sc:!0,Ne=(Ec=(Tc=r.features)==null?void 0:Tc.showToolCalls)!=null?Ec:!0,ye=(kc=(Mc=r.features)==null?void 0:Mc.scrollToBottom)!=null?kc:{},zt(),Wr();let he=ge;if(ge=(Pc=(Lc=r.features)==null?void 0:Lc.showEventStreamToggle)!=null?Pc:!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=(Wc=(Ic=r.features)==null?void 0:Ic.eventStream)==null?void 0:Wc.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(((Rc=r.launcher)==null?void 0:Rc.enabled)===!1&&Ee&&(Ee.destroy(),Ee=null),((Hc=r.launcher)==null?void 0:Hc.enabled)===!1&&Je&&(Je.remove(),Je=null),((Bc=r.launcher)==null?void 0:Bc.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&&((Dc=r.launcher)==null?void 0:Dc.title)!==void 0&&(Ae.textContent=r.launcher.title),Be&&((Nc=r.launcher)==null?void 0:Nc.subtitle)!==void 0&&(Be.textContent=r.launcher.subtitle);let Se=(Fc=r.layout)==null?void 0:Fc.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=((Oc=r.layout)==null?void 0:Oc.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(($c=r.layout)==null?void 0:$c.messages)!==JSON.stringify(b),E=((jc=r.loadingIndicator)==null?void 0:jc.render)!==(D==null?void 0:D.render)||((Uc=r.loadingIndicator)==null?void 0:Uc.renderIdle)!==(D==null?void 0:D.renderIdle)||((qc=r.loadingIndicator)==null?void 0:qc.showBubble)!==(D==null?void 0:D.showBubble),Te=r.iterationDisplay!==F,Re=((Vc=(zc=r.features)==null?void 0:zc.showReasoning)!=null?Vc:!0)!==(U!=null?U:!0)||((Jc=(Kc=r.features)==null?void 0:Kc.showToolCalls)!=null?Jc:!0)!==(R!=null?R:!0)||JSON.stringify((Gc=r.features)==null?void 0:Gc.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Xc=r.features)==null?void 0:Xc.reasoningDisplay)!==JSON.stringify(pe);(ke||Me||qe||E||Te||Re)&&S&&(ss++,go(_e,S.getMessages(),We));let xe=(Qc=r.launcher)!=null?Qc:{},kt=(Yc=xe.headerIconHidden)!=null?Yc:!1,st=(ed=(Zc=r.layout)==null?void 0:Zc.header)==null?void 0:ed.showIcon,Qt=kt||st===!1,cn=xe.headerIconName,It=(td=xe.headerIconSize)!=null?td:"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=(nd=xe.agentIconText)!=null?nd:"\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=(rd=xe.agentIconText)!=null?rd:"\u{1F4AC}"}let Nt=N.querySelector("img");Nt&&(Nt.style.height=It,Nt.style.width=It)}}let Cn=(sd=(od=r.layout)==null?void 0:od.header)==null?void 0:sd.showTitle,dn=(id=(ad=r.layout)==null?void 0:ad.header)==null?void 0:id.showSubtitle;if(Ae&&(Ae.style.display=Cn===!1?"none":""),Be&&(Be.style.display=dn===!1?"none":""),Ue){((cd=(ld=r.layout)==null?void 0:ld.header)==null?void 0:cd.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let xt=(dd=xe.closeButtonSize)!=null?dd:"32px",Nt=(pd=xe.closeButtonPlacement)!=null?pd:"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=(md=(ud=xe.clearChat)==null?void 0:ud.placement)!=null?md:"inline",sn=(fd=(gd=xe.clearChat)==null?void 0:gd.enabled)!=null?fd:!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=(hd=xe.closeButtonIconName)!=null?hd:"x",fr=(yd=xe.closeButtonIconText)!=null?yd:"\xD7";Ue.innerHTML="";let Tn=be(mn,"28px","currentColor",1);Tn?Ue.appendChild(Tn):Ue.textContent=fr;let Yt=(bd=xe.closeButtonTooltipText)!=null?bd:"Close chat",Jn=(xd=xe.closeButtonShowTooltip)!=null?xd:!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=(vd=xe.clearChat)!=null?vd:{},xt=(wd=X.enabled)!=null?wd:!0,Nt=(Ad=(Cd=r.layout)==null?void 0:Cd.header)==null?void 0:Ad.showClearChat,ct=Nt!==void 0?Nt:xt,Tt=(Sd=X.placement)!=null?Sd:"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=(Td=X.size)!=null?Td:"32px";Ze.style.height=pt,Ze.style.width=pt}let on=(Ed=X.iconName)!=null?Ed:"refresh-cw",mn=(Md=X.iconColor)!=null?Md:"";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=(kd=X.tooltipText)!=null?kd:"Clear chat",Jn=(Ld=X.showTooltip)!=null?Ld:!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:[ci],un=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick];C=di({parsers:An,handlers:un,getSessionMetadata:g,updateSessionMetadata:u,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),We=Vu(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=((Pd=r.voiceRecognition)==null?void 0:Pd.enabled)===!0,bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),xo=((Wd=(Id=r.voiceRecognition)==null?void 0:Id.provider)==null?void 0:Wd.type)==="runtype";if(yo&&(bo||xo))if(!q||!_t){let X=ma(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=(Rd=r.voiceRecognition)!=null?Rd:{},xt=(Hd=r.sendButton)!=null?Hd:{},Nt=(Bd=X.iconName)!=null?Bd:"mic",ct=(Dd=xt.size)!=null?Dd:"40px",Tt=(Nd=X.iconSize)!=null?Nd:ct,on=parseFloat(Tt)||24;q.style.width=Tt,q.style.height=Tt,q.style.minWidth=Tt,q.style.minHeight=Tt;let mn=(Od=(Fd=X.iconColor)!=null?Fd:xt.textColor)!=null?Od:"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=($d=X.tooltipText)!=null?$d:"Start voice recognition";if(((jd=X.showTooltip)!=null?jd:!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",((qd=(Ud=r.voiceRecognition)==null?void 0:Ud.provider)==null?void 0:qd.type)==="runtype"?S.isVoiceActive()&&S.toggleVoice():Vn&&gr());if(((zd=r.attachments)==null?void 0:zd.enabled)===!0)if(!Dt||!Ye){let X=(Vd=r.attachments)!=null?Vd:{},Nt=(Jd=((Kd=r.sendButton)!=null?Kd:{}).size)!=null?Jd:"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=((Gd=X.allowedTypes)!=null?Gd:Nr).join(","),ne.multiple=((Xd=X.maxFiles)!=null?Xd: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",(Qd=X.buttonTooltipText)!=null?Qd:"Attach file");let ct=(Yd=X.buttonIconName)!=null?Yd:"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=(Zd=X.buttonTooltipText)!=null?Zd:"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(Ku(X.dropOverlay))}else{Dt.style.display="";let X=(ep=r.attachments)!=null?ep:{};ne&&(ne.accept=((tp=X.allowedTypes)!=null?tp:Nr).join(","),ne.multiple=((np=X.maxFiles)!=null?np:4)>1),tt&&tt.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Dt&&(Dt.style.display="none"),tt&&tt.clearAttachments(),(rp=ce.querySelector(".persona-attachment-drop-overlay"))==null||rp.remove();let Vt=(op=r.sendButton)!=null?op:{},vo=(sp=Vt.useIcon)!=null?sp:!1,Zr=(ap=Vt.iconText)!=null?ap:"\u2191",ht=Vt.iconName,Pn=(ip=Vt.tooltipText)!=null?ip:"Send message",Br=(lp=Vt.showTooltip)!=null?lp:!1,Sn=(cp=Vt.size)!=null?cp:"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=(pp=(dp=r.copy)==null?void 0:dp.sendButtonLabel)!=null?pp:"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=(hp=(up=r.layout)==null?void 0:up.contentMaxWidth)!=null?hp:O()?(fp=(gp=(mp=r.launcher)==null?void 0:mp.composerBar)==null?void 0:gp.contentMaxWidth)!=null?fp:"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=(yp=r.statusIndicator)!=null?yp:{},Wn=(bp=Kt.visible)!=null?bp:!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=cl({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=dl({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((((yc=t==null?void 0:t.debugTools)!=null?yc:!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=Eb(r.persistState);if(or&&_()){let c=Mb(or.storage),f=`${or.keyPrefix}widget-open`,y=`${or.keyPrefix}widget-voice`,b=`${or.keyPrefix}widget-voice-mode`;if(c){let M=((bc=or.persist)==null?void 0:bc.openState)&&c.getItem(f)==="true",D=((xc=or.persist)==null?void 0:xc.voiceState)&&c.getItem(y)==="true",F=((vc=or.persist)==null?void 0:vc.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),(wc=or.persist)!=null&&wc.openState&&(o.on("widget:opened",()=>{c.setItem(f,"true")}),o.on("widget:closed",()=>{c.setItem(f,"false")})),(Cc=or.persist)!=null&&Cc.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 kb=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},Ju=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},hl=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=""},Gu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",hl(e)},ml=e=>{e.style.transition=""},gl=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=""},fl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ui=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},Lb=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Pb=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Xu=(e,n,t,r,s,o,a)=>{var v,x,C,T,H,L;let i=yr(o),d=i.reveal==="push";Lb(e,n,t,r,d),Pb(e,n,t,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",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.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"),gl(n),ml(r),Gu(r),fl(t),ui(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.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&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Gu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",gl(n),ml(r),fl(t),ui(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",ml(r),hl(r),ui(s,r);let P=kb(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)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${W+P}px`,n.style.transition=w,n.style.transform=I,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${W}px`,t.style.maxWidth=`${W}px`,t.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="",gl(n),hl(r),fl(t),ui(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")}},Ib=(e,n)=>{let t=e.ownerDocument.createElement("div");return Ju(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Ju(t,r)},destroy(){t.remove()}}},Wb=(e,n)=>{var H,L,P,W;let{ownerDocument:t}=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=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),p=t.createElement("div"),m=(L=(H=n==null?void 0:n.launcher)==null?void 0:H.enabled)==null||L?(W=(P=n==null?void 0:n.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(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Xu(a,i,d,l,p,n,m)}),g.observe(a))},x=()=>{Xu(a,i,d,l,p,n,m),v()},C=a.ownerDocument.defaultView,T=()=>{x()};return C==null||C.addEventListener("resize",T),yr(n).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;n=w,((O=(I=n==null?void 0:n.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()}}},mi=(e,n)=>an(n)?Wb(e,n):Ib(e,n);var yl={},Qu=!1,Rb=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 n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},Hb=()=>{try{if(typeof yl!="undefined"&&yl.url)return new URL("../widget.css",yl.url).href}catch{}return null},Yu=(e,n)=>{let t=Hb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},Zu=e=>{let n=Rb(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=mi(n,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"),t){let I=C.attachShadow({mode:"open"});I.appendChild(P),Yu(I,r)}else C.appendChild(P),Yu(C,r);return n.id&&P.setAttribute("data-persona-instance",n.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=ul(C,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(C=>C()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(Qu||(Qu=!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=mi(n,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 om=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Bb=new Set(["button","a","input","select","textarea","details","summary"]),Db=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),bl=/\b(product|card|item|listing|result)\b/i,vl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Nb=3e3,Fb=100;function sm(e){let n=typeof e.className=="string"?e.className:"";if(bl.test(n)||e.id&&bl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&bl.test(r.value))return!0}return!1}function am(e){var n;return vl.test(((n=e.textContent)!=null?n:"").trim())}function im(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Ob(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function em(e){let n=e.match(vl);return n?n[0]:null}function tm(e){var r,s,o;let n=(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(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function _b(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var $b="commerce-card",jb="result-card";function nm(e){return!sm(e)||!am(e)||!im(e)&&!Ob(e)?0:5200}function rm(e){var r;return!sm(e)||am(e)||!im(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 lm=[{id:$b,scoreElement(e){return nm(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||vl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,p;if(nm(e)===0)return null;let{title:t,href:r}=tm(e),s=(p=(l=em(((d=e.textContent)!=null?d:"").trim()))!=null?l:em(n.text))!=null?p:"",o=_b(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
108
|
+
`)}},{id:jb,scoreElement(e){return rm(e)},formatSummary(e,n){if(rm(e)===0)return null;let{title:t,href:r}=tm(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
|
|
109
|
+
`)}}];function Ub(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function qb(e){var p,m,g,u,v,x,C,T,H,L,P,W,w;let n=(p=e.options)!=null?p:{},t=(g=(m=n.maxElements)!=null?m:e.maxElements)!=null?g:80,r=(v=(u=n.excludeSelector)!=null?u:e.excludeSelector)!=null?v:".persona-host",s=(C=(x=n.maxTextLength)!=null?x:e.maxTextLength)!=null?C:200,o=(H=(T=n.visibleOnly)!=null?T:e.visibleOnly)!=null?H:!0,a=(L=n.root)!=null?L:e.root,i=(P=n.mode)!=null?P:"structured",d=(W=n.maxCandidates)!=null?W:Math.max(500,t*10),l=(w=e.rules)!=null?w:lm;return i==="simple"&&e.rules&&e.rules.length>0?(Ub(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function xl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var zb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Vb(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||Bb.has(n)||t&&Db.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function cm(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Kb(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(n[p.name]=p.value)}return n}function dm(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${xl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of zb){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${xl(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>xl(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 > ${n}`)).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 > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function Jb(e){return e==="static"?Fb:Nb}function pm(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:dm(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:Vb(e),attributes:Kb(e)}}function Gb(e,n,t,r){let s=Jb(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Xb(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function Qb(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,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(om.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!cm(l)){i=a.nextNode();continue}let m=pm(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}=Gb(l,m,e.rules,t);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;Xb(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,t);u&&(p=u)}let m={...l.enriched};return p&&(m.formattedSummary=p),m})}function Yb(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(om.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!cm(d)){o=s.nextNode();continue}let p=pm(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),t.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Zb(e={}){var r;let n=qb(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?Yb(n,t):Qb(n,t):[]}var gi=100;function ex(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="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(`
|
|
@@ -120,7 +120,7 @@ ${a.join(`
|
|
|
120
120
|
${a.join(`
|
|
121
121
|
`)}`)}return r.join(`
|
|
122
122
|
|
|
123
|
-
`)}var
|
|
123
|
+
`)}var um={name:"@runtypelabs/persona",version:"3.27.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./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: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:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting","build:launcher":`tsup src/launcher-global.ts --format iife --global-name AgentWidgetLauncher --minify --sourcemap --splitting false --out-dir dist && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/launcher-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/launcher'+ext);}"`,lint:"eslint . --ext .ts",typecheck:"pnpm run check:runtype-types && tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit","fetch:runtype-openapi":"node scripts/fetch-runtype-openapi.mjs","generate:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs","check:runtype-types":"pnpm run fetch:runtype-openapi && node scripts/generate-runtype-openapi-types.mjs --check"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var os=um.version;function nx(){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 rx(){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 ox(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.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)}}),{...n,palette:t}}}}function sx(){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 ax(){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,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function ix(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var lx={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"}}},mm={components:{panel:{borderRadius:"0",shadow:"none"}}},gm={id:"shop",label:"Shopping Assistant",config:{theme:lx,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?"]}},fm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:mm}},hm={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:mm}},ym={shop:gm,minimal:fm,fullscreen:hm};function cx(e){return ym[e]}var dx=Zu;function Fr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function px(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 bm=`({ 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
|
+
}`,xm=`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
|
+
}`,vm=`(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
|
+
}`,wm=`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
|
+
}`,ux=`(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
|
+
}`,mx=`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 bx(e,n){let t=n==null?void 0:n.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: 'body',"," 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(...hi(e," ")),r.push(...bi(e," ",t)),r.push(...yi(e," ")),r.push(...xi(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${px}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${bm}`),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(` ${bm}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${xm}`),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(` ${xm}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.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 gx(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function fi(e){var n,t;return(t=(n=e.parserType)!=null?n:gx(e.streamParser))!=null?t:"plain"}function hi(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function yi(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function bi(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function xi(e,n){let t=[];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)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?t.push(`${n} ${d}: "${l}",`):typeof l=="boolean"&&t.push(`${n} ${d}: ${l},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function wl(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function Cm(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),Cm(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function co(e,n,t,r){t&&(e.push(`${r}${n}: {`),Cm(e,t,`${r} `),e.push(`${r}},`))}function fx(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:px(t.hooks)}:void 0;return n==="esm"?hx(r,s):n==="script-installer"?xx(r,s):n==="script-advanced"?wx(r,s):n==="react-component"?yx(r,s):n==="react-advanced"?bx(r,s):vx(r,s)}function hx(e,n){let t=n==null?void 0:n.hooks,r=fi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," 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(...hi(e," ")),o.push(...yi(e," ",t)),o.push(...bi(e," ")),o.push(...xi(e," ")),o.push(...wl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
|
|
196
|
+
`)}function yx(e,n){let t=n==null?void 0:n.hooks,r=fi(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: 'body',"," 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(...hi(e," ")),o.push(...yi(e," ",t)),o.push(...bi(e," ")),o.push(...xi(e," ")),o.push(...wl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.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 bx(e,n){let t=n==null?void 0:n.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: 'body',"," 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(...hi(e," ")),r.push(...yi(e," ",t)),r.push(...bi(e," ")),r.push(...xi(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${ux}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${bm}`),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(` ${bm}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${vm}`),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(` ${vm}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.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 Am(e){var s;let n=fi(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),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 xx(e,n){let t=Am(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,s=JSON.stringify(r,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/install.global.js" data-config='${s}'></script>`}function vx(e,n){let t=n==null?void 0:n.hooks,r=fi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.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(...hi(e," ")),o.push(...yi(e," ",t)),o.push(...bi(e," ")),o.push(...xi(e," ")),o.push(...wl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
|
|
199
|
+
`)}function wx(e,n){let t=n==null?void 0:n.hooks,r=Am(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
200
200
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
201
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${
|
|
202
|
-
`)}var
|
|
201
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${mx});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${xm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${xm}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${wm}`),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(` ${wm}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.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(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.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: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.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 Sm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Tm=.1,Em=.15,Mm=1.5,Cl=24,km=40,Cx=`
|
|
203
203
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
204
204
|
.persona-dc-root {
|
|
205
205
|
display: flex;
|
|
@@ -440,5 +440,5 @@ ${a.join(`
|
|
|
440
440
|
min-height: 300px;
|
|
441
441
|
}
|
|
442
442
|
}
|
|
443
|
-
`;function
|
|
443
|
+
`;function Ax(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Cx,document.head.appendChild(e)}function Sx(e,n){let t=e.clientWidth-Cl*2-km,r=e.clientHeight-Cl*2-km;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function Tx(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function Ex(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Ax();let p=Math.max(0,Math.min(r,t.length-1)),m=s,g=o,u=null,v=1,x=!1,C=h("div","persona-dc-root"),T=h("div","persona-dc-toolbar"),H=h("div","persona-dc-toolbar-lead"),L=h("div","persona-dc-toolbar-trail"),P=qt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>we(-1)}),W=h("div");W.style.position="relative";let w=h("button","persona-dc-title-btn");w.type="button",w.setAttribute("aria-expanded","false"),w.setAttribute("aria-haspopup","listbox");let I=h("span","persona-dc-title-text"),O=h("span","persona-dc-title-chevron"),_=be("chevron-down",12,"currentColor",2);_&&O.appendChild(_),w.append(I,O);let B=h("div","persona-dc-dropdown");B.setAttribute("role","listbox"),B.style.display="none";let j=!1;function z(){B.innerHTML="";for(let ue=0;ue<t.length;ue++){let ie=t[ue],re=h("button","persona-dc-dropdown-item");re.type="button",re.setAttribute("role","option"),re.setAttribute("aria-current",ue===p?"true":"false");let Qe=h("span");if(Qe.textContent=ie.title,re.appendChild(Qe),ie.description){let Ie=h("span","persona-dc-dropdown-desc");Ie.textContent=ie.description,re.appendChild(Ie)}re.addEventListener("click",()=>{We(),ze(ue)}),B.appendChild(re)}}function oe(){j=!j,B.style.display=j?"":"none",w.setAttribute("aria-expanded",j?"true":"false"),j&&z()}function We(){j&&(j=!1,B.style.display="none",w.setAttribute("aria-expanded","false"))}w.addEventListener("click",ue=>{ue.stopPropagation(),oe()});let je=()=>We();document.addEventListener("click",je),W.append(w,B);let Ne=qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>we(1)}),ge=h("span","persona-dc-counter");H.append(P,W,Ne,ge);let ye=null;i&&(ye=Ga({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:ue=>{m=ue,V.dataset.device=m,u=null,Q()}}),L.appendChild(ye.element));let Le=null;if(a){let ue=h("div","persona-dc-zoom-controls"),ie=qt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ie=u!=null?u:v;u=Math.max(Em,Ie-Tm),Q()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{u=1,Q()});let re=qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ie=u!=null?u:v;u=Math.min(Mm,Ie+Tm),Q()}}),Qe=qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{u=null,Q()}});ue.append(ie,Le,re,Qe),L.appendChild(ue)}if(d){let ue=h("div","persona-dc-separator");L.appendChild(ue);let ie=Ga({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:re=>{g=re,V.dataset.colorScheme=g,ve()}});L.appendChild(ie.element)}let He=h("div","persona-dc-separator");L.appendChild(He);let ee=qt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});L.appendChild(ee),T.append(H,L);let Pe=h("div","persona-dc-stage"),V=h("div","persona-dc-iframe-wrapper");V.dataset.device=m,V.dataset.colorScheme=g;let le=h("iframe","persona-dc-iframe");le.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),le.setAttribute("loading","lazy"),le.title=t[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=t[p];I.textContent=ue.title,ge.textContent=`${p+1} / ${t.length}`,le.title=ue.title}function we(ue){let ie=((p+ue)%t.length+t.length)%t.length;ze(ie)}function ze(ue){ue<0||ue>=t.length||(p=ue,le.src=t[p].url,fe(),l==null||l(p,t[p]))}function Q(){var re;if(x)return;let ue=(re=Sm[m])!=null?re:Sm.desktop;v=Sx(Pe,ue);let ie=Math.max(Em,Math.min(Mm,u!=null?u:v));Tx(V,le,ue,ie,m),Le&&(Le.textContent=`${Math.round(ie*100)}%`)}let te=new ResizeObserver(()=>Q());te.observe(Pe),fe(),le.src=t[p].url,requestAnimationFrame(()=>Q());function se(){x||(x=!0,te.disconnect(),document.removeEventListener("click",je),C.remove())}return{element:C,goTo:ze,next:()=>we(1),prev:()=>we(-1),getIndex:()=>p,setDevice(ue){m=ue,V.dataset.device=ue,ye==null||ye.setSelected(ue),u=null,Q()},setColorScheme(ue){g=ue,V.dataset.colorScheme=ue},setZoom(ue){u=ue,Q()},destroy:se}}export{hu as ASK_USER_QUESTION_TOOL_NAME,qo as AgentWidgetClient,Is as AgentWidgetSession,Ko as AttachmentManager,jp as DEFAULT_COMPONENTS,Li as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,_p as DEFAULT_PALETTE,$p as DEFAULT_SEMANTIC,Ft as DEFAULT_WIDGET_CONFIG,ym as PRESETS,hm as PRESET_FULLSCREEN,fm as PRESET_MINIMAL,gm as PRESET_SHOP,wh as THEME_ZONES,os as VERSION,wa as WEBMCP_TOOL_PREFIX,Es as WebMcpBridge,nx as accessibilityPlugin,rx as animationsPlugin,Eo as applyThemeVariables,Go as attachHeaderToContainer,ox as brandPlugin,zs as buildComposer,nu as buildDefaultHeader,ro as buildHeader,qs as buildHeaderWithLayout,ru as buildMinimalHeader,Zb as collectEnrichedPageContext,lo as componentRegistry,di as createActionManager,ul as createAgentExperience,Hy as createAskUserQuestionBubble,ki as createBestAvailableVoiceProvider,ry as createBubbleWithLayout,cl as createCSATFeedback,Oi as createComboButton,wb as createComponentMiddleware,sl as createComponentStreamParser,Ap as createDefaultSanitizer,Ex as createDemoCarousel,Wm as createDirectivePostprocessor,Mo as createDropdownMenu,Jm as createFlexibleJsonStreamParser,qt as createIconButton,og as createImagePart,Ti as createJsonStreamParser,Ja as createLabelButton,ol as createLocalStorageAdapter,xa as createMarkdownProcessor,$o as createMarkdownProcessorFromConfig,uu as createMessageActions,dl as createNPSFeedback,Ai as createPlainTextParser,ix as createPlugin,Si as createRegexJsonParser,Vs as createStandardBubble,Pa as createTextPart,Rs as createTheme,Ri as createThemeObserver,Ga as createToggleGroup,Xo as createTypingIndicator,Vo as createVoiceProvider,mi as createWidgetHostLayout,Ei as createXmlParser,dx as default,ns as defaultActionHandlers,ci as defaultJsonActionParser,lm as defaultParseRules,Da as detectColorScheme,Rm as directivePostprocessor,Js as ensureAskUserQuestionSheet,jo as escapeHtml,ll as extractComponentDirectiveFromMessage,sg as fileToImagePart,ex as formatEnrichedContext,zo as generateAssistantMessageId,fx as generateCodeSnippet,Zm as generateMessageId,dm as generateStableSelector,Ls as generateUserMessageId,Hs as getActiveTheme,Vp as getColorScheme,tg as getDisplayText,ou as getHeaderLayout,rg as getImageParts,cx as getPreset,il as hasComponentDirective,ng as hasImages,_i as headerLayouts,ax as highContrastPlugin,Zu as initAgentWidget,oo as isAskUserQuestionMessage,vb as isComponentDirectiveType,an as isDockedMountMode,Ha as isVoiceSupported,Ca as isWebMcpToolName,Ih as listRegisteredStreamAnimations,vp as markdownPostprocessor,Pi as mergeWithDefaults,eg as normalizeContent,so as parseAskUserQuestionPayload,li as pluginRegistry,sx as reducedMotionPlugin,Lh as registerStreamAnimationPlugin,Lo as removeAskUserQuestionSheet,al as renderComponentDirective,pu as renderLoadingIndicatorWithFallback,be as renderLucideIcon,yr as resolveDockConfig,Ts as resolveSanitizer,Ii as resolveTokens,Ep as stripWebMcpPrefix,Wi as themeToCssVariables,Ph as unregisterStreamAnimationPlugin,ag as validateImageFile,Up as validateTheme};
|
|
444
444
|
//# sourceMappingURL=index.js.map
|