@runtypelabs/persona 3.15.1 → 3.16.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/dist/index.cjs +46 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.global.js +61 -61
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +46 -46
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +169 -64
- package/dist/theme-editor.d.cts +11 -0
- package/dist/theme-editor.d.ts +11 -0
- package/dist/theme-editor.js +169 -64
- package/package.json +1 -1
- package/src/client.ts +169 -2
- package/src/components/header-builder.ts +18 -7
- package/src/components/header-layouts.ts +3 -1
- package/src/defaults.ts +6 -0
- package/src/types.ts +11 -0
- package/src/ui.ts +4 -2
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{Marked as
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
1
|
+
import{Marked as ip}from"marked";var lp=e=>{if(e)return e},bs=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new ip({gfm:(s=r==null?void 0:r.gfm)!=null?s:!0,breaks:(o=r==null?void 0:r.breaks)!=null?o:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=lp(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},Zr=e=>e?bs({markedOptions:e.options,renderer:e.renderer}):bs(),cp=bs(),Ac=e=>cp(e),Ho=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Ec=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Sc=e=>`%%FORM_PLACEHOLDER_${e}%%`,Tc=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Sc(r.length);return r.push({token:a,type:String(o.type)}),a}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,s)=>{let o=Sc(r.length);return r.push({token:o,type:s}),o}),t},dp=e=>{let r=Zr(e);return t=>{let n=[],s=Tc(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let u=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Ec(i)}"></div>`;o=o.replace(u,p)}),o}},pp=e=>{let r=[],t=Tc(e,r),n=Ac(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Ec(o)}"></div>`;n=n.replace(a,u)}),n};import up from"dompurify";var mp={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"]},gp=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Mc=()=>{let e=up(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!gp.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,mp)},Bo=e=>e===!1?null:typeof e=="function"?e:Mc();import{parse as kc,STR as Lc,OBJ as Ic}from"partial-json";var xs=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Qr=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)}},fp=e=>{var a,i;let r=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:r,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Pc=e=>e.status==="complete"?fp(e):e.status==="pending"?"Waiting":"",hp=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 Wc=e=>e.status==="complete"?hp(e):"Using tool...",vs=e=>{let r=e/1e3;return r<.1?"<0.1s":r>=10?`${Math.round(r)}s`:`${r.toFixed(1).replace(/\.0$/,"")}s`},No=e=>{var t,n,s;let r=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(n=e.startedAt)!=null?n:e.completedAt)!=null?s:Date.now()));return vs(r)},Cs=e=>{var t,n,s;let r=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(n=e.startedAt)!=null?n:e.completedAt)!=null?s:Date.now()));return vs(r)},ra=(e,r,t)=>{var o;if(!r)return t;let n=((o=e.name)==null?void 0:o.trim())||"tool",s=No(e);return r.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,s)},ws=(e,r)=>{let t=e.replace(/\{toolName\}/g,r),n=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Do(n,t.slice(o,a.index),[]),a[1]!==void 0?Do(n,a[1],["bold"]):a[2]!==void 0?Do(n,a[2],["italic"]):a[3]!==void 0&&Do(n,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Do(n,t.slice(o),[]),n},Do=(e,r,t)=>{let n=r.split("{duration}");for(let s=0;s<n.length;s++)n[s]&&e.push({text:n[s],styles:t}),s<n.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},yp=()=>{let e=null,r=0,t=n=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=n.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Hr=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},qs=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Us=()=>{var r;let e=hp();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},Vs=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=Mc(t,kc|Lc);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?as(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=as(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},yp=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?as(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?as(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:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=Mc(o,kc|Lc),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Js=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var ds=class{constructor(r,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=r,this.gapTimeoutMs=t}push(r,t){var o,a,i;let n=(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(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(r,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(r,t),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(r,t);return}let s=this.buffer.get(n);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${s.payloadType} vs ${r}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(n,{payloadType:r,payload:t,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let r=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(r.payloadType,r.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 r=[...this.buffer.entries()].sort((t,n)=>t[0]-n[0]);for(let[t,n]of r)this.buffer.delete(t),this.emitter(n.payloadType,n.payload);r.length>0&&(this.nextExpectedSeq=r[r.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var bp="https://api.runtype.com/v1/dispatch",Gs="https://api.runtype.com",Ys=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 xp(e){switch(e){case"json":return Vs;case"regex-json":return Us;case"xml":return Js;default:return qs}}var Wc=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function vp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=Wc(t);if(!Wc(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=Hr(e);return Hr(r)!==null&&a===null?r:e}var Gr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:bp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:xp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Gs;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,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 n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.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}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Gs}/v1/client/feedback`}async sendFeedback(r){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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,d={sessionId:u.sessionId,messages:r.messages.filter(Ys).map(g=>{var x,T,C;return{id:g.id,role:g.role,content:(C=(T=(x=g.contentParts)!=null?x:g.llmContent)!=null?T:g.rawContent)!=null?C:g.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:n.signal});if(!f.ok){let g=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let T=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:T}),T}if(f.status===429){let T=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:T}),T}let x=new Error(g.error||"Failed to send message");throw t({type:"error",error:x}),x}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.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:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.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:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.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,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Gs}/v1/agents/${r.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:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(Ys).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(Ys).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=p=>{let d={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 n.current=d,s(d),d},c=p=>n.current?n.current:u(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.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(r,t,n){var kt,dt,Wt,Jt;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,p=P=>{let $=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,ne=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,Pe=P.tools?P.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...P,reasoning:$,toolCall:ne,tools:Pe}},d=P=>{t({type:"message",message:p(P)})},f=null,g={current:null},x={current:null},T=!1,C=new Map,S=new Map,M={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=P=>{if(P==null)return null;try{return String(P)}catch{return null}},L=P=>{var $,ne,Pe,Fe,Ce;return w((Ce=(Fe=(Pe=(ne=($=P.stepId)!=null?$:P.step_id)!=null?ne:P.step)!=null?Pe:P.parentId)!=null?Fe:P.flowStepId)!=null?Ce:P.flow_step_id)},W=P=>{var $,ne,Pe,Fe,Ce,be,at;return w((at=(be=(Ce=(Fe=(Pe=(ne=($=P.callId)!=null?$:P.call_id)!=null?ne:P.requestId)!=null?Pe:P.request_id)!=null?Fe:P.toolCallId)!=null?Ce:P.tool_call_id)!=null?be:P.stepId)!=null?at:P.step_id)},E=n,K=!1,Q=()=>{if(f)return f;let P;return!K&&E?(P=E,K=!0):E&&x.current?P=`${E}_${x.current}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f},X=(P,$)=>{M.lastId=$,P&&M.byStep.set(P,$)},O=(P,$)=>{var Ce;let ne=(Ce=P.reasoningId)!=null?Ce:P.id,Pe=L(P);if(ne){let be=String(ne);return X(Pe,be),be}if(Pe){let be=M.byStep.get(Pe);if(be)return M.lastId=be,be}if(M.lastId&&!$)return M.lastId;if(!$)return null;let Fe=`reason-${c()}`;return X(Pe,Fe),Fe},oe=P=>{let $=C.get(P);if($)return $;let ne={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:P,status:"streaming",chunks:[]}};return C.set(P,ne),d(ne),ne},Ee=(P,$)=>{H.lastId=$,P&&H.byCall.set(P,$)},ae=new Set,we=new Map,$e=new Set,he=new Map,We=P=>{if(!P)return!1;let $=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return $==="emit_artifact_markdown"||$==="emit_artifact_component"},Re=(P,$)=>{var Ce;let ne=(Ce=P.toolId)!=null?Ce:P.id,Pe=W(P);if(ne){let be=String(ne);return Ee(Pe,be),be}if(Pe){let be=H.byCall.get(Pe);if(be)return H.lastId=be,be}if(H.lastId&&!$)return H.lastId;if(!$)return null;let Fe=`tool-${c()}`;return Ee(Pe,Fe),Fe},ie=P=>{let $=S.get(P);if($)return $;let ne={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:P,status:"pending"}};return S.set(P,ne),d(ne),ne},Z=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let $=Number(P);if(!Number.isNaN($)&&Number.isFinite($))return $;let ne=Date.parse(P);if(!Number.isNaN(ne))return ne}return Date.now()},me=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},V=new Map,re=new Map,He=new Map,ge=new Map,Be=null,st=(P,$,ne)=>{var at;let Pe=He.get(P);Pe||(Pe=[],He.set(P,Pe));let Fe=0,Ce=Pe.length;for(;Fe<Ce;){let mt=Fe+Ce>>>1;Pe[mt].seq<$?Fe=mt+1:Ce=mt}((at=Pe[Fe])==null?void 0:at.seq)===$?Pe[Fe]={seq:$,text:ne}:Pe.splice(Fe,0,{seq:$,text:ne});let be="";for(let mt=0;mt<Pe.length;mt++)be+=Pe[mt].text;return be},z=(P,$)=>{let ne=me($),Pe=re.get(P.id),Fe=vp(Pe,ne);P.rawContent=Fe;let Ce=V.get(P.id),be=xe=>{var Ze;let ue=(Ze=P.content)!=null?Ze:"";xe.trim()!==""&&(ue.trim().length===0||xe.startsWith(ue)||xe.trimStart().startsWith(ue.trim()))&&(P.content=xe)},at=()=>{var xe;if(Ce){let ue=(xe=Ce.close)==null?void 0:xe.call(Ce);ue instanceof Promise&&ue.catch(()=>{})}V.delete(P.id),re.delete(P.id),P.streaming=!1,d(P)};if(!Ce){be(ne),at();return}let mt=Hr(Fe);if(mt!==null&&mt.trim()!==""){be(mt),at();return}let At=xe=>{var qe;let ue=typeof xe=="string"?xe:(qe=xe==null?void 0:xe.text)!=null?qe:null;if(ue!==null&&ue.trim()!=="")return ue;let Ze=Ce.getExtractedText();return Ze!==null&&Ze.trim()!==""?Ze:ne},j;try{j=Ce.processChunk(Fe)}catch{be(ne),at();return}if(j instanceof Promise){j.then(xe=>{be(At(xe)),at()}).catch(()=>{be(ne),at()});return}be(At(j)),at()},U=[],se=!1,N,J=()=>{se||(se=!0,queueMicrotask(()=>{se=!1,N()}))},ce=new ds((P,$)=>{U.push({payloadType:P,payload:$}),J()}),fe=null,te=new Map,pe=(kt=this.config.iterationDisplay)!=null?kt:"separate";for(N=()=>{var P,$,ne,Pe,Fe,Ce,be,at,mt,At,j,xe,ue,Ze,qe,de,Te,Ve,vt,Ot,pt,$t,ht,Qe,yt,je,_t,zn,Kn,Wn,tt,Cr,qn,wr,An,Fr,ar,Xn,it,hn,Rn,nn,ir,yn,Et,rn,En,lr,Zn,cr,Un,bn,Vn,Ct,Bt,Dt,xn,dr,Hn,vn,D,Bn,Tn,pr,an,ln,le,Cn,Qn,_o,ao,jo,Or,et,io,Mn,cn,zo,qo,lo,er,Uo,Sr,co,tr,po,ur,mr,Vo,Jo,$s,Ar,Er,It,$r,_r,uo,Jn,Go,mo,go,fo,on,wn,nr,Je,ho,Tr,Dn,Yo,jr,zr,Mr,gr,Ko,Xo,Nn,kr,Zo;for(let qr=0;qr<U.length;qr++){let De=U[qr].payloadType,b=U[qr].payload;if(De==="reason_start"){let k=(P=O(b,!0))!=null?P:`reason-${c()}`,v=oe(k);v.reasoning=($=v.reasoning)!=null?$:{id:k,status:"streaming",chunks:[]},v.reasoning.startedAt=(Pe=v.reasoning.startedAt)!=null?Pe:Z((ne=b.startedAt)!=null?ne:b.timestamp),v.reasoning.completedAt=void 0,v.reasoning.durationMs=void 0,v.streaming=!0,v.reasoning.status="streaming",d(v)}else if(De==="reason_delta"||De==="reason_chunk"){let k=(Ce=(Fe=O(b,!1))!=null?Fe:O(b,!0))!=null?Ce:`reason-${c()}`,v=oe(k);v.reasoning=(be=v.reasoning)!=null?be:{id:k,status:"streaming",chunks:[]},v.reasoning.startedAt=(mt=v.reasoning.startedAt)!=null?mt:Z((at=b.startedAt)!=null?at:b.timestamp);let ee=(xe=(j=(At=b.reasoningText)!=null?At:b.text)!=null?j:b.delta)!=null?xe:"";if(ee&&b.hidden!==!0){let q=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(q!==void 0){let Le=st(k,q,String(ee));v.reasoning.chunks=[Le]}else v.reasoning.chunks.push(String(ee))}if(v.reasoning.status=b.done?"complete":"streaming",b.done){v.reasoning.completedAt=Z((ue=b.completedAt)!=null?ue:b.timestamp);let q=(Ze=v.reasoning.startedAt)!=null?Ze:Date.now();v.reasoning.durationMs=Math.max(0,((qe=v.reasoning.completedAt)!=null?qe:Date.now())-q)}v.streaming=v.reasoning.status!=="complete",d(v)}else if(De==="reason_complete"){let k=(Te=(de=O(b,!1))!=null?de:O(b,!0))!=null?Te:`reason-${c()}`,v=C.get(k);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=Z((Ve=b.completedAt)!=null?Ve:b.timestamp);let q=(vt=v.reasoning.startedAt)!=null?vt:Date.now();v.reasoning.durationMs=Math.max(0,((Ot=v.reasoning.completedAt)!=null?Ot:Date.now())-q),v.streaming=!1,d(v)}let ee=L(b);ee&&M.byStep.delete(ee)}else if(De==="tool_start"){let k=(pt=Re(b,!0))!=null?pt:`tool-${c()}`,v=($t=b.toolName)!=null?$t:b.name;if(We(v)){ae.add(k);continue}let ee=ie(k),q=(ht=ee.toolCall)!=null?ht:{id:k,status:"pending"};q.name=v!=null?v:q.name,q.status="running",b.args!==void 0?q.args=b.args:b.parameters!==void 0&&(q.args=b.parameters),q.startedAt=(yt=q.startedAt)!=null?yt:Z((Qe=b.startedAt)!=null?Qe:b.timestamp),q.completedAt=void 0,q.durationMs=void 0,ee.toolCall=q,ee.streaming=!0;let Le=b.agentContext;(Le||b.executionId)&&(ee.agentMetadata={executionId:(je=Le==null?void 0:Le.executionId)!=null?je:b.executionId,iteration:(_t=Le==null?void 0:Le.iteration)!=null?_t:b.iteration}),d(ee)}else if(De==="tool_chunk"||De==="tool_delta"){let k=(Kn=(zn=Re(b,!1))!=null?zn:Re(b,!0))!=null?Kn:`tool-${c()}`;if(ae.has(k))continue;let v=ie(k),ee=(Wn=v.toolCall)!=null?Wn:{id:k,status:"running"};ee.startedAt=(Cr=ee.startedAt)!=null?Cr:Z((tt=b.startedAt)!=null?tt:b.timestamp);let q=(An=(wr=(qn=b.text)!=null?qn:b.delta)!=null?wr:b.message)!=null?An:"";q&&(ee.chunks=(Fr=ee.chunks)!=null?Fr:[],ee.chunks.push(String(q))),ee.status="running",v.toolCall=ee,v.streaming=!0;let Le=b.agentContext;(Le||b.executionId)&&(v.agentMetadata=(it=v.agentMetadata)!=null?it:{executionId:(ar=Le==null?void 0:Le.executionId)!=null?ar:b.executionId,iteration:(Xn=Le==null?void 0:Le.iteration)!=null?Xn:b.iteration}),d(v)}else if(De==="tool_complete"){let k=(Rn=(hn=Re(b,!1))!=null?hn:Re(b,!0))!=null?Rn:`tool-${c()}`;if(ae.has(k)){ae.delete(k);continue}let v=ie(k),ee=(nn=v.toolCall)!=null?nn:{id:k,status:"running"};ee.status="complete",b.result!==void 0&&(ee.result=b.result),typeof b.duration=="number"&&(ee.duration=b.duration),ee.completedAt=Z((ir=b.completedAt)!=null?ir:b.timestamp);let q=(yn=b.duration)!=null?yn:b.executionTime;if(typeof q=="number")ee.durationMs=q;else{let Rt=(Et=ee.startedAt)!=null?Et:Date.now();ee.durationMs=Math.max(0,((rn=ee.completedAt)!=null?rn:Date.now())-Rt)}v.toolCall=ee,v.streaming=!1;let Le=b.agentContext;(Le||b.executionId)&&(v.agentMetadata=(Zn=v.agentMetadata)!=null?Zn:{executionId:(En=Le==null?void 0:Le.executionId)!=null?En:b.executionId,iteration:(lr=Le==null?void 0:Le.iteration)!=null?lr:b.iteration}),d(v);let Xe=W(b);Xe&&H.byCall.delete(Xe)}else if(De==="text_start"){let k=b.partId;if(k!==void 0&&x.current!==null&&k!==x.current){let v=f;v&&(v.streaming=!1,d(v),Be=v,f=null,T=!0)}k!==void 0&&(x.current=k)}else if(De==="text_end"){let k=f;k&&(k.streaming=!1,d(k),Be=k,f=null,T=!0)}else if(De==="step_chunk"||De==="step_delta"){let k=b.stepType,v=b.executionType;if(k==="tool"||v==="context")continue;let ee=b.partId;if(ee!==void 0&&x.current!==null&&ee!==x.current){let Xe=f;Xe&&(Xe.streaming=!1,d(Xe),Be=Xe,f=null,T=!0)}ee!==void 0&&(x.current=ee);let q=ee!==void 0&&(cr=ge.get(ee))!=null?cr:Q();ee!==void 0&&(q.partId||(q.partId=ee),ge.set(ee,q));let Le=(Ct=(Vn=(bn=(Un=b.text)!=null?Un:b.delta)!=null?bn:b.content)!=null?Vn:b.chunk)!=null?Ct:"";if(Le){let Xe=typeof b.seq=="number"?b.seq:void 0,Rt=ee!=null?ee:q.id,wt=Xe!==void 0?st(Rt,Xe,String(Le)):((Bt=re.get(q.id))!=null?Bt:"")+Le;q.rawContent=wt,V.has(q.id)||V.set(q.id,this.createStreamParser());let Gt=V.get(q.id),Ht=wt.trim().startsWith("{")||wt.trim().startsWith("[");if(Ht&&re.set(q.id,wt),Gt.__isPlainTextParser===!0){q.content=Xe!==void 0?wt:q.content+Le,re.delete(q.id),V.delete(q.id),q.rawContent=void 0,d(q);continue}let rt=Gt.processChunk(wt);if(rt instanceof Promise)rt.then(ut=>{var Fn;let zt=typeof ut=="string"?ut:(Fn=ut==null?void 0:ut.text)!=null?Fn:null;if(zt!==null&&zt.trim()!=="")q.content=zt,d(q);else if(!Ht&&!wt.trim().startsWith("<")){let bt=f,Nt=bt&&bt.id===q.id?bt:q;Nt.id===q.id&&(Nt.content=Xe!==void 0?wt:Nt.content+Le,re.delete(Nt.id),V.delete(Nt.id),Nt.rawContent=void 0,d(Nt))}}).catch(()=>{q.content=Xe!==void 0?wt:q.content+Le,re.delete(q.id),V.delete(q.id),q.rawContent=void 0,d(q)});else{let ut=typeof rt=="string"?rt:(Dt=rt==null?void 0:rt.text)!=null?Dt:null;ut!==null&&ut.trim()!==""?(q.content=ut,d(q)):!Ht&&!wt.trim().startsWith("<")&&(q.content=Xe!==void 0?wt:q.content+Le,re.delete(q.id),V.delete(q.id),q.rawContent=void 0,d(q))}}if(b.isComplete){let Xe=(dr=(xn=b.result)==null?void 0:xn.response)!=null?dr:q.content;if(Xe){let Rt=re.get(q.id),wt=Rt!=null?Rt:me(Xe);q.rawContent=wt;let Gt=V.get(q.id),Ht=null,Zt=!1;if(Gt&&(Ht=Gt.getExtractedText(),Ht===null&&(Ht=Hr(wt)),Ht===null)){let rt=Gt.processChunk(wt);rt instanceof Promise?(Zt=!0,rt.then(ut=>{var Fn;let zt=typeof ut=="string"?ut:(Fn=ut==null?void 0:ut.text)!=null?Fn:null;if(zt!==null){let bt=f;bt&&bt.id===q.id&&(bt.content=zt,bt.streaming=!1,V.delete(bt.id),re.delete(bt.id),d(bt))}})):Ht=typeof rt=="string"?rt:(Hn=rt==null?void 0:rt.text)!=null?Hn:null}if(!Zt){Ht!==null&&Ht.trim()!==""?q.content=Ht:re.has(q.id)||(q.content=me(Xe));let rt=V.get(q.id);if(rt){let ut=(vn=rt.close)==null?void 0:vn.call(rt);ut instanceof Promise&&ut.catch(()=>{}),V.delete(q.id)}re.delete(q.id),q.streaming=!1,d(q)}}}}else if(De==="step_complete"){let k=b.stepType,v=b.executionType;if(k==="tool"||v==="context")continue;if(T){if(f!==null){let Rt=f;V.delete(Rt.id),re.delete(Rt.id),Rt.streaming!==!1&&(Rt.streaming=!1,d(Rt))}let Le=(D=b.result)==null?void 0:D.response,Xe=Be;Xe&&(Le!=null?z(Xe,Le):(V.delete(Xe.id),re.delete(Xe.id))),Be=null;continue}let ee=(Bn=b.result)==null?void 0:Bn.response,q=Q();if(ee!=null){let Le=V.get(q.id),Xe=!1,Rt=!1;if(Le){let wt=Le.getExtractedText(),Gt=re.get(q.id),Ht=Gt!=null?Gt:me(ee);if(q.rawContent=Ht,wt!==null&&wt.trim()!=="")q.content=wt,Xe=!0;else{let Zt=Hr(Ht);if(Zt!==null)q.content=Zt,Xe=!0;else{let rt=Le.processChunk(Ht);if(rt instanceof Promise)Rt=!0,rt.then(ut=>{var Fn;let zt=typeof ut=="string"?ut:(Fn=ut==null?void 0:ut.text)!=null?Fn:null;if(zt!==null&&zt.trim()!==""){let bt=f;bt&&bt.id===q.id&&(bt.content=zt,bt.streaming=!1,V.delete(bt.id),re.delete(bt.id),d(bt))}else{let bt=Le.getExtractedText(),Nt=f;Nt&&Nt.id===q.id&&(bt!==null&&bt.trim()!==""?Nt.content=bt:re.has(Nt.id)||(Nt.content=me(ee)),Nt.streaming=!1,V.delete(Nt.id),re.delete(Nt.id),d(Nt))}});else{let ut=typeof rt=="string"?rt:(Tn=rt==null?void 0:rt.text)!=null?Tn:null;if(ut!==null&&ut.trim()!=="")q.content=ut,Xe=!0;else{let zt=Le.getExtractedText();zt!==null&&zt.trim()!==""&&(q.content=zt,Xe=!0)}}}}}if(!Rt){if(!q.rawContent){let wt=re.get(q.id);q.rawContent=wt!=null?wt:me(ee)}if(!Xe&&!re.has(q.id)&&(q.content=me(ee)),Le){let wt=(pr=Le.close)==null?void 0:pr.call(Le);wt instanceof Promise&&wt.catch(()=>{})}V.delete(q.id),re.delete(q.id),q.streaming=!1,d(q)}}else V.delete(q.id),re.delete(q.id),q.streaming=!1,d(q)}else if(De==="flow_complete"){let k=(an=b.result)==null?void 0:an.response;if(T){if(f!==null){let v=f;V.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,d(v))}}else if(k!=null){let v=Q(),ee=re.get(v.id),q=ee!=null?ee:me(k);v.rawContent=q;let Le=me(k),Xe=V.get(v.id);if(Xe){let Gt=Hr(q);if(Gt!==null)Le=Gt;else{let Ht=Xe.processChunk(q);Ht instanceof Promise&&Ht.then(rt=>{var zt;let ut=typeof rt=="string"?rt:(zt=rt==null?void 0:rt.text)!=null?zt:null;ut!==null&&(v.content=ut,v.streaming=!1,d(v))});let Zt=Xe.getExtractedText();Zt!==null&&(Le=Zt)}}V.delete(v.id),re.delete(v.id);let Rt=Le!==v.content,wt=v.streaming!==!1;Rt&&(v.content=Le),v.streaming=!1,(Rt||wt)&&d(v)}else if(f!==null){let v=f;V.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,d(v))}t({type:"status",status:"idle"})}else if(De==="agent_start")fe={executionId:b.executionId,agentId:(ln=b.agentId)!=null?ln:"virtual",agentName:(le=b.agentName)!=null?le:"",status:"running",currentIteration:0,maxTurns:(Cn=b.maxTurns)!=null?Cn:1,startedAt:Z(b.startedAt)};else if(De==="agent_iteration_start"){if(fe&&(fe.currentIteration=b.iteration),pe==="separate"&&b.iteration>1){let k=f;k&&(k.streaming=!1,d(k),te.set(b.iteration-1,k),f=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(b.contentType==="text"){let k=Q();k.content+=(Qn=b.delta)!=null?Qn:"",k.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:fe==null?void 0:fe.agentName},d(k)}else if(b.contentType==="thinking"){let k=(_o=b.turnId)!=null?_o:`agent-think-${b.iteration}`,v=oe(k);v.reasoning=(ao=v.reasoning)!=null?ao:{id:k,status:"streaming",chunks:[]},v.reasoning.chunks.push((jo=b.delta)!=null?jo:""),v.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},d(v)}else if(b.contentType==="tool_input"){let k=(Or=b.toolCallId)!=null?Or:H.lastId;if(k){let v=S.get(k);v!=null&&v.toolCall&&(v.toolCall.chunks=(et=v.toolCall.chunks)!=null?et:[],v.toolCall.chunks.push((io=b.delta)!=null?io:""),d(v))}}}else if(De==="agent_turn_complete"){let k=b.turnId;if(k){let v=C.get(k);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=Z(b.completedAt);let ee=(Mn=v.reasoning.startedAt)!=null?Mn:Date.now();v.reasoning.durationMs=Math.max(0,((cn=v.reasoning.completedAt)!=null?cn:Date.now())-ee),v.streaming=!1,d(v)}}}else if(De==="agent_tool_start"){let k=(zo=b.toolCallId)!=null?zo:`agent-tool-${c()}`;Ee(W(b),k);let v=ie(k),ee=(qo=v.toolCall)!=null?qo:{id:k,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};ee.name=(er=(lo=b.toolName)!=null?lo:b.name)!=null?er:ee.name,ee.status="running",b.parameters!==void 0&&(ee.args=b.parameters),ee.startedAt=Z((Uo=b.startedAt)!=null?Uo:b.timestamp),v.toolCall=ee,v.streaming=!0,v.agentMetadata={executionId:b.executionId,iteration:b.iteration},d(v)}else if(De==="agent_tool_delta"){let k=(Sr=b.toolCallId)!=null?Sr:H.lastId;if(k){let v=(co=S.get(k))!=null?co:ie(k);v.toolCall&&(v.toolCall.chunks=(tr=v.toolCall.chunks)!=null?tr:[],v.toolCall.chunks.push((po=b.delta)!=null?po:""),v.toolCall.status="running",v.streaming=!0,d(v))}}else if(De==="agent_tool_complete"){let k=(ur=b.toolCallId)!=null?ur:H.lastId;if(k){let v=(mr=S.get(k))!=null?mr:ie(k);if(v.toolCall){v.toolCall.status="complete",b.result!==void 0&&(v.toolCall.result=b.result),typeof b.executionTime=="number"&&(v.toolCall.durationMs=b.executionTime),v.toolCall.completedAt=Z((Vo=b.completedAt)!=null?Vo:b.timestamp),v.streaming=!1,d(v);let ee=W(b);ee&&H.byCall.delete(ee)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let k=`agent-reflection-${b.executionId}-${b.iteration}`,v={id:k,role:"assistant",content:(Jo=b.reflection)!=null?Jo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:k,status:"complete",chunks:[($s=b.reflection)!=null?$s:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};d(v)}else if(De==="agent_complete"){fe&&(fe.status=b.success?"complete":"error",fe.completedAt=Z(b.completedAt),fe.stopReason=b.stopReason);let k=f;k&&(k.streaming=!1,d(k)),t({type:"status",status:"idle"})}else if(De==="agent_error"){let k=typeof b.error=="string"?b.error:(Er=(Ar=b.error)==null?void 0:Ar.message)!=null?Er:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",k):t({type:"error",error:new Error(k)})}else if(De!=="agent_ping"){if(De==="agent_approval_start"){let k=(It=b.approvalId)!=null?It:`approval-${c()}`,v={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:"pending",agentId:($r=fe==null?void 0:fe.agentId)!=null?$r:"virtual",executionId:(uo=(_r=b.executionId)!=null?_r:fe==null?void 0:fe.executionId)!=null?uo:"",toolName:(Jn=b.toolName)!=null?Jn:"",toolType:b.toolType,description:(mo=b.description)!=null?mo:`Execute ${(Go=b.toolName)!=null?Go:"tool"}`,parameters:b.parameters}};d(v)}else if(De==="step_await"&&b.awaitReason==="approval_required"){let k=(go=b.approvalId)!=null?go:`approval-${c()}`,v={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:"pending",agentId:(fo=fe==null?void 0:fe.agentId)!=null?fo:"virtual",executionId:(wn=(on=b.executionId)!=null?on:fe==null?void 0:fe.executionId)!=null?wn:"",toolName:(nr=b.toolName)!=null?nr:"",toolType:b.toolType,description:(ho=b.description)!=null?ho:`Execute ${(Je=b.toolName)!=null?Je:"tool"}`,parameters:b.parameters}};d(v)}else if(De==="agent_approval_complete"){let k=b.approvalId;if(k){let ee={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:(Tr=b.decision)!=null?Tr:"approved",agentId:(Dn=fe==null?void 0:fe.agentId)!=null?Dn:"virtual",executionId:(jr=(Yo=b.executionId)!=null?Yo:fe==null?void 0:fe.executionId)!=null?jr:"",toolName:(zr=b.toolName)!=null?zr:"",description:(Mr=b.description)!=null?Mr:"",resolvedAt:Date.now()}};d(ee)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let k=b.artifactType,v=String(b.id),ee=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:v,artifactType:k,title:ee,component:typeof b.component=="string"?b.component:void 0}),he.set(v,{markdown:"",title:ee}),!$e.has(v)){$e.add(v);let q={id:`artifact-ref-${v}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:v,title:ee,artifactType:k,status:"streaming"}})};we.set(v,q),d(q)}}else if(De==="artifact_delta"){let k=String(b.id),v=typeof b.delta=="string"?b.delta:String((gr=b.delta)!=null?gr:"");t({type:"artifact_delta",id:k,artDelta:v});let ee=he.get(k);ee&&(ee.markdown+=v)}else if(De==="artifact_update"){let k=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:k,component:typeof b.component=="string"?b.component:void 0})}else if(De==="artifact_complete"){let k=String(b.id);t({type:"artifact_complete",id:k});let v=we.get(k);if(v){v.streaming=!1;try{let ee=JSON.parse((Ko=v.rawContent)!=null?Ko:"{}");if(ee.props){ee.props.status="complete";let q=he.get(k);q!=null&&q.markdown&&(ee.props.markdown=q.markdown)}v.rawContent=JSON.stringify(ee)}catch{}he.delete(k),d(v),we.delete(k)}}}else if(De==="transcript_insert"){let k=b.message;if(!k||typeof k!="object")continue;let v=String((Xo=k.id)!=null?Xo:`msg-${c()}`),ee=k.role,Le={id:v,role:ee==="user"?"user":ee==="system"?"system":"assistant",content:typeof k.content=="string"?k.content:"",rawContent:typeof k.rawContent=="string"?k.rawContent:void 0,createdAt:typeof k.createdAt=="string"?k.createdAt:new Date().toISOString(),streaming:k.streaming===!0,...typeof k.variant=="string"?{variant:k.variant}:{},sequence:c()};if(d(Le),Le.rawContent)try{let Xe=JSON.parse(Le.rawContent),Rt=(Nn=Xe==null?void 0:Xe.props)==null?void 0:Nn.artifactId;typeof Rt=="string"&&$e.add(Rt)}catch{}f=null,g.current=null,V.delete(v),re.delete(v)}else if(De==="error"||De==="step_error"||De==="dispatch_error"||De==="flow_error"){let k=null;if(b.error instanceof Error)k=b.error;else if(De==="dispatch_error"){let v=(kr=b.message)!=null?kr:b.error;v!=null&&v!==""&&(k=new Error(String(v)))}else if(De==="step_error"||De==="flow_error"){let v=b.error;typeof v=="string"&&v!==""?k=new Error(v):v!=null&&typeof v=="object"&&"message"in v&&(k=new Error(String((Zo=v.message)!=null?Zo:v)))}else De==="error"&&b.error!=null&&b.error!==""&&(k=new Error(String(b.error)));if(k){t({type:"error",error:k});let v=f;v&&v.streaming&&(v.streaming=!1,d(v)),t({type:"status",status:"idle"})}}}}}}U.length=0};;){let{done:P,value:$}=await s.read();if(P)break;a+=o.decode($,{stream:!0});let ne=a.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},$r=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},oa=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},sa=()=>{var r;let e=yp();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},aa=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=kc(t,Lc|Ic);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?xs(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=xs(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},bp=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?xs(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?xs(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:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=kc(o,Lc|Ic),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},ia=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var Ss=class{constructor(r,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=r,this.gapTimeoutMs=t}push(r,t){var o,a,i;let n=(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(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(r,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(r,t),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(r,t);return}let s=this.buffer.get(n);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${s.payloadType} vs ${r}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(n,{payloadType:r,payload:t,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let r=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(r.payloadType,r.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 r=[...this.buffer.entries()].sort((t,n)=>t[0]-n[0]);for(let[t,n]of r)this.buffer.delete(t),this.emitter(n.payloadType,n.payload);r.length>0&&(this.nextExpectedSeq=r[r.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var xp="https://api.runtype.com/v1/dispatch",la="https://api.runtype.com",ca=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 vp(e){switch(e){case"json":return aa;case"regex-json":return sa;case"xml":return ia;default:return oa}}var Rc=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Cp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=Rc(t);if(!Rc(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=$r(e);return $r(r)!==null&&a===null?r:e}var eo=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:xp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:vp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||la;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,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 n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.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}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||la}/v1/client/feedback`}async sendFeedback(r){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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,d={sessionId:u.sessionId,messages:r.messages.filter(ca).map(g=>{var x,M,w;return{id:g.id,role:g.role,content:(w=(M=(x=g.contentParts)!=null?x:g.llmContent)!=null?M:g.rawContent)!=null?w:g.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:n.signal});if(!f.ok){let g=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(f.status===429){let M=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let x=new Error(g.error||"Failed to send message");throw t({type:"error",error:x}),x}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.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:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.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:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.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,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||la}/v1/agents/${r.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:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(ca).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(ca).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=p=>{let d={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 n.current=d,s(d),d},c=p=>n.current?n.current:u(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.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(r,t,n){var ge,Ge,Wt,Rt;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,p=W=>{let X=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,Se=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Fe=W.tools?W.tools.map(Ve=>({...Ve,chunks:Ve.chunks?[...Ve.chunks]:void 0})):void 0;return{...W,reasoning:X,toolCall:Se,tools:Fe}},d=W=>{t({type:"message",message:p(W)})},f=null,g={current:null},x={current:null},M=!1,w=new Map,S=new Map,k=new Map,$=new Map,v={lastId:null,byStep:new Map},T={lastId:null,byCall:new Map},B=(W,X,Se="")=>`${W}::${X}::${Se}`,E=(W,X)=>`${W}::${X}::`,K=(W,X,Se,Fe)=>{let Ve=B(W,X,Se),I=k.get(Ve);if(I)return I;let te=Se?`-${Se}`:"",Z={id:`nested-${W}-${X}${te}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Se?{partId:Se}:{},agentMetadata:{executionId:Fe,parentToolId:W,parentStepId:X}};return k.set(Ve,Z),d(Z),Z},Q=W=>{if(W==null)return null;try{return String(W)}catch{return null}},G=W=>{var X,Se,Fe,Ve,I;return Q((I=(Ve=(Fe=(Se=(X=W.stepId)!=null?X:W.step_id)!=null?Se:W.step)!=null?Fe:W.parentId)!=null?Ve:W.flowStepId)!=null?I:W.flow_step_id)},j=W=>{var X,Se,Fe,Ve,I,te,Z;return Q((Z=(te=(I=(Ve=(Fe=(Se=(X=W.callId)!=null?X:W.call_id)!=null?Se:W.requestId)!=null?Fe:W.request_id)!=null?Ve:W.toolCallId)!=null?I:W.tool_call_id)!=null?te:W.stepId)!=null?Z:W.step_id)},re=n,Te=!1,oe=()=>{if(f)return f;let W;return!Te&&re?(W=re,Te=!0):re&&x.current?W=`${re}_${x.current}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:W,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f},Ce=(W,X)=>{v.lastId=X,W&&v.byStep.set(W,X)},Ne=(W,X)=>{var I;let Se=(I=W.reasoningId)!=null?I:W.id,Fe=G(W);if(Se){let te=String(Se);return Ce(Fe,te),te}if(Fe){let te=v.byStep.get(Fe);if(te)return v.lastId=te,te}if(v.lastId&&!X)return v.lastId;if(!X)return null;let Ve=`reason-${c()}`;return Ce(Fe,Ve),Ve},he=W=>{let X=w.get(W);if(X)return X;let Se={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:W,status:"streaming",chunks:[]}};return w.set(W,Se),d(Se),Se},ke=(W,X)=>{T.lastId=X,W&&T.byCall.set(W,X)},Be=new Set,ue=new Map,Y=new Set,ye=new Map,de=W=>{if(!W)return!1;let X=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return X==="emit_artifact_markdown"||X==="emit_artifact_component"},we=(W,X)=>{var I;let Se=(I=W.toolId)!=null?I:W.id,Fe=j(W);if(Se){let te=String(Se);return ke(Fe,te),te}if(Fe){let te=T.byCall.get(Fe);if(te)return T.lastId=te,te}if(T.lastId&&!X)return T.lastId;if(!X)return null;let Ve=`tool-${c()}`;return ke(Fe,Ve),Ve},Me=W=>{let X=S.get(W);if(X)return X;let Se={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:W,status:"pending"}};return S.set(W,Se),d(Se),Se},ae=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let X=Number(W);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let Se=Date.parse(W);if(!Number.isNaN(Se))return Se}return Date.now()},Le=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},Ie=new Map,P=new Map,q=new Map,ie=new Map,F=null,U=(W,X,Se)=>{var Z;let Fe=q.get(W);Fe||(Fe=[],q.set(W,Fe));let Ve=0,I=Fe.length;for(;Ve<I;){let Ye=Ve+I>>>1;Fe[Ye].seq<X?Ve=Ye+1:I=Ye}((Z=Fe[Ve])==null?void 0:Z.seq)===X?Fe[Ve]={seq:X,text:Se}:Fe.splice(Ve,0,{seq:X,text:Se});let te="";for(let Ye=0;Ye<Fe.length;Ye++)te+=Fe[Ye].text;return te},me=(W,X)=>{let Se=Le(X),Fe=P.get(W.id),Ve=Cp(Fe,Se);W.rawContent=Ve;let I=Ie.get(W.id),te=pe=>{var at;let He=(at=W.content)!=null?at:"";pe.trim()!==""&&(He.trim().length===0||pe.startsWith(He)||pe.trimStart().startsWith(He.trim()))&&(W.content=pe)},Z=()=>{var pe;if(I){let He=(pe=I.close)==null?void 0:pe.call(I);He instanceof Promise&&He.catch(()=>{})}Ie.delete(W.id),P.delete(W.id),W.streaming=!1,d(W)};if(!I){te(Se),Z();return}let Ye=$r(Ve);if(Ye!==null&&Ye.trim()!==""){te(Ye),Z();return}let Pe=pe=>{var Ft;let He=typeof pe=="string"?pe:(Ft=pe==null?void 0:pe.text)!=null?Ft:null;if(He!==null&&He.trim()!=="")return He;let at=I.getExtractedText();return at!==null&&at.trim()!==""?at:Se},ne;try{ne=I.processChunk(Ve)}catch{te(Se),Z();return}if(ne instanceof Promise){ne.then(pe=>{te(Pe(pe)),Z()}).catch(()=>{te(Se),Z()});return}te(Pe(ne)),Z()},Je=[],ee=!1,le,Pt=()=>{ee||(ee=!0,queueMicrotask(()=>{ee=!1,le()}))},mt=new Ss((W,X)=>{Je.push({payloadType:W,payload:X}),Pt()}),ze=null,Xt=new Map,Xe=(ge=this.config.iterationDisplay)!=null?ge:"separate";for(le=()=>{var W,X,Se,Fe,Ve,I,te,Z,Ye,Pe,ne,pe,He,at,Ft,ft,jt,xt,nt,vt,qe,zt,qn,Xn,Rn,it,Tr,Un,Mr,Tn,qr,cr,Zn,pt,bn,Hn,on,dr,xn,At,sn,Mn,pr,Qn,ur,Vn,vn,Jn,wt,Ot,$t,Cn,mr,Bn,wn,O,Dn,kn,gr,cn,dn,ce,Sn,er,Qo,mo,es,Ur,rt,go,Ln,pn,ts,ns,fo,tr,rs,kr,ho,nr,yo,fr,hr,os,ss,Qs,Lr,Ir,Ht,Vr,Jr,bo,Gn,as,xo,vo,Co,an,An,rr,Ze,wo,Pr,Nn,is,Gr,Kr,Wr,yr,ls,cs,Fn,Rr,ds,ps,or,Bt,Dt,br,So,Ao,Eo,To,ea,Mo,xr,Yr,sr,ko;for(let Hr=0;Hr<Je.length;Hr++){let _e=Je[Hr].payloadType,b=Je[Hr].payload;if(_e==="reason_start"){let R=(W=Ne(b,!0))!=null?W:`reason-${c()}`,C=he(R);C.reasoning=(X=C.reasoning)!=null?X:{id:R,status:"streaming",chunks:[]},C.reasoning.startedAt=(Fe=C.reasoning.startedAt)!=null?Fe:ae((Se=b.startedAt)!=null?Se:b.timestamp),C.reasoning.completedAt=void 0,C.reasoning.durationMs=void 0,C.streaming=!0,C.reasoning.status="streaming",d(C)}else if(_e==="reason_delta"||_e==="reason_chunk"){let R=(I=(Ve=Ne(b,!1))!=null?Ve:Ne(b,!0))!=null?I:`reason-${c()}`,C=he(R);C.reasoning=(te=C.reasoning)!=null?te:{id:R,status:"streaming",chunks:[]},C.reasoning.startedAt=(Ye=C.reasoning.startedAt)!=null?Ye:ae((Z=b.startedAt)!=null?Z:b.timestamp);let se=(pe=(ne=(Pe=b.reasoningText)!=null?Pe:b.text)!=null?ne:b.delta)!=null?pe:"";if(se&&b.hidden!==!0){let We=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(We!==void 0){let N=U(R,We,String(se));C.reasoning.chunks=[N]}else C.reasoning.chunks.push(String(se))}if(C.reasoning.status=b.done?"complete":"streaming",b.done){C.reasoning.completedAt=ae((He=b.completedAt)!=null?He:b.timestamp);let We=(at=C.reasoning.startedAt)!=null?at:Date.now();C.reasoning.durationMs=Math.max(0,((Ft=C.reasoning.completedAt)!=null?Ft:Date.now())-We)}C.streaming=C.reasoning.status!=="complete",d(C)}else if(_e==="reason_complete"){let R=(jt=(ft=Ne(b,!1))!=null?ft:Ne(b,!0))!=null?jt:`reason-${c()}`,C=w.get(R);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=ae((xt=b.completedAt)!=null?xt:b.timestamp);let We=(nt=C.reasoning.startedAt)!=null?nt:Date.now();C.reasoning.durationMs=Math.max(0,((vt=C.reasoning.completedAt)!=null?vt:Date.now())-We),C.streaming=!1,d(C)}let se=G(b);se&&v.byStep.delete(se)}else if(_e==="tool_start"){let R=(qe=we(b,!0))!=null?qe:`tool-${c()}`,C=(zt=b.toolName)!=null?zt:b.name;if(de(C)){Be.add(R);continue}let se=Me(R),We=(qn=se.toolCall)!=null?qn:{id:R,status:"pending"};We.name=C!=null?C:We.name,We.status="running",b.args!==void 0?We.args=b.args:b.parameters!==void 0&&(We.args=b.parameters),We.startedAt=(Rn=We.startedAt)!=null?Rn:ae((Xn=b.startedAt)!=null?Xn:b.timestamp),We.completedAt=void 0,We.durationMs=void 0,se.toolCall=We,se.streaming=!0;let N=b.agentContext;(N||b.executionId)&&(se.agentMetadata={executionId:(it=N==null?void 0:N.executionId)!=null?it:b.executionId,iteration:(Tr=N==null?void 0:N.iteration)!=null?Tr:b.iteration}),d(se)}else if(_e==="tool_chunk"||_e==="tool_delta"){let R=(Mr=(Un=we(b,!1))!=null?Un:we(b,!0))!=null?Mr:`tool-${c()}`;if(Be.has(R))continue;let C=Me(R),se=(Tn=C.toolCall)!=null?Tn:{id:R,status:"running"};se.startedAt=(cr=se.startedAt)!=null?cr:ae((qr=b.startedAt)!=null?qr:b.timestamp);let We=(bn=(pt=(Zn=b.text)!=null?Zn:b.delta)!=null?pt:b.message)!=null?bn:"";We&&(se.chunks=(Hn=se.chunks)!=null?Hn:[],se.chunks.push(String(We))),se.status="running",C.toolCall=se,C.streaming=!0;let N=b.agentContext;(N||b.executionId)&&(C.agentMetadata=(xn=C.agentMetadata)!=null?xn:{executionId:(on=N==null?void 0:N.executionId)!=null?on:b.executionId,iteration:(dr=N==null?void 0:N.iteration)!=null?dr:b.iteration}),d(C)}else if(_e==="tool_complete"){let R=(sn=(At=we(b,!1))!=null?At:we(b,!0))!=null?sn:`tool-${c()}`;if(Be.has(R)){Be.delete(R);continue}let C=Me(R),se=(Mn=C.toolCall)!=null?Mn:{id:R,status:"running"};se.status="complete",b.result!==void 0&&(se.result=b.result),typeof b.duration=="number"&&(se.duration=b.duration),se.completedAt=ae((pr=b.completedAt)!=null?pr:b.timestamp);let We=(Qn=b.duration)!=null?Qn:b.executionTime;if(typeof We=="number")se.durationMs=We;else{let Oe=(ur=se.startedAt)!=null?ur:Date.now();se.durationMs=Math.max(0,((Vn=se.completedAt)!=null?Vn:Date.now())-Oe)}C.toolCall=se,C.streaming=!1;let N=b.agentContext;(N||b.executionId)&&(C.agentMetadata=(wt=C.agentMetadata)!=null?wt:{executionId:(vn=N==null?void 0:N.executionId)!=null?vn:b.executionId,iteration:(Jn=N==null?void 0:N.iteration)!=null?Jn:b.iteration}),d(C);let ct=j(b);ct&&T.byCall.delete(ct)}else if(_e==="text_start"){if((Ot=b.toolContext)!=null&&Ot.toolId)continue;let R=b.partId;if(R!==void 0&&x.current!==null&&R!==x.current){let C=f;C&&(C.streaming=!1,d(C),F=C,f=null,M=!0)}R!==void 0&&(x.current=R)}else if(_e==="text_end"){if(($t=b.toolContext)!=null&&$t.toolId)continue;let R=f;R&&(R.streaming=!1,d(R),F=R,f=null,M=!0)}else if(_e==="step_chunk"||_e==="step_delta"){let R=b.stepType,C=b.executionType;if(R==="tool"||C==="context")continue;let se=b.toolContext;if(se!=null&&se.toolId){let Oe=String((mr=(Cn=b.id)!=null?Cn:se.stepId)!=null?mr:`step-${c()}`),kt=b.partId!==void 0&&b.partId!==null?String(b.partId):"",ot=`${se.toolId}::${Oe}`,qt=$.get(ot);if(kt!==""&&qt!==void 0&&qt!==""&&qt!==kt){let st=k.get(B(se.toolId,Oe,qt));st&&st.streaming!==!1&&(st.streaming=!1,d(st))}kt!==""&&$.set(ot,kt);let Tt=K(se.toolId,Oe,kt,se.executionId),Zt=(Dn=(O=(wn=(Bn=b.text)!=null?Bn:b.delta)!=null?wn:b.content)!=null?O:b.chunk)!=null?Dn:"";Zt&&(Tt.content+=String(Zt),Tt.streaming=!0,d(Tt)),b.isComplete&&(Tt.streaming=!1,d(Tt));continue}let We=b.partId;if(We!==void 0&&x.current!==null&&We!==x.current){let Oe=f;Oe&&(Oe.streaming=!1,d(Oe),F=Oe,f=null,M=!0)}We!==void 0&&(x.current=We);let N=We!==void 0&&(kn=ie.get(We))!=null?kn:oe();We!==void 0&&(N.partId||(N.partId=We),ie.set(We,N));let ct=(ce=(dn=(cn=(gr=b.text)!=null?gr:b.delta)!=null?cn:b.content)!=null?dn:b.chunk)!=null?ce:"";if(ct){let Oe=typeof b.seq=="number"?b.seq:void 0,kt=We!=null?We:N.id,ot=Oe!==void 0?U(kt,Oe,String(ct)):((Sn=P.get(N.id))!=null?Sn:"")+ct;N.rawContent=ot,Ie.has(N.id)||Ie.set(N.id,this.createStreamParser());let qt=Ie.get(N.id),Tt=ot.trim().startsWith("{")||ot.trim().startsWith("[");if(Tt&&P.set(N.id,ot),qt.__isPlainTextParser===!0){N.content=Oe!==void 0?ot:N.content+ct,P.delete(N.id),Ie.delete(N.id),N.rawContent=void 0,d(N);continue}let st=qt.processChunk(ot);if(st instanceof Promise)st.then(ht=>{var On;let Qt=typeof ht=="string"?ht:(On=ht==null?void 0:ht.text)!=null?On:null;if(Qt!==null&&Qt.trim()!=="")N.content=Qt,d(N);else if(!Tt&&!ot.trim().startsWith("<")){let Lt=f,Vt=Lt&&Lt.id===N.id?Lt:N;Vt.id===N.id&&(Vt.content=Oe!==void 0?ot:Vt.content+ct,P.delete(Vt.id),Ie.delete(Vt.id),Vt.rawContent=void 0,d(Vt))}}).catch(()=>{N.content=Oe!==void 0?ot:N.content+ct,P.delete(N.id),Ie.delete(N.id),N.rawContent=void 0,d(N)});else{let ht=typeof st=="string"?st:(er=st==null?void 0:st.text)!=null?er:null;ht!==null&&ht.trim()!==""?(N.content=ht,d(N)):!Tt&&!ot.trim().startsWith("<")&&(N.content=Oe!==void 0?ot:N.content+ct,P.delete(N.id),Ie.delete(N.id),N.rawContent=void 0,d(N))}}if(b.isComplete){let Oe=(mo=(Qo=b.result)==null?void 0:Qo.response)!=null?mo:N.content;if(Oe){let kt=P.get(N.id),ot=kt!=null?kt:Le(Oe);N.rawContent=ot;let qt=Ie.get(N.id),Tt=null,Zt=!1;if(qt&&(Tt=qt.getExtractedText(),Tt===null&&(Tt=$r(ot)),Tt===null)){let st=qt.processChunk(ot);st instanceof Promise?(Zt=!0,st.then(ht=>{var On;let Qt=typeof ht=="string"?ht:(On=ht==null?void 0:ht.text)!=null?On:null;if(Qt!==null){let Lt=f;Lt&&Lt.id===N.id&&(Lt.content=Qt,Lt.streaming=!1,Ie.delete(Lt.id),P.delete(Lt.id),d(Lt))}})):Tt=typeof st=="string"?st:(es=st==null?void 0:st.text)!=null?es:null}if(!Zt){Tt!==null&&Tt.trim()!==""?N.content=Tt:P.has(N.id)||(N.content=Le(Oe));let st=Ie.get(N.id);if(st){let ht=(Ur=st.close)==null?void 0:Ur.call(st);ht instanceof Promise&&ht.catch(()=>{}),Ie.delete(N.id)}P.delete(N.id),N.streaming=!1,d(N)}}}}else if(_e==="step_complete"){let R=b.stepType,C=b.executionType;if(R==="tool"||C==="context")continue;let se=b.toolContext;if(se!=null&&se.toolId){let ct=String((go=(rt=b.id)!=null?rt:se.stepId)!=null?go:"");if(ct){let Oe=E(se.toolId,ct);for(let[kt,ot]of k)kt.startsWith(Oe)&&ot.streaming!==!1&&(ot.streaming=!1,d(ot));$.delete(`${se.toolId}::${ct}`)}continue}if(M){if(f!==null){let kt=f;Ie.delete(kt.id),P.delete(kt.id),kt.streaming!==!1&&(kt.streaming=!1,d(kt))}let ct=(Ln=b.result)==null?void 0:Ln.response,Oe=F;Oe&&(ct!=null?me(Oe,ct):(Ie.delete(Oe.id),P.delete(Oe.id))),F=null;continue}let We=(pn=b.result)==null?void 0:pn.response,N=oe();if(We!=null){let ct=Ie.get(N.id),Oe=!1,kt=!1;if(ct){let ot=ct.getExtractedText(),qt=P.get(N.id),Tt=qt!=null?qt:Le(We);if(N.rawContent=Tt,ot!==null&&ot.trim()!=="")N.content=ot,Oe=!0;else{let Zt=$r(Tt);if(Zt!==null)N.content=Zt,Oe=!0;else{let st=ct.processChunk(Tt);if(st instanceof Promise)kt=!0,st.then(ht=>{var On;let Qt=typeof ht=="string"?ht:(On=ht==null?void 0:ht.text)!=null?On:null;if(Qt!==null&&Qt.trim()!==""){let Lt=f;Lt&&Lt.id===N.id&&(Lt.content=Qt,Lt.streaming=!1,Ie.delete(Lt.id),P.delete(Lt.id),d(Lt))}else{let Lt=ct.getExtractedText(),Vt=f;Vt&&Vt.id===N.id&&(Lt!==null&&Lt.trim()!==""?Vt.content=Lt:P.has(Vt.id)||(Vt.content=Le(We)),Vt.streaming=!1,Ie.delete(Vt.id),P.delete(Vt.id),d(Vt))}});else{let ht=typeof st=="string"?st:(ts=st==null?void 0:st.text)!=null?ts:null;if(ht!==null&&ht.trim()!=="")N.content=ht,Oe=!0;else{let Qt=ct.getExtractedText();Qt!==null&&Qt.trim()!==""&&(N.content=Qt,Oe=!0)}}}}}if(!kt){if(!N.rawContent){let ot=P.get(N.id);N.rawContent=ot!=null?ot:Le(We)}if(!Oe&&!P.has(N.id)&&(N.content=Le(We)),ct){let ot=(ns=ct.close)==null?void 0:ns.call(ct);ot instanceof Promise&&ot.catch(()=>{})}Ie.delete(N.id),P.delete(N.id),N.streaming=!1,d(N)}}else Ie.delete(N.id),P.delete(N.id),N.streaming=!1,d(N)}else if(_e==="flow_complete"){let R=(fo=b.result)==null?void 0:fo.response;if(M){if(f!==null){let C=f;Ie.delete(C.id),P.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}}else if(R!=null){let C=oe(),se=P.get(C.id),We=se!=null?se:Le(R);C.rawContent=We;let N=Le(R),ct=Ie.get(C.id);if(ct){let ot=$r(We);if(ot!==null)N=ot;else{let qt=ct.processChunk(We);qt instanceof Promise&&qt.then(Zt=>{var ht;let st=typeof Zt=="string"?Zt:(ht=Zt==null?void 0:Zt.text)!=null?ht:null;st!==null&&(C.content=st,C.streaming=!1,d(C))});let Tt=ct.getExtractedText();Tt!==null&&(N=Tt)}}Ie.delete(C.id),P.delete(C.id);let Oe=N!==C.content,kt=C.streaming!==!1;Oe&&(C.content=N),C.streaming=!1,(Oe||kt)&&d(C)}else if(f!==null){let C=f;Ie.delete(C.id),P.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}t({type:"status",status:"idle"})}else if(_e==="agent_start")ze={executionId:b.executionId,agentId:(tr=b.agentId)!=null?tr:"virtual",agentName:(rs=b.agentName)!=null?rs:"",status:"running",currentIteration:0,maxTurns:(kr=b.maxTurns)!=null?kr:1,startedAt:ae(b.startedAt)};else if(_e==="agent_iteration_start"){if(ze&&(ze.currentIteration=b.iteration),Xe==="separate"&&b.iteration>1){let R=f;R&&(R.streaming=!1,d(R),Xt.set(b.iteration-1,R),f=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(b.contentType==="text"){let R=oe();R.content+=(ho=b.delta)!=null?ho:"",R.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:ze==null?void 0:ze.agentName},d(R)}else if(b.contentType==="thinking"){let R=(nr=b.turnId)!=null?nr:`agent-think-${b.iteration}`,C=he(R);C.reasoning=(yo=C.reasoning)!=null?yo:{id:R,status:"streaming",chunks:[]},C.reasoning.chunks.push((fr=b.delta)!=null?fr:""),C.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},d(C)}else if(b.contentType==="tool_input"){let R=(hr=b.toolCallId)!=null?hr:T.lastId;if(R){let C=S.get(R);C!=null&&C.toolCall&&(C.toolCall.chunks=(os=C.toolCall.chunks)!=null?os:[],C.toolCall.chunks.push((ss=b.delta)!=null?ss:""),d(C))}}}else if(_e==="agent_turn_complete"){let R=b.turnId;if(R){let C=w.get(R);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=ae(b.completedAt);let se=(Qs=C.reasoning.startedAt)!=null?Qs:Date.now();C.reasoning.durationMs=Math.max(0,((Lr=C.reasoning.completedAt)!=null?Lr:Date.now())-se),C.streaming=!1,d(C)}}}else if(_e==="agent_tool_start"){let R=(Ir=b.toolCallId)!=null?Ir:`agent-tool-${c()}`;ke(j(b),R);let C=Me(R),se=(Ht=C.toolCall)!=null?Ht:{id:R,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};se.name=(Jr=(Vr=b.toolName)!=null?Vr:b.name)!=null?Jr:se.name,se.status="running",b.parameters!==void 0&&(se.args=b.parameters),se.startedAt=ae((bo=b.startedAt)!=null?bo:b.timestamp),C.toolCall=se,C.streaming=!0,C.agentMetadata={executionId:b.executionId,iteration:b.iteration},d(C)}else if(_e==="agent_tool_delta"){let R=(Gn=b.toolCallId)!=null?Gn:T.lastId;if(R){let C=(as=S.get(R))!=null?as:Me(R);C.toolCall&&(C.toolCall.chunks=(xo=C.toolCall.chunks)!=null?xo:[],C.toolCall.chunks.push((vo=b.delta)!=null?vo:""),C.toolCall.status="running",C.streaming=!0,d(C))}}else if(_e==="agent_tool_complete"){let R=(Co=b.toolCallId)!=null?Co:T.lastId;if(R){let C=(an=S.get(R))!=null?an:Me(R);if(C.toolCall){C.toolCall.status="complete",b.result!==void 0&&(C.toolCall.result=b.result),typeof b.executionTime=="number"&&(C.toolCall.durationMs=b.executionTime),C.toolCall.completedAt=ae((An=b.completedAt)!=null?An:b.timestamp),C.streaming=!1,d(C);let se=j(b);se&&T.byCall.delete(se)}}}else if(_e!=="agent_iteration_complete"){if(_e==="agent_reflection"||_e==="agent_reflect"){let R=`agent-reflection-${b.executionId}-${b.iteration}`,C={id:R,role:"assistant",content:(rr=b.reflection)!=null?rr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:R,status:"complete",chunks:[(Ze=b.reflection)!=null?Ze:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};d(C)}else if(_e==="agent_complete"){ze&&(ze.status=b.success?"complete":"error",ze.completedAt=ae(b.completedAt),ze.stopReason=b.stopReason);let R=f;R&&(R.streaming=!1,d(R)),t({type:"status",status:"idle"})}else if(_e==="agent_error"){let R=typeof b.error=="string"?b.error:(Pr=(wo=b.error)==null?void 0:wo.message)!=null?Pr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",R):t({type:"error",error:new Error(R)})}else if(_e!=="agent_ping"){if(_e==="agent_approval_start"){let R=(Nn=b.approvalId)!=null?Nn:`approval-${c()}`,C={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:"pending",agentId:(is=ze==null?void 0:ze.agentId)!=null?is:"virtual",executionId:(Kr=(Gr=b.executionId)!=null?Gr:ze==null?void 0:ze.executionId)!=null?Kr:"",toolName:(Wr=b.toolName)!=null?Wr:"",toolType:b.toolType,description:(ls=b.description)!=null?ls:`Execute ${(yr=b.toolName)!=null?yr:"tool"}`,parameters:b.parameters}};d(C)}else if(_e==="step_await"&&b.awaitReason==="approval_required"){let R=(cs=b.approvalId)!=null?cs:`approval-${c()}`,C={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:"pending",agentId:(Fn=ze==null?void 0:ze.agentId)!=null?Fn:"virtual",executionId:(ds=(Rr=b.executionId)!=null?Rr:ze==null?void 0:ze.executionId)!=null?ds:"",toolName:(ps=b.toolName)!=null?ps:"",toolType:b.toolType,description:(Bt=b.description)!=null?Bt:`Execute ${(or=b.toolName)!=null?or:"tool"}`,parameters:b.parameters}};d(C)}else if(_e==="agent_approval_complete"){let R=b.approvalId;if(R){let se={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:(Dt=b.decision)!=null?Dt:"approved",agentId:(br=ze==null?void 0:ze.agentId)!=null?br:"virtual",executionId:(Ao=(So=b.executionId)!=null?So:ze==null?void 0:ze.executionId)!=null?Ao:"",toolName:(Eo=b.toolName)!=null?Eo:"",description:(To=b.description)!=null?To:"",resolvedAt:Date.now()}};d(se)}}else if(_e==="artifact_start"||_e==="artifact_delta"||_e==="artifact_update"||_e==="artifact_complete"){if(_e==="artifact_start"){let R=b.artifactType,C=String(b.id),se=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:C,artifactType:R,title:se,component:typeof b.component=="string"?b.component:void 0}),ye.set(C,{markdown:"",title:se}),!Y.has(C)){Y.add(C);let We={id:`artifact-ref-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:C,title:se,artifactType:R,status:"streaming"}})};ue.set(C,We),d(We)}}else if(_e==="artifact_delta"){let R=String(b.id),C=typeof b.delta=="string"?b.delta:String((ea=b.delta)!=null?ea:"");t({type:"artifact_delta",id:R,artDelta:C});let se=ye.get(R);se&&(se.markdown+=C)}else if(_e==="artifact_update"){let R=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:R,component:typeof b.component=="string"?b.component:void 0})}else if(_e==="artifact_complete"){let R=String(b.id);t({type:"artifact_complete",id:R});let C=ue.get(R);if(C){C.streaming=!1;try{let se=JSON.parse((Mo=C.rawContent)!=null?Mo:"{}");if(se.props){se.props.status="complete";let We=ye.get(R);We!=null&&We.markdown&&(se.props.markdown=We.markdown)}C.rawContent=JSON.stringify(se)}catch{}ye.delete(R),d(C),ue.delete(R)}}}else if(_e==="transcript_insert"){let R=b.message;if(!R||typeof R!="object")continue;let C=String((xr=R.id)!=null?xr:`msg-${c()}`),se=R.role,N={id:C,role:se==="user"?"user":se==="system"?"system":"assistant",content:typeof R.content=="string"?R.content:"",rawContent:typeof R.rawContent=="string"?R.rawContent:void 0,createdAt:typeof R.createdAt=="string"?R.createdAt:new Date().toISOString(),streaming:R.streaming===!0,...typeof R.variant=="string"?{variant:R.variant}:{},sequence:c()};if(d(N),N.rawContent)try{let ct=JSON.parse(N.rawContent),Oe=(Yr=ct==null?void 0:ct.props)==null?void 0:Yr.artifactId;typeof Oe=="string"&&Y.add(Oe)}catch{}f=null,g.current=null,Ie.delete(C),P.delete(C)}else if(_e==="error"||_e==="step_error"||_e==="dispatch_error"||_e==="flow_error"){let R=null;if(b.error instanceof Error)R=b.error;else if(_e==="dispatch_error"){let C=(sr=b.message)!=null?sr:b.error;C!=null&&C!==""&&(R=new Error(String(C)))}else if(_e==="step_error"||_e==="flow_error"){let C=b.error;typeof C=="string"&&C!==""?R=new Error(C):C!=null&&typeof C=="object"&&"message"in C&&(R=new Error(String((ko=C.message)!=null?ko:C)))}else _e==="error"&&b.error!=null&&b.error!==""&&(R=new Error(String(b.error)));if(R){t({type:"error",error:R});let C=f;C&&C.streaming&&(C.streaming=!1,d(C)),t({type:"status",status:"idle"})}}}}}}Je.length=0};;){let{done:W,value:X}=await s.read();if(W)break;a+=o.decode(X,{stream:!0});let Se=a.split(`
|
|
5
5
|
|
|
6
|
-
`);a=(
|
|
7
|
-
`),Ce="message",be="";for(let At of Fe)At.startsWith("event:")?Ce=At.replace("event:","").trim():At.startsWith("data:")&&(be+=At.replace("data:","").trim());if(!be)continue;let at;try{at=JSON.parse(be)}catch(At){t({type:"error",error:At instanceof Error?At:new Error("Failed to parse chat stream payload")});continue}let mt=Ce!=="message"?Ce:(Wt=at.type)!=null?Wt:"message";if((Jt=this.onSSEEvent)==null||Jt.call(this,mt,at),this.parseSSEEvent){g.current=f;let At=await this.handleCustomSSEEvent(at,t,g,d,c,x);if(g.current&&g.current!==f&&(f=g.current),At)continue}ce.push(mt,at),N()}}ce.flushPending(),N(),ce.destroy()}};function Cp(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function To(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Yr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var ps="[Image]";function wp(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Sp(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Ap(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Ep(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function us(e){return{type:"text",text:e}}function Tp(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Mp(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function kp(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.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: ${r.join(", ")}`}}var Rc=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Lp=["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"],or=[...Rc,...Lp];function Ip(e){return Rc.includes(e)||e.startsWith("image/")}function ms(e){return Ip(e.type)}async function Hc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;ms(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Bc(e,r=or,t=10*1024*1024){return r.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: ${r.join(", ")}`}}function Pp(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Dc(e,r){let t=Pp(r).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 gs=class{constructor(r=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=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,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 n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.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 u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.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(r){this.finishedCallbacks.push(r)}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 r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var fs=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.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 u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=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 Mo=class{constructor(r){this.config=r;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 fs;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(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;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=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let x=!1,T=S=>{x||(x=!0,clearTimeout(C),g(new Error(S)))},C=setTimeout(()=>T("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(C),f())},{once:!0}),this.ws.addEventListener("error",()=>{T("WebSocket connection failed to "+p+"."+d)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!x){let M=S.code!==1006?` (code ${S.code})`:"";T("WebSocket connection failed"+M+"."+d)}},{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(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.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(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new gs(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(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("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 r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",d=new Blob(this.audioChunks,{type:p});await this.sendAudio(d),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("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(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}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(r=>r.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(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Br=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.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(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({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(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Kr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Mo(e.runtype);case"browser":if(!Br.isSupported())throw new Error("Browser speech recognition not supported");return new Br(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ks(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Kr({type:"runtype",runtype:e.runtype});if(Br.isSupported())return Kr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function hs(e){try{return Ks(e),!0}catch{return!1}}var ko=class e{constructor(r={},t){this.config=r;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.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Gr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return hs((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Kr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,d,f,g,x,T;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=c.text)!=null&&g.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let C=(T=this.pendingVoiceAssistantMessageId)!=null?T:(x=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:x.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(p=this.callbacks).onVoiceStatusChanged)==null||d.call(p,c)}),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(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Gr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?To():t==="assistant"?Yr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:p,streaming:d=!1}=n,g={id:u!=null?u:s==="user"?To():s==="assistant"?Yr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:d,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,d,f,g;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=To(),o=Yr(),a={id:s,role:"user",content:n||ps,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 u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let T=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!T){let C={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(C)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,T||(x instanceof Error?(d=(p=this.callbacks).onError)==null||d.call(p,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Yr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error((u=g==null?void 0:g.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(p=(c=this.callbacks).onError)==null||p.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.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(()=>n.speak(s),50)}static pickBestVoice(r){var n;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=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Gn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as Wp from"lucide";var ye=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=Wp[s];return o?Rp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function Rp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),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){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&u.setAttribute(c,String(p))}),s.appendChild(u)}}}),s}var ys={allowedTypes:or,maxFileSize:10*1024*1024,maxFiles:4};function Hp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Bp(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-json":"file"}var Xr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:ys.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:ys.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:ys.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:ys.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Bc(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let d=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await Hc(c),f=ms(c)?URL.createObjectURL(c):null,g={id:Hp(),file:c,previewUrl:f,contentPart:d};this.attachments.push(g),this.renderPreview(g)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=ms(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.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",n.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=Bp(r.file.type),u=ye(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=Dc(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.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(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var Nc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Lo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Nc(o)&&Nc(s)?t[n]=Lo(o,s):t[n]=s}return t}var In="min(440px, calc(100vw - 24px))",Xs="440px",Lt={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:In,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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"}},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 Fc(e,r){if(!(!e&&!r))return e?r?Lo(e,r):e:r}function Zs(e){var r,t,n,s,o,a,i,u,c,p,d,f,g,x,T,C,S,M,H,w,L;return e?{...Lt,...e,theme:Fc(Lt.theme,e.theme),darkTheme:Fc(Lt.darkTheme,e.darkTheme),launcher:{...Lt.launcher,...e.launcher,dock:{...(r=Lt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Lt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Lt.copy,...e.copy},sendButton:{...Lt.sendButton,...e.sendButton},statusIndicator:{...Lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Lt.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,Ee,ae,we;let W=(oe=Lt.features)==null?void 0:oe.artifacts,E=(Ee=e.features)==null?void 0:Ee.artifacts,K=(ae=Lt.features)==null?void 0:ae.scrollToBottom,Q=(we=e.features)==null?void 0:we.scrollToBottom,X=W===void 0&&E===void 0?void 0:{...W,...E,layout:{...W==null?void 0:W.layout,...E==null?void 0:E.layout}},O=K===void 0&&Q===void 0?void 0:{...K,...Q};return{...Lt.features,...e.features,...O!==void 0?{scrollToBottom:O}:{},...X!==void 0?{artifacts:X}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Lt.suggestionChips,suggestionChipsConfig:{...Lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Lt.layout,...e.layout,header:{...(a=Lt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=Lt.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(p=Lt.layout)==null?void 0:p.messages)==null?void 0:d.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(T=(x=Lt.layout)==null?void 0:x.messages)==null?void 0:T.timestamp,...(S=(C=e.layout)==null?void 0:C.messages)==null?void 0:S.timestamp}},slots:{...(M=Lt.layout)==null?void 0:M.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...Lt.markdown,...e.markdown,options:{...(w=Lt.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Lt.messageActions,...e.messageActions}}:Lt}var Oc={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"}},$c={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"}},_c={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:In,maxWidth:Xs,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"},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 Io(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Io(e,n):n}function Qs(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=Io(e,a);u!==void 0&&(r[i]={path:i,value:u,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"),r}function jc(e){let r=[],t=[];return e.palette||r.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:r.length===0,errors:r,warnings:t}}function zc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=zc(o,s):t[n]=s}return t}function Dp(e,r){return r?zc(e,r):e}function Po(e,r={}){var s,o,a,i,u,c,p,d,f,g,x,T,C;let t={palette:Oc,semantic:$c,components:_c},n={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,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.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,...(f=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...t.semantic.spacing,...(T=e==null?void 0:e.semantic)==null?void 0:T.spacing},typography:{...t.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:Dp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let S=jc(n);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let S of r.plugins)n=S.transform(n);return n}function ea(e){var x,T,C,S,M,H,w,L,W,E,K,Q,X,O,oe,Ee,ae,we,$e,he,We,Re,ie,Z,me,V,re,He,ge,Be,st,z,U,se,N,J,ce,fe,te,pe,kt,dt,Wt,Jt,P,$,ne,Pe,Fe,Ce,be,at,mt,At,j,xe,ue,Ze,qe,de,Te,Ve,vt,Ot,pt,$t,ht,Qe,yt,je,_t,zn,Kn,Wn,tt,Cr,qn,wr,An,Fr,ar,Xn,it,hn,Rn,nn,ir,yn,Et,rn,En,lr,Zn,cr,Un,bn,Vn,Ct,Bt,Dt,xn,dr,Hn,vn,D,Bn,Tn,pr,an,ln;let r=Qs(e),t={};for(let[le,Cn]of Object.entries(r)){let Qn=le.replace(/\./g,"-");t[`--persona-${Qn}`]=Cn.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"]=(C=t["--persona-semantic-colors-accent"])!=null?C:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H: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"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(E=t["--persona-semantic-colors-border"])!=null?E:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(K=t["--persona-semantic-colors-divider"])!=null?K:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(Q=t["--persona-components-voice-recording-indicator"])!=null?Q:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(X=t["--persona-components-voice-recording-background"])!=null?X:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O: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"]=(Ee=t["--persona-components-approval-requested-background"])!=null?Ee:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ae=t["--persona-components-approval-requested-border"])!=null?ae:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(we=t["--persona-components-approval-requested-text"])!=null?we:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=($e=t["--persona-components-approval-approve-background"])!=null?$e:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(he=t["--persona-components-approval-deny-background"])!=null?he:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(We=t["--persona-components-attachment-image-background"])!=null?We:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Re=t["--persona-components-attachment-image-border"])!=null?Re:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ie=t["--persona-semantic-typography-fontFamily"])!=null?ie:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Z=t["--persona-semantic-typography-fontSize"])!=null?Z:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(me=t["--persona-semantic-typography-fontWeight"])!=null?me:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(V=t["--persona-semantic-typography-lineHeight"])!=null?V: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"]=(re=t["--persona-palette-radius-sm"])!=null?re:"0.125rem",t["--persona-radius-md"]=(He=t["--persona-palette-radius-md"])!=null?He:"0.375rem",t["--persona-radius-lg"]=(ge=t["--persona-palette-radius-lg"])!=null?ge:"0.5rem",t["--persona-radius-xl"]=(Be=t["--persona-palette-radius-xl"])!=null?Be:"0.75rem",t["--persona-radius-full"]=(st=t["--persona-palette-radius-full"])!=null?st:"9999px",t["--persona-launcher-radius"]=(U=(z=t["--persona-components-launcher-borderRadius"])!=null?z:t["--persona-palette-radius-full"])!=null?U:"9999px",t["--persona-launcher-bg"]=(se=t["--persona-components-launcher-background"])!=null?se:t["--persona-primary"],t["--persona-launcher-fg"]=(N=t["--persona-components-launcher-foreground"])!=null?N:t["--persona-text-inverse"],t["--persona-launcher-border"]=(J=t["--persona-components-launcher-border"])!=null?J:t["--persona-border"],t["--persona-button-primary-bg"]=(ce=t["--persona-components-button-primary-background"])!=null?ce:t["--persona-primary"],t["--persona-button-primary-fg"]=(fe=t["--persona-components-button-primary-foreground"])!=null?fe:t["--persona-text-inverse"],t["--persona-button-radius"]=(pe=(te=t["--persona-components-button-primary-borderRadius"])!=null?te:t["--persona-palette-radius-full"])!=null?pe:"9999px",t["--persona-panel-radius"]=(dt=(kt=t["--persona-components-panel-borderRadius"])!=null?kt:t["--persona-radius-xl"])!=null?dt:"0.75rem",t["--persona-panel-border"]=(Wt=t["--persona-components-panel-border"])!=null?Wt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(P=(Jt=t["--persona-components-panel-shadow"])!=null?Jt:t["--persona-palette-shadows-xl"])!=null?P:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ne=($=t["--persona-components-input-borderRadius"])!=null?$:t["--persona-radius-lg"])!=null?ne:"0.5rem",t["--persona-message-user-radius"]=(Fe=(Pe=t["--persona-components-message-user-borderRadius"])!=null?Pe:t["--persona-radius-lg"])!=null?Fe:"0.5rem",t["--persona-message-assistant-radius"]=(be=(Ce=t["--persona-components-message-assistant-borderRadius"])!=null?Ce:t["--persona-radius-lg"])!=null?be:"0.5rem",t["--persona-header-bg"]=(at=t["--persona-components-header-background"])!=null?at:t["--persona-surface"],t["--persona-header-border"]=(mt=t["--persona-components-header-border"])!=null?mt:t["--persona-divider"],t["--persona-header-icon-bg"]=(At=t["--persona-components-header-iconBackground"])!=null?At:t["--persona-primary"],t["--persona-header-icon-fg"]=(j=t["--persona-components-header-iconForeground"])!=null?j:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(xe=t["--persona-components-header-titleForeground"])!=null?xe:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ue=t["--persona-components-header-subtitleForeground"])!=null?ue:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Ze=t["--persona-components-header-actionIconForeground"])!=null?Ze:t["--persona-muted"];let n=(qe=e.components)==null?void 0:qe.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(de=t["--persona-components-input-background"])!=null?de:t["--persona-surface"],t["--persona-input-placeholder"]=(Te=t["--persona-components-input-placeholder"])!=null?Te:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Ve=t["--persona-components-message-user-background"])!=null?Ve:t["--persona-accent"],t["--persona-message-user-text"]=(vt=t["--persona-components-message-user-text"])!=null?vt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ot=t["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(pt=t["--persona-components-message-assistant-background"])!=null?pt:t["--persona-surface"],t["--persona-message-assistant-text"]=($t=t["--persona-components-message-assistant-text"])!=null?$t:t["--persona-text"],t["--persona-message-assistant-border"]=(ht=t["--persona-components-message-assistant-border"])!=null?ht:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Qe=t["--persona-components-message-assistant-shadow"])!=null?Qe:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(je=(yt=t["--persona-components-scrollToBottom-background"])!=null?yt:t["--persona-button-primary-bg"])!=null?je:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(zn=(_t=t["--persona-components-scrollToBottom-foreground"])!=null?_t:t["--persona-button-primary-fg"])!=null?zn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Kn=t["--persona-components-scrollToBottom-border"])!=null?Kn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Wn=t["--persona-components-scrollToBottom-size"])!=null?Wn:"40px",t["--persona-scroll-to-bottom-radius"]=(qn=(Cr=(tt=t["--persona-components-scrollToBottom-borderRadius"])!=null?tt:t["--persona-button-radius"])!=null?Cr:t["--persona-radius-full"])!=null?qn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(An=(wr=t["--persona-components-scrollToBottom-shadow"])!=null?wr:t["--persona-palette-shadows-sm"])!=null?An:"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"]=(ar=t["--persona-components-scrollToBottom-gap"])!=null?ar:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(it=(Xn=t["--persona-components-scrollToBottom-fontSize"])!=null?Xn:t["--persona-palette-typography-fontSize-sm"])!=null?it:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(hn=t["--persona-components-scrollToBottom-iconSize"])!=null?hn:"14px",t["--persona-tool-bubble-shadow"]=(Rn=t["--persona-components-toolBubble-shadow"])!=null?Rn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(nn=t["--persona-components-reasoningBubble-shadow"])!=null?nn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(ir=t["--persona-components-composer-shadow"])!=null?ir:"none",t["--persona-md-inline-code-bg"]=(yn=t["--persona-components-markdown-inlineCode-background"])!=null?yn:t["--persona-container"],t["--persona-md-inline-code-color"]=(Et=t["--persona-components-markdown-inlineCode-foreground"])!=null?Et:t["--persona-text"],t["--persona-md-link-color"]=(En=(rn=t["--persona-components-markdown-link-foreground"])!=null?rn:t["--persona-accent"])!=null?En:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(lr=t["--persona-components-markdown-codeBlock-background"])!=null?lr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Zn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Zn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(cr=t["--persona-components-markdown-codeBlock-textColor"])!=null?cr:"inherit",t["--persona-md-table-header-bg"]=(Un=t["--persona-components-markdown-table-headerBackground"])!=null?Un:t["--persona-container"],t["--persona-md-table-border-color"]=(bn=t["--persona-components-markdown-table-borderColor"])!=null?bn:t["--persona-border"],t["--persona-md-hr-color"]=(Vn=t["--persona-components-markdown-hr-color"])!=null?Vn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Ct=t["--persona-components-markdown-blockquote-borderColor"])!=null?Ct:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Bt=t["--persona-components-markdown-blockquote-background"])!=null?Bt:"transparent",t["--persona-md-blockquote-text-color"]=(Dt=t["--persona-components-markdown-blockquote-textColor"])!=null?Dt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(xn=t["--persona-components-collapsibleWidget-container"])!=null?xn:t["--persona-surface"],t["--cw-surface"]=(dr=t["--persona-components-collapsibleWidget-surface"])!=null?dr:t["--persona-surface"],t["--cw-border"]=(Hn=t["--persona-components-collapsibleWidget-border"])!=null?Hn:t["--persona-border"],t["--persona-message-border"]=(vn=t["--persona-components-message-border"])!=null?vn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let g=c==null?void 0:c.artifact;if(g!=null&&g.toolbar){let le=g.toolbar;le.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=le.iconHoverColor),le.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=le.iconHoverBackground),le.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=le.iconPadding),le.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=le.iconBorderRadius),le.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=le.iconBorder),le.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=le.toggleGroupGap),le.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=le.toggleBorderRadius),le.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=le.copyBackground),le.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=le.copyBorder),le.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=le.copyColor),le.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=le.copyBorderRadius),le.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=le.copyPadding),le.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=le.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:le.copyMenuBackground),le.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=le.copyMenuBorder,t["--persona-dropdown-border"]=(Bn=t["--persona-dropdown-border"])!=null?Bn:le.copyMenuBorder),le.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=le.copyMenuShadow,t["--persona-dropdown-shadow"]=(Tn=t["--persona-dropdown-shadow"])!=null?Tn:le.copyMenuShadow),le.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=le.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(pr=t["--persona-dropdown-radius"])!=null?pr:le.copyMenuBorderRadius),le.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=le.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(an=t["--persona-dropdown-item-hover-bg"])!=null?an:le.copyMenuItemHoverBackground),le.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=le.iconBackground),le.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=le.toolbarBorder)}if(g!=null&&g.tab){let le=g.tab;le.background&&(t["--persona-artifact-tab-bg"]=le.background),le.activeBackground&&(t["--persona-artifact-tab-active-bg"]=le.activeBackground),le.activeBorder&&(t["--persona-artifact-tab-active-border"]=le.activeBorder),le.borderRadius&&(t["--persona-artifact-tab-radius"]=le.borderRadius),le.textColor&&(t["--persona-artifact-tab-color"]=le.textColor),le.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=le.hoverBackground),le.listBackground&&(t["--persona-artifact-tab-list-bg"]=le.listBackground),le.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=le.listBorderColor),le.listPadding&&(t["--persona-artifact-tab-list-padding"]=le.listPadding)}if(g!=null&&g.pane){let le=g.pane;if(le.toolbarBackground){let Cn=(ln=Io(e,le.toolbarBackground))!=null?ln:le.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Cn}}return t}var Np={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 Fp={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"}}},qc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},bs=()=>{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"},Op=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":bs()},Uc=e=>Op(e),$p=e=>Po(e),_p=e=>{var t;let r=Po(void 0,{validate:!1});return Po({...e,palette:{...r.palette,colors:{...Fp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},xs=e=>{let r=Uc(e),t=qc(e==null?void 0:e.theme),n=qc(e==null?void 0:e.darkTheme);return r==="dark"?_p(Lo(t!=null?t:{},n!=null?n:{})):$p(t)},jp=e=>ea(e),Dr=(e,r)=>{var o;let t=xs(r),n=jp(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ta=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(bs())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(bs());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};import{Idiomorph as zp}from"idiomorph";var Vc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;zp.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&n){if(s.classList.contains("persona-animate-typing"))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 u=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(u!==c)return}return!1}}}}})};function Jc(e,r){var t,n,s,o,a,i,u,c,p,d,f,g,x,T,C,S,M,H,w,L,W,E,K,Q,X,O,oe,Ee,ae;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(C=(T=e.toolCall)==null?void 0:T.name)!=null?C:"",(H=(M=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:M.length)!=null?H:0,(E=(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?E:"",typeof((K=e.toolCall)==null?void 0:K.args)=="string"?e.toolCall.args.length:(Q=e.toolCall)!=null&&Q.args?JSON.stringify(e.toolCall.args).length:0,(oe=(O=(X=e.reasoning)==null?void 0:X.chunks)==null?void 0:O.length)!=null?oe:0,(ae=(Ee=e.contentParts)==null?void 0:Ee.length)!=null?ae:0,r].join("\0")}function Gc(){return new Map}function Yc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Kc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Xc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function vs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Wo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ro(e,r){return Wo(e)-e.scrollTop<=r}function Cs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function ws(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},gn=1e5,hr=gn+1;function na(e,r=gn){let t=e.style.position,n=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(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Ho=0,yr=null;function ra(e=document){var t;if(Ho++,Ho===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;yr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Ho=Math.max(0,Ho-1),Ho===0&&yr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=yr.originalOverflow,s.style.position=yr.originalPosition,s.style.top=yr.originalTop,s.style.width=yr.originalWidth,o.scrollTo(0,yr.scrollY),yr=null}}}var Ss={side:"right",width:"420px",animate:!0,reveal:"resize"},Kt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},_n=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:Ss.side,width:(s=r==null?void 0:r.width)!=null?s:Ss.width,animate:(o=r==null?void 0:r.animate)!=null?o:Ss.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:Ss.reveal}};var jn={"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 Bo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
6
|
+
`);a=(Ge=Se.pop())!=null?Ge:"";for(let Fe of Se){let Ve=Fe.split(`
|
|
7
|
+
`),I="message",te="";for(let Pe of Ve)Pe.startsWith("event:")?I=Pe.replace("event:","").trim():Pe.startsWith("data:")&&(te+=Pe.replace("data:","").trim());if(!te)continue;let Z;try{Z=JSON.parse(te)}catch(Pe){t({type:"error",error:Pe instanceof Error?Pe:new Error("Failed to parse chat stream payload")});continue}let Ye=I!=="message"?I:(Wt=Z.type)!=null?Wt:"message";if((Rt=this.onSSEEvent)==null||Rt.call(this,Ye,Z),this.parseSSEEvent){g.current=f;let Pe=await this.handleCustomSSEEvent(Z,t,g,d,c,x);if(g.current&&g.current!==f&&(f=g.current),Pe)continue}mt.push(Ye,Z),le()}}mt.flushPending(),le(),mt.destroy()}};function wp(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Fo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function to(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var As="[Image]";function Sp(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ap(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Ep(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Tp(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function Es(e){return{type:"text",text:e}}function Mp(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function kp(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Lp(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.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: ${r.join(", ")}`}}var Hc=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ip=["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"],ir=[...Hc,...Ip];function Pp(e){return Hc.includes(e)||e.startsWith("image/")}function Ts(e){return Pp(e.type)}async function Bc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Ts(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Dc(e,r=ir,t=10*1024*1024){return r.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: ${r.join(", ")}`}}function Wp(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Nc(e,r){let t=Wp(r).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 Ms=class{constructor(r=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=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,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 n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.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 u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.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(r){this.finishedCallbacks.push(r)}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 r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var ks=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.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 u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=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 Oo=class{constructor(r){this.config=r;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 ks;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(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;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=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let x=!1,M=S=>{x||(x=!0,clearTimeout(w),g(new Error(S)))},w=setTimeout(()=>M("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(w),f())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+d)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!x){let k=S.code!==1006?` (code ${S.code})`:"";M("WebSocket connection failed"+k+"."+d)}},{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(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.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(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ms(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(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("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 r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",d=new Blob(this.audioChunks,{type:p});await this.sendAudio(d),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("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(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}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(r=>r.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(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var _r=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.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(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({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(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function no(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Oo(e.runtype);case"browser":if(!_r.isSupported())throw new Error("Browser speech recognition not supported");return new _r(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function da(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return no({type:"runtype",runtype:e.runtype});if(_r.isSupported())return no({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ls(e){try{return da(e),!0}catch{return!1}}var $o=class e{constructor(r={},t){this.config=r;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.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new eo(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Ls((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=no(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,d,f,g,x,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=c.text)!=null&&g.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let w=(M=this.pendingVoiceAssistantMessageId)!=null?M:(x=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:x.id;w&&this.ttsSpokenMessageIds.add(w)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(p=this.callbacks).onVoiceStatusChanged)==null||d.call(p,c)}),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(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new eo(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?Fo():t==="assistant"?to():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:p,streaming:d=!1}=n,g={id:u!=null?u:s==="user"?Fo():s==="assistant"?to():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:d,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,d,f,g;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=Fo(),o=to(),a={id:s,role:"user",content:n||As,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 u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let M=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!M){let w={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(w)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(x instanceof Error?(d=(p=this.callbacks).onError)==null||d.call(p,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=to();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error((u=g==null?void 0:g.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(p=(c=this.callbacks).onError)==null||p.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.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(()=>n.speak(s),50)}static pickBestVoice(r){var n;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=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Kn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as Rp from"lucide";var fe=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=Rp[s];return o?Hp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function Hp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),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){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&u.setAttribute(c,String(p))}),s.appendChild(u)}}}),s}var Is={allowedTypes:ir,maxFileSize:10*1024*1024,maxFiles:4};function Bp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Dp(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-json":"file"}var ro=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Is.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Is.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Is.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:Is.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Dc(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let d=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await Bc(c),f=Ts(c)?URL.createObjectURL(c):null,g={id:Bp(),file:c,previewUrl:f,contentPart:d};this.attachments.push(g),this.renderPreview(g)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=Ts(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.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",n.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=Dp(r.file.type),u=fe(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=Nc(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.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=fe("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(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var Fc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function _o(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Fc(o)&&Fc(s)?t[n]=_o(o,s):t[n]=s}return t}var Pn="min(440px, calc(100vw - 24px))",pa="440px",It={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:Pn,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"}},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 Oc(e,r){if(!(!e&&!r))return e?r?_o(e,r):e:r}function ua(e){var r,t,n,s,o,a,i,u,c,p,d,f,g,x,M,w,S,k,$,v,T;return e?{...It,...e,theme:Oc(It.theme,e.theme),darkTheme:Oc(It.darkTheme,e.darkTheme),launcher:{...It.launcher,...e.launcher,dock:{...(r=It.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=It.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...It.copy,...e.copy},sendButton:{...It.sendButton,...e.sendButton},statusIndicator:{...It.statusIndicator,...e.statusIndicator},voiceRecognition:{...It.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,Te,oe,Ce;let B=(re=It.features)==null?void 0:re.artifacts,E=(Te=e.features)==null?void 0:Te.artifacts,K=(oe=It.features)==null?void 0:oe.scrollToBottom,Q=(Ce=e.features)==null?void 0:Ce.scrollToBottom,G=B===void 0&&E===void 0?void 0:{...B,...E,layout:{...B==null?void 0:B.layout,...E==null?void 0:E.layout}},j=K===void 0&&Q===void 0?void 0:{...K,...Q};return{...It.features,...e.features,...j!==void 0?{scrollToBottom:j}:{},...G!==void 0?{artifacts:G}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...It.layout,...e.layout,header:{...(a=It.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=It.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(p=It.layout)==null?void 0:p.messages)==null?void 0:d.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(M=(x=It.layout)==null?void 0:x.messages)==null?void 0:M.timestamp,...(S=(w=e.layout)==null?void 0:w.messages)==null?void 0:S.timestamp}},slots:{...(k=It.layout)==null?void 0:k.slots,...($=e.layout)==null?void 0:$.slots}},markdown:{...It.markdown,...e.markdown,options:{...(v=It.markdown)==null?void 0:v.options,...(T=e.markdown)==null?void 0:T.options}},messageActions:{...It.messageActions,...e.messageActions}}:It}var $c={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"}},_c={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"}},jc={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:Pn,maxWidth:pa,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"},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,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?jo(e,n):n}function ma(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=jo(e,a);u!==void 0&&(r[i]={path:i,value:u,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"),r}function zc(e){let r=[],t=[];return e.palette||r.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:r.length===0,errors:r,warnings:t}}function qc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=qc(o,s):t[n]=s}return t}function Np(e,r){return r?qc(e,r):e}function zo(e,r={}){var s,o,a,i,u,c,p,d,f,g,x,M,w;let t={palette:$c,semantic:_c,components:jc},n={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,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.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,...(f=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(w=e==null?void 0:e.semantic)==null?void 0:w.typography}},components:Np(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let S=zc(n);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(k=>k.message).join(", ")}`)}if(r.plugins)for(let S of r.plugins)n=S.transform(n);return n}function ga(e){var x,M,w,S,k,$,v,T,B,E,K,Q,G,j,re,Te,oe,Ce,Ne,he,ke,Be,ue,Y,ye,de,we,Me,ae,Le,Ie,P,q,ie,F,U,me,Je,ee,le,Pt,mt,ze,Xt,Xe,ge,Ge,Wt,Rt,W,X,Se,Fe,Ve,I,te,Z,Ye,Pe,ne,pe,He,at,Ft,ft,jt,xt,nt,vt,qe,zt,qn,Xn,Rn,it,Tr,Un,Mr,Tn,qr,cr,Zn,pt,bn,Hn,on,dr,xn,At,sn,Mn,pr,Qn,ur,Vn,vn,Jn,wt,Ot,$t,Cn,mr,Bn,wn,O,Dn,kn,gr,cn,dn;let r=ma(e),t={};for(let[ce,Sn]of Object.entries(r)){let er=ce.replace(/\./g,"-");t[`--persona-${er}`]=Sn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(w=t["--persona-semantic-colors-accent"])!=null?w:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(k=t["--persona-semantic-colors-background"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-container"]=($=t["--persona-semantic-colors-container"])!=null?$:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(v=t["--persona-semantic-colors-text"])!=null?v:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(T=t["--persona-semantic-colors-text-muted"])!=null?T:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(B=t["--persona-semantic-colors-text-inverse"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(E=t["--persona-semantic-colors-border"])!=null?E:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(K=t["--persona-semantic-colors-divider"])!=null?K:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(Q=t["--persona-components-voice-recording-indicator"])!=null?Q:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(G=t["--persona-components-voice-recording-background"])!=null?G:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(j=t["--persona-components-voice-processing-icon"])!=null?j:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(re=t["--persona-components-voice-speaking-icon"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Te=t["--persona-components-approval-requested-background"])!=null?Te:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(oe=t["--persona-components-approval-requested-border"])!=null?oe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ce=t["--persona-components-approval-requested-text"])!=null?Ce:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(Ne=t["--persona-components-approval-approve-background"])!=null?Ne:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(he=t["--persona-components-approval-deny-background"])!=null?he:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ke=t["--persona-components-attachment-image-background"])!=null?ke:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Be=t["--persona-components-attachment-image-border"])!=null?Be:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ue=t["--persona-semantic-typography-fontFamily"])!=null?ue:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Y=t["--persona-semantic-typography-fontSize"])!=null?Y:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ye=t["--persona-semantic-typography-fontWeight"])!=null?ye:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(de=t["--persona-semantic-typography-lineHeight"])!=null?de: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"]=(we=t["--persona-palette-radius-sm"])!=null?we:"0.125rem",t["--persona-radius-md"]=(Me=t["--persona-palette-radius-md"])!=null?Me:"0.375rem",t["--persona-radius-lg"]=(ae=t["--persona-palette-radius-lg"])!=null?ae:"0.5rem",t["--persona-radius-xl"]=(Le=t["--persona-palette-radius-xl"])!=null?Le:"0.75rem",t["--persona-radius-full"]=(Ie=t["--persona-palette-radius-full"])!=null?Ie:"9999px",t["--persona-launcher-radius"]=(q=(P=t["--persona-components-launcher-borderRadius"])!=null?P:t["--persona-palette-radius-full"])!=null?q:"9999px",t["--persona-launcher-bg"]=(ie=t["--persona-components-launcher-background"])!=null?ie:t["--persona-primary"],t["--persona-launcher-fg"]=(F=t["--persona-components-launcher-foreground"])!=null?F:t["--persona-text-inverse"],t["--persona-launcher-border"]=(U=t["--persona-components-launcher-border"])!=null?U:t["--persona-border"],t["--persona-button-primary-bg"]=(me=t["--persona-components-button-primary-background"])!=null?me:t["--persona-primary"],t["--persona-button-primary-fg"]=(Je=t["--persona-components-button-primary-foreground"])!=null?Je:t["--persona-text-inverse"],t["--persona-button-radius"]=(le=(ee=t["--persona-components-button-primary-borderRadius"])!=null?ee:t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-panel-radius"]=(mt=(Pt=t["--persona-components-panel-borderRadius"])!=null?Pt:t["--persona-radius-xl"])!=null?mt:"0.75rem",t["--persona-panel-border"]=(ze=t["--persona-components-panel-border"])!=null?ze:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Xe=(Xt=t["--persona-components-panel-shadow"])!=null?Xt:t["--persona-palette-shadows-xl"])!=null?Xe:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ge=(ge=t["--persona-components-input-borderRadius"])!=null?ge:t["--persona-radius-lg"])!=null?Ge:"0.5rem",t["--persona-message-user-radius"]=(Rt=(Wt=t["--persona-components-message-user-borderRadius"])!=null?Wt:t["--persona-radius-lg"])!=null?Rt:"0.5rem",t["--persona-message-assistant-radius"]=(X=(W=t["--persona-components-message-assistant-borderRadius"])!=null?W:t["--persona-radius-lg"])!=null?X:"0.5rem",t["--persona-header-bg"]=(Se=t["--persona-components-header-background"])!=null?Se:t["--persona-surface"],t["--persona-header-border"]=(Fe=t["--persona-components-header-border"])!=null?Fe:t["--persona-divider"],t["--persona-header-icon-bg"]=(Ve=t["--persona-components-header-iconBackground"])!=null?Ve:t["--persona-primary"],t["--persona-header-icon-fg"]=(I=t["--persona-components-header-iconForeground"])!=null?I:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(te=t["--persona-components-header-titleForeground"])!=null?te:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Z=t["--persona-components-header-subtitleForeground"])!=null?Z:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Ye=t["--persona-components-header-actionIconForeground"])!=null?Ye:t["--persona-muted"];let n=(Pe=e.components)==null?void 0:Pe.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(ne=t["--persona-components-input-background"])!=null?ne:t["--persona-surface"],t["--persona-input-placeholder"]=(pe=t["--persona-components-input-placeholder"])!=null?pe:t["--persona-text-muted"],t["--persona-message-user-bg"]=(He=t["--persona-components-message-user-background"])!=null?He:t["--persona-accent"],t["--persona-message-user-text"]=(at=t["--persona-components-message-user-text"])!=null?at:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ft=t["--persona-components-message-user-shadow"])!=null?Ft:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(ft=t["--persona-components-message-assistant-background"])!=null?ft:t["--persona-surface"],t["--persona-message-assistant-text"]=(jt=t["--persona-components-message-assistant-text"])!=null?jt:t["--persona-text"],t["--persona-message-assistant-border"]=(xt=t["--persona-components-message-assistant-border"])!=null?xt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(nt=t["--persona-components-message-assistant-shadow"])!=null?nt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(qe=(vt=t["--persona-components-scrollToBottom-background"])!=null?vt:t["--persona-button-primary-bg"])!=null?qe:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(qn=(zt=t["--persona-components-scrollToBottom-foreground"])!=null?zt:t["--persona-button-primary-fg"])!=null?qn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Xn=t["--persona-components-scrollToBottom-border"])!=null?Xn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Rn=t["--persona-components-scrollToBottom-size"])!=null?Rn:"40px",t["--persona-scroll-to-bottom-radius"]=(Un=(Tr=(it=t["--persona-components-scrollToBottom-borderRadius"])!=null?it:t["--persona-button-radius"])!=null?Tr:t["--persona-radius-full"])!=null?Un:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Tn=(Mr=t["--persona-components-scrollToBottom-shadow"])!=null?Mr:t["--persona-palette-shadows-sm"])!=null?Tn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(qr=t["--persona-components-scrollToBottom-padding"])!=null?qr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(cr=t["--persona-components-scrollToBottom-gap"])!=null?cr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(pt=(Zn=t["--persona-components-scrollToBottom-fontSize"])!=null?Zn:t["--persona-palette-typography-fontSize-sm"])!=null?pt:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(bn=t["--persona-components-scrollToBottom-iconSize"])!=null?bn:"14px",t["--persona-tool-bubble-shadow"]=(Hn=t["--persona-components-toolBubble-shadow"])!=null?Hn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(on=t["--persona-components-reasoningBubble-shadow"])!=null?on:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(dr=t["--persona-components-composer-shadow"])!=null?dr:"none",t["--persona-md-inline-code-bg"]=(xn=t["--persona-components-markdown-inlineCode-background"])!=null?xn:t["--persona-container"],t["--persona-md-inline-code-color"]=(At=t["--persona-components-markdown-inlineCode-foreground"])!=null?At:t["--persona-text"],t["--persona-md-link-color"]=(Mn=(sn=t["--persona-components-markdown-link-foreground"])!=null?sn:t["--persona-accent"])!=null?Mn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(pr=t["--persona-components-markdown-codeBlock-background"])!=null?pr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Qn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Qn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(ur=t["--persona-components-markdown-codeBlock-textColor"])!=null?ur:"inherit",t["--persona-md-table-header-bg"]=(Vn=t["--persona-components-markdown-table-headerBackground"])!=null?Vn:t["--persona-container"],t["--persona-md-table-border-color"]=(vn=t["--persona-components-markdown-table-borderColor"])!=null?vn:t["--persona-border"],t["--persona-md-hr-color"]=(Jn=t["--persona-components-markdown-hr-color"])!=null?Jn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(wt=t["--persona-components-markdown-blockquote-borderColor"])!=null?wt:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Ot=t["--persona-components-markdown-blockquote-background"])!=null?Ot:"transparent",t["--persona-md-blockquote-text-color"]=($t=t["--persona-components-markdown-blockquote-textColor"])!=null?$t:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Cn=t["--persona-components-collapsibleWidget-container"])!=null?Cn:t["--persona-surface"],t["--cw-surface"]=(mr=t["--persona-components-collapsibleWidget-surface"])!=null?mr:t["--persona-surface"],t["--cw-border"]=(Bn=t["--persona-components-collapsibleWidget-border"])!=null?Bn:t["--persona-border"],t["--persona-message-border"]=(wn=t["--persona-components-message-border"])!=null?wn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let g=c==null?void 0:c.artifact;if(g!=null&&g.toolbar){let ce=g.toolbar;ce.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ce.iconHoverColor),ce.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ce.iconHoverBackground),ce.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ce.iconPadding),ce.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ce.iconBorderRadius),ce.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ce.iconBorder),ce.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ce.toggleGroupGap),ce.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ce.toggleBorderRadius),ce.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ce.copyBackground),ce.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ce.copyBorder),ce.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ce.copyColor),ce.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ce.copyBorderRadius),ce.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ce.copyPadding),ce.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ce.copyMenuBackground,t["--persona-dropdown-bg"]=(O=t["--persona-dropdown-bg"])!=null?O:ce.copyMenuBackground),ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ce.copyMenuBorder,t["--persona-dropdown-border"]=(Dn=t["--persona-dropdown-border"])!=null?Dn:ce.copyMenuBorder),ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(kn=t["--persona-dropdown-shadow"])!=null?kn:ce.copyMenuShadow),ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(gr=t["--persona-dropdown-radius"])!=null?gr:ce.copyMenuBorderRadius),ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(cn=t["--persona-dropdown-item-hover-bg"])!=null?cn:ce.copyMenuItemHoverBackground),ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ce.iconBackground),ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ce.toolbarBorder)}if(g!=null&&g.tab){let ce=g.tab;ce.background&&(t["--persona-artifact-tab-bg"]=ce.background),ce.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ce.activeBackground),ce.activeBorder&&(t["--persona-artifact-tab-active-border"]=ce.activeBorder),ce.borderRadius&&(t["--persona-artifact-tab-radius"]=ce.borderRadius),ce.textColor&&(t["--persona-artifact-tab-color"]=ce.textColor),ce.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ce.hoverBackground),ce.listBackground&&(t["--persona-artifact-tab-list-bg"]=ce.listBackground),ce.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ce.listBorderColor),ce.listPadding&&(t["--persona-artifact-tab-list-padding"]=ce.listPadding)}if(g!=null&&g.pane){let ce=g.pane;if(ce.toolbarBackground){let Sn=(dn=jo(e,ce.toolbarBackground))!=null?dn:ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Sn}}return t}var Fp={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 Op={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"}}},Uc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ps=()=>{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"},$p=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Ps()},Vc=e=>$p(e),_p=e=>zo(e),jp=e=>{var t;let r=zo(void 0,{validate:!1});return zo({...e,palette:{...r.palette,colors:{...Op.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Ws=e=>{let r=Vc(e),t=Uc(e==null?void 0:e.theme),n=Uc(e==null?void 0:e.darkTheme);return r==="dark"?jp(_o(t!=null?t:{},n!=null?n:{})):_p(t)},zp=e=>ga(e),jr=(e,r)=>{var o;let t=Ws(r),n=zp(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},fa=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Ps())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Ps());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};import{Idiomorph as qp}from"idiomorph";var Jc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;qp.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&n){if(s.classList.contains("persona-animate-typing"))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 u=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(u!==c)return}return!1}}}}})};function Gc(e,r){var t,n,s,o,a,i,u,c,p,d,f,g,x,M,w,S,k,$,v,T,B,E,K,Q,G,j,re,Te,oe;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(w=(M=e.toolCall)==null?void 0:M.name)!=null?w:"",($=(k=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:k.length)!=null?$:0,(E=(B=(T=(v=e.toolCall)==null?void 0:v.chunks)==null?void 0:T[e.toolCall.chunks.length-1])==null?void 0:B.slice(-32))!=null?E:"",typeof((K=e.toolCall)==null?void 0:K.args)=="string"?e.toolCall.args.length:(Q=e.toolCall)!=null&&Q.args?JSON.stringify(e.toolCall.args).length:0,(re=(j=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:j.length)!=null?re:0,(oe=(Te=e.contentParts)==null?void 0:Te.length)!=null?oe:0,r].join("\0")}function Kc(){return new Map}function Yc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Xc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Zc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Rs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function qo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Uo(e,r){return qo(e)-e.scrollTop<=r}function Hs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function Bs(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var rn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,Cr=hn+1;function ha(e,r=hn){let t=e.style.position,n=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(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Vo=0,wr=null;function ya(e=document){var t;if(Vo++,Vo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;wr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Vo=Math.max(0,Vo-1),Vo===0&&wr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=wr.originalOverflow,s.style.position=wr.originalPosition,s.style.top=wr.originalTop,s.style.width=wr.originalWidth,o.scrollTo(0,wr.scrollY),wr=null}}}var Ds={side:"right",width:"420px",animate:!0,reveal:"resize"},Yt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},jn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:Ds.side,width:(s=r==null?void 0:r.width)!=null?s:Ds.width,animate:(o=r==null?void 0:r.animate)!=null?o:Ds.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:Ds.reveal}};var zn={"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 Jo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
8
8
|
<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>
|
|
9
9
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -12,14 +12,14 @@ import{Marked as ap}from"marked";var ip=e=>{if(e)return e},ss=e=>{var s,o;let r=
|
|
|
12
12
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<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>
|
|
15
|
-
`,t.addEventListener("click",r);let n=o=>{var H,w,L,W,E,K,Q,X,O,oe,Ee,ae,we,$e;let a=(H=o.launcher)!=null?H:{},i=Kt(o),u=t.querySelector("[data-role='launcher-title']");if(u){let he=(w=a.title)!=null?w:"Chat Assistant";u.textContent=he,u.setAttribute("title",he)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let he=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=he,c.setAttribute("title",he)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let he=(W=a.agentIconSize)!=null?W:"40px";if(d.style.height=he,d.style.width=he,d.innerHTML="",a.agentIconName){let We=parseFloat(he)||24,Re=ye(a.agentIconName,We*.6,"var(--persona-text-inverse, #ffffff)",2);Re?(d.appendChild(Re),d.style.display=""):(d.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(K=a.agentIconText)!=null?K:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let he=(Q=a.agentIconSize)!=null?Q:"40px";f.style.height=he,f.style.width=he,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let he=(X=a.callToActionIconSize)!=null?X:"32px";g.style.height=he,g.style.width=he,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let We=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,We=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Re=parseFloat(he)||24,ie=Math.max(Re-We,8),Z=ye(a.callToActionIconName,ie,"currentColor",2);Z?g.appendChild(Z):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(oe=a.callToActionIconText)!=null?oe:"\u2197"}let x=a.position&&jn[a.position]?jn[a.position]:jn["bottom-right"],T="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:`${T} ${x}`,i||(t.style.zIndex=String((Ee=a.zIndex)!=null?Ee:gn));let S="1px solid var(--persona-border, #e5e7eb)",M="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=(ae=a.border)!=null?ae:S,t.style.boxShadow=(we=a.shadow)!=null?we:M,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=($e=a.collapsedMaxWidth)!=null?$e:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var fn={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))"},br=e=>{var X,O,oe,Ee,ae,we,$e,he,We,Re,ie,Z,me,V,re,He,ge,Be,st,z,U,se,N,J,ce,fe,te,pe,kt,dt,Wt,Jt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(X=r==null?void 0:r.launcher)!=null?X:{},o=(O=s.headerIconSize)!=null?O:"48px",a=(oe=s.closeButtonSize)!=null?oe:"32px",i=(Ee=s.closeButtonPlacement)!=null?Ee:"inline",u=(ae=s.headerIconHidden)!=null?ae:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let P=parseFloat(o)||24,$=ye(c,P*.6,"currentColor",1);$?p.replaceChildren($):p.textContent=($e=(we=r==null?void 0:r.launcher)==null?void 0:we.agentIconText)!=null?$e:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let P=h("img");P.src=r.launcher.iconUrl,P.alt="",P.className="persona-rounded-xl persona-object-cover",P.style.height=o,P.style.width=o,p.replaceChildren(P)}else p.textContent=(Re=(We=r==null?void 0:r.launcher)==null?void 0:We.agentIconText)!=null?Re:"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=fn.titleColor,f.textContent=(Z=(ie=r==null?void 0:r.launcher)==null?void 0:ie.title)!=null?Z:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=fn.subtitleColor,g.textContent=(V=(me=r==null?void 0:r.launcher)==null?void 0:me.subtitle)!=null?V:"Here to help you get answers fast",d.append(f,g),u?n.append(d):n.append(p,d);let x=(re=s.clearChat)!=null?re:{},T=(He=x.enabled)!=null?He:!0,C=(ge=x.placement)!=null?ge:"inline",S=null,M=null;if(T){let P=(Be=x.size)!=null?Be:"32px",$=(st=x.iconName)!=null?st:"refresh-cw",ne=(z=x.iconColor)!=null?z:"",Pe=(U=x.backgroundColor)!=null?U:"",Fe=(se=x.borderWidth)!=null?se:"",Ce=(N=x.borderColor)!=null?N:"",be=(J=x.borderRadius)!=null?J:"",at=(ce=x.paddingX)!=null?ce:"",mt=(fe=x.paddingY)!=null?fe:"",At=(te=x.tooltipText)!=null?te:"Clear chat",j=(pe=x.showTooltip)!=null?pe:!0;M=h("div",C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),C==="top-right"&&(M.style.right="48px"),S=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"),S.style.height=P,S.style.width=P,S.type="button",S.setAttribute("aria-label",At),S.style.color=ne||fn.actionIconColor;let xe=ye($,"20px","currentColor",1);if(xe&&S.appendChild(xe),Pe&&(S.style.backgroundColor=Pe,S.classList.remove("hover:persona-bg-gray-100")),Fe||Ce){let ue=Fe||"0px",Ze=Ce||"transparent";S.style.border=`${ue} solid ${Ze}`,S.classList.remove("persona-border-none")}if(be&&(S.style.borderRadius=be,S.classList.remove("persona-rounded-full")),at?(S.style.paddingLeft=at,S.style.paddingRight=at):(S.style.paddingLeft="",S.style.paddingRight=""),mt?(S.style.paddingTop=mt,S.style.paddingBottom=mt):(S.style.paddingTop="",S.style.paddingBottom=""),M.appendChild(S),j&&At&&S&&M){let ue=null,Ze=()=>{if(ue||!S)return;let de=S.ownerDocument,Te=de.body;if(!Te)return;ue=Gn(de,"div","persona-clear-chat-tooltip"),ue.textContent=At;let Ve=Gn(de,"div");Ve.className="persona-clear-chat-tooltip-arrow",ue.appendChild(Ve);let vt=S.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(hr),ue.style.left=`${vt.left+vt.width/2}px`,ue.style.top=`${vt.top-8}px`,ue.style.transform="translate(-50%, -100%)",Te.appendChild(ue)},qe=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};M.addEventListener("mouseenter",Ze),M.addEventListener("mouseleave",qe),S.addEventListener("focus",Ze),S.addEventListener("blur",qe),M._cleanupTooltip=()=>{qe(),M&&(M.removeEventListener("mouseenter",Ze),M.removeEventListener("mouseleave",qe)),S&&(S.removeEventListener("focus",Ze),S.removeEventListener("blur",qe))}}C==="inline"&&n.appendChild(M)}let H=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":T&&C==="inline"?"":"persona-ml-auto"),w=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");w.style.height=a,w.style.width=a,w.type="button";let L=(kt=s.closeButtonTooltipText)!=null?kt:"Close chat",W=(dt=s.closeButtonShowTooltip)!=null?dt:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let E=(Wt=s.closeButtonIconName)!=null?Wt:"x",K=(Jt=s.closeButtonIconText)!=null?Jt:"\xD7";w.style.color=s.closeButtonColor||fn.actionIconColor;let Q=ye(E,"20px","currentColor",1);if(Q?w.appendChild(Q):w.textContent=K,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let P=s.closeButtonBorderWidth||"0px",$=s.closeButtonBorderColor||"transparent";w.style.border=`${P} solid ${$}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),H.appendChild(w),W&&L){let P=null,$=()=>{if(P)return;let Pe=w.ownerDocument,Fe=Pe.body;if(!Fe)return;P=Gn(Pe,"div","persona-clear-chat-tooltip"),P.textContent=L;let Ce=Gn(Pe,"div");Ce.className="persona-clear-chat-tooltip-arrow",P.appendChild(Ce);let be=w.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(hr),P.style.left=`${be.left+be.width/2}px`,P.style.top=`${be.top-8}px`,P.style.transform="translate(-50%, -100%)",Fe.appendChild(P)},ne=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};H.addEventListener("mouseenter",$),H.addEventListener("mouseleave",ne),w.addEventListener("focus",$),w.addEventListener("blur",ne),H._cleanupTooltip=()=>{ne(),H.removeEventListener("mouseenter",$),H.removeEventListener("mouseleave",ne),w.removeEventListener("focus",$),w.removeEventListener("blur",ne)}}return i!=="top-right"&&n.appendChild(H),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:g,closeButton:w,closeButtonWrapper:H,clearChatButton:S,clearChatButtonWrapper:M}},Zr=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function Nr(e){let{items:r,onSelect:t,anchor:n,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(hr)):(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 g of r){if(g.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let C=ye(g.icon,16,"currentColor",1.5);C&&x.appendChild(C)}let T=document.createElement("span");T.textContent=g.label,x.appendChild(T),x.addEventListener("click",C=>{C.stopPropagation(),p(),t(g.id)}),a.appendChild(x)}let i=null;function u(){if(!o)return;let g=n.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!n.contains(x.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function d(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:d,destroy:f}}function Pt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=ye(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[p,d]of Object.entries(i))u.setAttribute(p,d);return u}function As(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=ye(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let d=h("span");if(d.textContent=t,p.appendChild(d),i&&p.addEventListener("click",i),u)for(let[f,g]of Object.entries(u))p.setAttribute(f,g);return p}function Es(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let d;p.icon?d=Pt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,u(),n(p.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",p.label),d.title=p.label,d.textContent=p.label,d.addEventListener("click",()=>{a=p.id,u(),n(p.id)})),d.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:d}),o.appendChild(d)}function c(p){a=p,u()}return{element:o,setSelected:c}}function oa(e){var g,x;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let d=ye(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),u&&(c.style.borderRadius=(g=u.borderRadius)!=null?g:"10px",c.style.padding=(x=u.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var T,C;c.style.backgroundColor=(T=u.background)!=null?T:"",c.style.borderColor=(C=u.border)!=null?C:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Nr({items:n,onSelect:T=>{c.setAttribute("aria-expanded","false"),s(T)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",T=>{T.stopPropagation();let C=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",C?"false":"true"),f.toggle()}),c.addEventListener("keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),c.click())}),{element:c,setLabel:T=>{p.textContent=T,c.setAttribute("aria-label",T)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let T=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Zc=e=>{var n;let r=br({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.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 r};function qp(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){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=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=ye(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=Nr({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Qc=e=>{var M,H,w,L,W,E,K,Q,X;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},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 u=s==null?void 0:s.titleMenu,c,p;if(u)c=oa({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=fn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=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=fn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),qp(c,s==null?void 0:s.trailingActions,(W=s==null?void 0:s.onAction)!=null?W:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let oe=s.onTitleClick;c.addEventListener("click",Ee=>{Ee.target.closest("button")||oe()}),c.addEventListener("keydown",Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),oe())})}let O=s==null?void 0:s.titleRowHover;O&&(c.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",c.style.padding=(K=O.padding)!=null?K:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var oe,Ee;c.style.backgroundColor=(oe=O.background)!=null?oe:"",c.style.borderColor=(Ee=O.border)!=null?Ee:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(Q=a.closeButtonSize)!=null?Q:"32px",f=h("div",""),g=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");g.style.height=d,g.style.width=d,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||fn.actionIconColor;let x=(X=a.closeButtonIconName)!=null?X:"x",T=ye(x,"20px","currentColor",2);T?g.appendChild(T):g.textContent="\xD7",n&&g.addEventListener("click",n),f.appendChild(g),i.appendChild(f);let C=h("div");C.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:C,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},sa={default:Zc,minimal:Qc},ed=e=>{var r;return(r=sa[e])!=null?r:sa.default},Do=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),p=h("div");p.style.display="none";let d=h("span"),f=h("span"),g=h("button");g.style.display="none";let x=h("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:d,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=ed(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var No=e=>{var ge,Be,st,z,U,se,N,J,ce,fe,te,pe,kt,dt,Wt,Jt,P,$,ne,Pe,Fe,Ce,be,at,mt,At,j;let{config:r}=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 n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),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 o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(Be=(ge=r==null?void 0:r.copy)==null?void 0:ge.inputPlaceholder)!=null?Be:"Type your message\u2026",o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let xe=Math.min(o.scrollHeight,u);o.style.height=`${xe}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(st=r==null?void 0:r.sendButton)!=null?st:{},d=(z=p.useIcon)!=null?z:!1,f=(U=p.iconText)!=null?U:"\u2191",g=p.iconName,x=(se=p.tooltipText)!=null?se:"Send message",T=(N=p.showTooltip)!=null?N:!1,C=(J=p.size)!=null?J:"40px",S=p.backgroundColor,M=p.textColor,H=h("div","persona-send-button-wrapper"),w=h("button",d?"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");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),d){if(w.style.width=C,w.style.height=C,w.style.minWidth=C,w.style.minHeight=C,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",M?w.style.color=M:w.style.color="var(--persona-button-primary-fg, #ffffff)",g){let xe=parseFloat(C)||24,ue=(M==null?void 0:M.trim())||"currentColor",Ze=ye(g,xe,ue,2);Ze?w.appendChild(Ze):w.textContent=f}else w.textContent=f;S?w.style.backgroundColor=S:w.classList.add("persona-bg-persona-primary")}else w.textContent=(fe=(ce=r==null?void 0:r.copy)==null?void 0:ce.sendButtonLabel)!=null?fe:"Send",M?w.style.color=M:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),T&&x){let xe=h("div","persona-send-button-tooltip");xe.textContent=x,H.appendChild(xe)}H.appendChild(w);let L=(te=r==null?void 0:r.voiceRecognition)!=null?te:{},W=L.enabled===!0,E=null,K=null,Q=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),X=((pe=L.provider)==null?void 0:pe.type)==="runtype";if(W&&(Q||X)){K=h("div","persona-send-button-wrapper"),E=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),E.type="button",E.setAttribute("data-persona-composer-mic",""),E.setAttribute("aria-label","Start voice recognition");let xe=(kt=L.iconName)!=null?kt:"mic",ue=(dt=L.iconSize)!=null?dt:C,Ze=parseFloat(ue)||24,qe=(Wt=L.backgroundColor)!=null?Wt:S,de=(Jt=L.iconColor)!=null?Jt:M;E.style.width=ue,E.style.height=ue,E.style.minWidth=ue,E.style.minHeight=ue,E.style.fontSize="18px",E.style.lineHeight="1",de?E.style.color=de:E.style.color="var(--persona-text, #111827)";let Ve=ye(xe,Ze,de||"currentColor",1.5);Ve?E.appendChild(Ve):E.textContent="\u{1F3A4}",qe&&(E.style.backgroundColor=qe),L.borderWidth&&(E.style.borderWidth=L.borderWidth,E.style.borderStyle="solid"),L.borderColor&&(E.style.borderColor=L.borderColor),L.paddingX&&(E.style.paddingLeft=L.paddingX,E.style.paddingRight=L.paddingX),L.paddingY&&(E.style.paddingTop=L.paddingY,E.style.paddingBottom=L.paddingY),K.appendChild(E);let vt=(P=L.tooltipText)!=null?P:"Start voice recognition";if((($=L.showTooltip)!=null?$:!1)&&vt){let pt=h("div","persona-send-button-tooltip");pt.textContent=vt,K.appendChild(pt)}}let oe=(ne=r==null?void 0:r.attachments)!=null?ne:{},Ee=oe.enabled===!0,ae=null,we=null,$e=null,he=null;if(Ee){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",$e=h("input"),$e.type="file",$e.accept=((Pe=oe.allowedTypes)!=null?Pe:or).join(","),$e.multiple=((Fe=oe.maxFiles)!=null?Fe:4)>1,$e.style.display="none",$e.setAttribute("aria-label","Attach files"),we=h("div","persona-send-button-wrapper"),ae=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ae.type="button",ae.setAttribute("aria-label",(Ce=oe.buttonTooltipText)!=null?Ce:"Attach file");let xe=(be=oe.buttonIconName)!=null?be:"paperclip",ue=C,Ze=parseFloat(ue)||40,qe=Math.round(Ze*.6);ae.style.width=ue,ae.style.height=ue,ae.style.minWidth=ue,ae.style.minHeight=ue,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.style.backgroundColor="transparent",ae.style.color="var(--persona-primary, #111827)",ae.style.border="none",ae.style.borderRadius="6px",ae.style.transition="background-color 0.15s ease",ae.addEventListener("mouseenter",()=>{ae.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ae.addEventListener("mouseleave",()=>{ae.style.backgroundColor="transparent"});let de=ye(xe,qe,"currentColor",1.5);de?ae.appendChild(de):ae.textContent="\u{1F4CE}",ae.addEventListener("click",vt=>{vt.preventDefault(),$e==null||$e.click()}),we.appendChild(ae);let Te=(at=oe.buttonTooltipText)!=null?at:"Attach file",Ve=h("div","persona-send-button-tooltip");Ve.textContent=Te,we.appendChild(Ve)}s.addEventListener("click",xe=>{xe.target!==w&&xe.target!==H&&xe.target!==E&&xe.target!==K&&xe.target!==ae&&xe.target!==we&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),$e&&s.append($e),s.append(o);let We=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Re=h("div","persona-flex persona-items-center persona-gap-2");we&&Re.append(we);let ie=h("div","persona-flex persona-items-center persona-gap-1");K&&ie.append(K),ie.append(H),We.append(Re,ie),s.append(We);let Z=(mt=r==null?void 0:r.statusIndicator)!=null?mt:{},me=Z.align==="left"?"persona-text-left":Z.align==="center"?"persona-text-center":"persona-text-right",V=h("div",`persona-mt-2 ${me} persona-text-xs persona-text-persona-muted`);V.setAttribute("data-persona-composer-status","");let re=(At=Z.visible)!=null?At:!0;V.style.display=re?"":"none";let He=(j=Z.idleText)!=null?j:"Online";if(Z.idleLink){let xe=h("a");xe.href=Z.idleLink,xe.target="_blank",xe.rel="noopener noreferrer",xe.textContent=He,xe.style.color="inherit",xe.style.textDecoration="none",V.appendChild(xe)}else V.textContent=He;return t.append(n,s,V),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:H,micButton:E,micButtonWrapper:K,statusText:V,attachmentButton:ae,attachmentButtonWrapper:we,attachmentInput:$e,attachmentPreviewsContainer:he,actionsRow:We,leftActions:Re,rightActions:ie}};var td=e=>{var c,p,d,f,g,x,T,C,S;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Kt(e)){let M=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),H=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return M.appendChild(H),{wrapper:M,panel:H}}if(!r){let M=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),H=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return M.style.width=w,H.style.width="100%",M.appendChild(H),{wrapper:M,panel:H}}let n=(g=e==null?void 0:e.launcher)!=null?g:{},s=n.position&&jn[n.position]?jn[n.position]:jn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((T=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?T:gn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(S=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?S:e==null?void 0:e.launcherWidth,u=i!=null?i:In;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},nd=(e,r=!0)=>{var C,S,M,H,w,L,W,E,K;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-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=n?Do(e,n,{showClose:r}):br({config:e,showClose:r}),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=Kt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(H=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?H:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",u.append(c,p);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(W=e==null?void 0:e.layout)==null?void 0:W.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,d);let x=No({config:e}),T=((K=e==null?void 0:e.layout)==null?void 0:K.showFooter)!==!1;return s?Zr(t,o,e):(o.header.style.display="none",Zr(t,o,e)),t.append(a),T||(x.footer.style.display="none"),t.append(x.footer),{container:t,body:a,messagesWrapper:d,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,introTitle:c,introSubtitle:p,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:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions}};var Up=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Vp=320,Jp=320,Gp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Yp=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Vp}px`,c.style.maxHeight=`${Jp}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),Up(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},Qr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="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 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="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},od=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Qr};if(r){let s=r(n);if(s!==null)return s}return Qr()},Kp=(e,r)=>{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"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},rd=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Xp=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){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},sd=(e,r,t)=>{var g,x,T,C,S,M;let n=(g=r.showCopy)!=null?g:!0,s=(x=r.showUpvote)!=null?x:!0,o=(T=r.showDownvote)!=null?T:!0;if(!n&&!s&&!o){let H=h("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(C=r.visibility)!=null?C:"hover",i=(S=r.align)!=null?S:"right",u=(M=r.layout)!=null?M:"pill-inside",c={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"}[u],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(H,w,L)=>{let W=Pt({icon:H,label:w,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",L),W};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},Fo=(e,r,t,n,s,o)=>{var X,O,oe,Ee,ae,we,$e;let a=t!=null?t:{},i=(X=a.layout)!=null?X:"bubble",u=a.avatar,c=a.timestamp,p=(O=u==null?void 0:u.show)!=null?O:!1,d=(oe=c==null?void 0:c.show)!=null?oe:!1,f=(Ee=u==null?void 0:u.position)!=null?Ee:"left",g=(ae=c==null?void 0:c.position)!=null?ae:"below",x=Xp(e.role,i),T=h("div",x.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=Gp(e),S=($e=(we=e.content)==null?void 0:we.trim())!=null?$e:"",H=C.length>0&&S===ps,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),W=null;if(H?(W=document.createElement("div"),W.innerHTML=L,W.style.display="none",w.appendChild(W)):w.innerHTML=L,d&&g==="inline"&&e.createdAt){let he=rd(e,c);he.classList.add("persona-ml-2","persona-inline"),w.appendChild(he)}if(C.length>0){let he=Yp(C,!H&&!!S,()=>{H&&W&&(W.style.display="")});he?T.appendChild(he):H&&W&&(W.style.display="")}if(T.appendChild(w),d&&g==="below"&&e.createdAt){let he=rd(e,c);he.classList.add("persona-mt-1"),T.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=od("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&T.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=sd(e,n,s);T.appendChild(he)}if(!p||e.role==="system")return T;let K=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Q=Kp(u,e.role);return f==="right"||f==="left"&&e.role==="user"?K.append(T,Q):K.append(Q,T),T.classList.remove("persona-max-w-[85%]"),T.classList.add("persona-max-w-[calc(85%-2.5rem)]"),K},Zp=(e,r,t,n,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}):Fo(e,r,t,n,s,o)};var eo=new Set,Qp=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),eu=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
|
|
16
|
-
`):""},
|
|
17
|
-
`);let s=
|
|
18
|
-
`):""},ru=(e,r)=>{var p,d,f,g,x;let t=e.toolCall,n=(p=r==null?void 0:r.features)==null?void 0:p.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=nu(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=t?Pc(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=(g=r==null?void 0:r.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((x=t.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&u.activeTextTemplate?c=zs(t,u.activeTextTemplate,c):!i&&u.completeTextTemplate&&(c=zs(t,u.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},id=(e,r,t)=>{var p;let n=to.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=s.toggleTextColor||s.headerTextColor||"currentColor",f=ye(n?"chevron-up":"chevron-down",16,d,2);f?c.appendChild(f):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},ia=(e,r)=>{var oe,Ee,ae,we,$e,he,We,Re,ie;let t=e.toolCall,n=(oe=r==null?void 0:r.toolCall)!=null?oe:{},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),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=(ae=(Ee=r==null?void 0:r.features)==null?void 0:Ee.toolCallDisplay)!=null?ae:{},a=o.expandable!==!1,i=a&&to.has(e.id),{summary:u,previewText:c,isActive:p}=ru(e,r),d=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");d.type="button",a&&(d.setAttribute("aria-expanded",i?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(d.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(d.style.paddingLeft=n.headerPaddingX,d.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(d.style.paddingTop=n.headerPaddingY,d.style.paddingBottom=n.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(g.style.color=n.headerTextColor);let x=String((we=t.startedAt)!=null?we:Date.now()),T=()=>{let Z=h("span","");return Z.setAttribute("data-tool-elapsed",x),Z.textContent=Eo(t),Z},C=(he=n.renderCollapsedSummary)==null?void 0:he.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:($e=o.collapsedMode)!=null?$e:"tool-call",isActive:p,config:r!=null?r:{},elapsed:Eo(t),createElapsedElement:T});typeof C=="string"&&C.trim()?(g.textContent=C,f.appendChild(g)):C instanceof HTMLElement?f.appendChild(C):(g.textContent=u,f.appendChild(g));let S=(We=o.loadingAnimation)!=null?We:"none",M=n.activeTextTemplate,H=n.completeTextTemplate,w=p?M:H,L=C instanceof HTMLElement,W=(Z,me,V)=>{let re=V;for(let He of me){let ge=h("span","persona-tool-char");ge.style.setProperty("--char-index",String(re)),ge.textContent=He===" "?"\xA0":He,Z.appendChild(ge),re++}return re},E=(Z,me)=>{var ge;g.textContent="";let V=((ge=t.name)==null?void 0:ge.trim())||"tool",re=cs(Z,V),He=0;for(let Be of re){let st=Be.styles.length>0?(()=>{let z=h("span",Be.styles.map(U=>`persona-tool-text-${U}`).join(" "));return g.appendChild(z),z})():g;if(Be.isDuration&&p)st.appendChild(T());else{let z=Be.isDuration?Eo(t):Be.text;me?He=W(st,z,He):st.appendChild(document.createTextNode(z))}}};if(!L)if(p&&S!=="none"){let Z=(Re=n.loadingAnimationDuration)!=null?Re:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),w&&E(w,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),S==="shimmer-color"&&(n.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),w)E(w,!0);else{let me=g.textContent||u;g.textContent="",W(g,me,0)}}else w&&E(w,!1);let K=null;if(a){K=h("div","persona-flex persona-items-center");let Z=n.toggleTextColor||n.headerTextColor||"currentColor",me=ye(i?"chevron-up":"chevron-down",16,Z,2);me?K.appendChild(me):K.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append(K),d.append(f,V)}else d.append(f);let Q=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(Q.setAttribute("data-persona-collapsed-preview","tool"),Q.style.display="none",Q.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let Z=(ie=n.renderCollapsedPreview)==null?void 0:ie.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:p,config:r!=null?r:{}});tu(Q,Z)||(Q.textContent=c),Q.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(d,Q),s;let X=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(X.style.display=i?"":"none",n.contentBackgroundColor&&(X.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(X.style.color=n.contentTextColor),n.contentPaddingX&&(X.style.paddingLeft=n.contentPaddingX,X.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(X.style.paddingTop=n.contentPaddingY,X.style.paddingBottom=n.contentPaddingY),t.name){let Z=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?Z.style.color=n.contentTextColor:n.headerTextColor&&(Z.style.color=n.headerTextColor),Z.textContent=t.name,X.appendChild(Z)}if(t.args!==void 0){let Z=h("div","persona-space-y-1"),me=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(me.style.color=n.labelTextColor),me.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",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=Jr(t.args),Z.append(me,V),X.appendChild(Z)}if(t.chunks&&t.chunks.length){let Z=h("div","persona-space-y-1"),me=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(me.style.color=n.labelTextColor),me.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",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=t.chunks.join(""),Z.append(me,V),X.appendChild(Z)}if(t.status==="complete"&&t.result!==void 0){let Z=h("div","persona-space-y-1"),me=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(me.style.color=n.labelTextColor),me.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",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=Jr(t.result),Z.append(me,V),X.appendChild(Z)}if(t.status==="complete"&&typeof t.duration=="number"){let Z=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(Z.style.color=n.contentTextColor),Z.textContent=`Duration: ${t.duration}ms`,X.appendChild(Z)}return(()=>{if(d.setAttribute("aria-expanded",i?"true":"false"),K){K.innerHTML="";let Z=n.toggleTextColor||n.headerTextColor||"currentColor",me=ye(i?"chevron-up":"chevron-down",16,Z,2);me?K.appendChild(me):K.textContent=i?"Hide":"Show"}X.style.display=i?"":"none",Q.style.display=i?"none":Q.textContent||Q.childNodes.length?"":"none"})(),s.append(d,Q,X),s};var la=(e,r)=>{var T,C,S,M,H,w,L,W,E,K,Q,X;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.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=(T=n==null?void 0:n.backgroundColor)!=null?T:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=n==null?void 0:n.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 u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=n==null?void 0:n.titleColor)!=null?S:"currentColor",p=ye(u,20,c,2);p&&i.appendChild(p);let d=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(g.style.color=n.titleColor),g.textContent=(M=n==null?void 0:n.title)!=null?M:"Approval Required",f.appendChild(g),!s){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}d.appendChild(f);let x=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(x.style.color=n.descriptionColor),x.textContent=t.description,d.appendChild(x),t.parameters){let O=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");n!=null&&n.parameterBackgroundColor&&(O.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(O.style.color=n.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=Jr(t.parameters),d.appendChild(O)}if(s){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let oe=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");oe.type="button",oe.style.backgroundColor=(H=n==null?void 0:n.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",oe.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",oe.setAttribute("data-approval-action","approve");let Ee=ye("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);Ee&&(Ee.style.marginRight="4px",oe.appendChild(Ee));let ae=document.createTextNode((W=n==null?void 0:n.approveLabel)!=null?W:"Approve");oe.appendChild(ae);let we=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");we.type="button",we.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",we.style.color=(K=n==null?void 0:n.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",we.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,we.setAttribute("data-approval-action","deny");let $e=ye("shield-x",14,(Q=n==null?void 0:n.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",2);$e&&($e.style.marginRight="4px",we.appendChild($e));let he=document.createTextNode((X=n==null?void 0:n.denyLabel)!=null?X:"Deny");we.appendChild(he),O.append(oe,we),d.appendChild(O)}return a.append(i,d),o.appendChild(a),o};var ld=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let p=document.createDocumentFragment(),d=s?s.isStreaming():!1,f=g=>{switch(g){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'}};n.forEach(g=>{let x=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");x.type="button",x.textContent=g,x.disabled=d,i!=null&&i.fontFamily&&(x.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),p.appendChild(x),r.push(x)}),e.appendChild(p)}}};var Oo=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var $o=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function no(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var ou={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)"}},su={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},au=["flowName","stepName","reasoningText","text","name","tool","toolName"],iu=100;function lu(e,r){let t={...ou,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return su}function cu(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function du(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function pu(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.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 uu(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function mu(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function gu(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.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]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function ca(e,r,t,n,s,o,a,i){var f;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");no(c,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(d()),c;function d(){var oe,Ee;let g=h("div",""),x=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");x.setAttribute("data-event-id",e.id);let T=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=ye(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&T.appendChild(C);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(oe=n.timestampFormat)!=null?oe:"relative";S.textContent=M==="relative"?cu(e.timestamp,t):du(e.timestamp);let H=null;n.showSequenceNumbers!==!1&&(H=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(r+1));let w=lu(e.type,n.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=(Ee=n.descriptionFields)!=null?Ee:au,E=pu(e.payload,W),K=null;E&&(K=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),K.textContent=E);let Q=h("div","persona-flex-1 persona-min-w-0"),X=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"),O=ye("clipboard","12px","currentColor",1.5);return O&&X.appendChild(O),X.addEventListener("click",async ae=>{ae.stopPropagation(),await uu(mu(e)),X.innerHTML="";let we=ye("check","12px","currentColor",1.5);we&&X.appendChild(we),setTimeout(()=>{X.innerHTML="";let $e=ye("clipboard","12px","currentColor",1.5);$e&&X.appendChild($e)},1500)}),x.appendChild(T),x.appendChild(S),H&&x.appendChild(H),x.appendChild(L),K&&x.appendChild(K),x.appendChild(Q),x.appendChild(X),g.appendChild(x),u&&g.appendChild(gu(e,a,i)),g}}function cd(e){var g,x,T,C,S;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(g=s==null?void 0:s.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(x=a==null?void 0:a.iconName)!=null?x:"arrow-down",c=(T=a==null?void 0:a.label)!=null?T:"",p=(S=(C=s==null?void 0:s.features)==null?void 0:C.eventStream)!=null?S:{},d=o.find(M=>M.renderEventStreamView);if(d!=null&&d.renderEventStreamView&&s){let M=d.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return f();function f(){let M=p.classNames,H=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");no(H,M==null?void 0:M.panel);let w=[],L="",W="",E=null,K=[],Q={},X=0,O=vs(),oe=0,Ee=0,ae=!1,we=null,$e=!1,he=0,We=new Set,Re=new Map,ie="",Z="",me=null,V,re,He,ge,Be;function st(){let de=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),Te=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");no(Te,M==null?void 0:M.headerBar);let Ve=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ve.textContent="Events",V=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"),V.textContent="0";let vt=h("div","persona-flex-1");re=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 Ot=h("option","");Ot.value="",Ot.textContent="All events",re.appendChild(Ot),He=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"),He.type="button",He.title="Copy All";let $t=ye("clipboard-copy","12px","currentColor",1.5);$t&&He.appendChild($t);let ht=h("span","persona-text-xs");ht.textContent="Copy All",He.appendChild(ht),Te.appendChild(Ve),Te.appendChild(V),Te.appendChild(vt),Te.appendChild(re),Te.appendChild(He);let Qe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");no(Qe,M==null?void 0:M.searchBar);let yt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),je=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&&je.appendChild(yt),ge=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"),no(ge,M==null?void 0:M.searchInput),ge.type="text",ge.placeholder="Search event payloads...",Be=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"),Be.type="button",Be.style.display="none";let _t=ye("x","12px","currentColor",2);return _t&&Be.appendChild(_t),Qe.appendChild(je),Qe.appendChild(ge),Qe.appendChild(Be),de.appendChild(Te),de.appendChild(Qe),de}let z,U=o.find(de=>de.renderEventStreamToolbar);if(U!=null&&U.renderEventStreamToolbar&&s){let de=U.renderEventStreamToolbar({config:s,defaultRenderer:()=>st(),eventCount:r.getSize(),filteredCount:0,onFilterChange:Te=>{L=Te,Jt(),ne()},onSearchChange:Te=>{W=Te,Jt(),ne()}});z=de!=null?de:st()}else z=st();let se=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");se.style.display="none";let N=h("div","persona-flex-1 persona-min-h-0 persona-relative"),J=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ce=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");no(ce,M==null?void 0:M.scrollIndicator),ce.style.display="none",ce.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let fe=ye(u,"14px","currentColor",2);fe&&ce.appendChild(fe);let te=h("span","");te.textContent=c,ce.appendChild(te);let pe=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");pe.style.display="none",N.appendChild(J),N.appendChild(pe),N.appendChild(ce),H.setAttribute("tabindex","0"),H.appendChild(z),H.appendChild(se),H.appendChild(N);function kt(){let de=r.getAll(),Te={};for(let ht of de)Te[ht.type]=(Te[ht.type]||0)+1;let Ve=Object.keys(Te).sort(),vt=Ve.length!==K.length||!Ve.every((ht,Qe)=>ht===K[Qe]),Ot=!vt&&Ve.some(ht=>Te[ht]!==Q[ht]),pt=de.length!==Object.values(Q).reduce((ht,Qe)=>ht+Qe,0);if(!vt&&!Ot&&!pt||(K=Ve,Q=Te,!re))return;let $t=re.value;if(re.options[0].textContent="All events",vt){for(;re.options.length>1;)re.remove(1);for(let ht of Ve){let Qe=h("option","");Qe.value=ht,Qe.textContent=`${ht} (${Te[ht]||0})`,re.appendChild(Qe)}$t&&Ve.includes($t)?re.value=$t:$t&&(re.value="",L="")}else for(let ht=1;ht<re.options.length;ht++){let Qe=re.options[ht];Qe.textContent=`${Qe.value} (${Te[Qe.value]||0})`}}function dt(){let de=r.getAll();if(L&&(de=de.filter(Te=>Te.type===L)),W){let Te=W.toLowerCase();de=de.filter(Ve=>Ve.type.toLowerCase().includes(Te)||Ve.payload.toLowerCase().includes(Te))}return de}function Wt(){return L!==""||W!==""}function Jt(){X=0,oe=0,O.resume(),ce.style.display="none"}function P(de){We.has(de)?We.delete(de):We.add(de),me=de;let Te=J.scrollTop,Ve=O.isFollowing();$e=!0,O.pause(),ne(),J.scrollTop=Te,Ve&&O.resume(),$e=!1}function $(){return Ro(J,50)}function ne(){Ee=Date.now(),ae=!1,kt();let de=r.getEvictedCount();de>0?(se.textContent=`${de.toLocaleString()} older events truncated`,se.style.display=""):se.style.display="none",w=dt();let Te=w.length,Ve=r.getSize()>0;V&&(V.textContent=String(r.getSize())),Te===0&&Ve&&Wt()?(pe.textContent=W?`No events matching '${W}'`:"No events matching filter",pe.style.display="",J.style.display="none"):(pe.style.display="none",J.style.display=""),He&&(He.title=Wt()?`Copy Filtered (${Te})`:"Copy All"),i&&!O.isFollowing()&&Te>X&&(oe+=Te-X,te.textContent=c?`${c}${oe>0?` (${oe})`:""}`:"",ce.style.display=""),X=Te;let vt=r.getAll(),Ot=vt.length>0?vt[0].timestamp:0,pt=new Set(w.map(Qe=>Qe.id));for(let Qe of We)pt.has(Qe)||We.delete(Qe);let $t=L!==ie||W!==Z,ht=Re.size===0&&w.length>0;if($t||ht||w.length===0){J.innerHTML="",Re.clear();let Qe=document.createDocumentFragment();for(let yt=0;yt<w.length;yt++){let je=ca(w[yt],yt,Ot,p,We,P,o,s);Re.set(w[yt].id,je),Qe.appendChild(je)}J.appendChild(Qe),ie=L,Z=W,me=null}else{if(me!==null){let yt=Re.get(me);if(yt&&yt.parentNode===J){let je=w.findIndex(_t=>_t.id===me);if(je>=0){let _t=ca(w[je],je,Ot,p,We,P,o,s);J.insertBefore(_t,yt),yt.remove(),Re.set(me,_t)}}me=null}let Qe=new Set(w.map(yt=>yt.id));for(let[yt,je]of Re)Qe.has(yt)||(je.remove(),Re.delete(yt));for(let yt=0;yt<w.length;yt++){let je=w[yt];if(!Re.has(je.id)){let _t=ca(je,yt,Ot,p,We,P,o,s);Re.set(je.id,_t),J.appendChild(_t)}}}O.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Pe(){if(Date.now()-Ee>=iu){we!==null&&(cancelAnimationFrame(we),we=null),ne();return}ae||(ae=!0,we=requestAnimationFrame(()=>{we=null,ne()}))}let Fe=(de,Te)=>{if(!He)return;He.innerHTML="";let Ve=ye(de,"12px","currentColor",1.5);Ve&&He.appendChild(Ve);let vt=h("span","persona-text-xs");vt.textContent="Copy All",He.appendChild(vt),setTimeout(()=>{He.innerHTML="";let Ot=ye("clipboard-copy","12px","currentColor",1.5);Ot&&He.appendChild(Ot);let pt=h("span","persona-text-xs");pt.textContent="Copy All",He.appendChild(pt),He.disabled=!1},Te)},Ce=async()=>{if(He){He.disabled=!0;try{let de;Wt()?de=w:t?(de=await t(),de.length===0&&(de=r.getAll())):de=r.getAll();let Te=de.map(Ve=>{try{return JSON.parse(Ve.payload)}catch{return Ve.payload}});await navigator.clipboard.writeText(JSON.stringify(Te,null,2)),Fe("check",1500)}catch{Fe("x",1500)}}},be=()=>{re&&(L=re.value,Jt(),ne())},at=()=>{!ge||!Be||(Be.style.display=ge.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{W=ge.value,Jt(),ne()},150))},mt=()=>{!ge||!Be||(ge.value="",W="",Be.style.display="none",E&&clearTimeout(E),Jt(),ne())},At=()=>{if($e)return;let de=J.scrollTop,{action:Te,nextLastScrollTop:Ve}=Cs({following:O.isFollowing(),currentScrollTop:de,lastScrollTop:he,nearBottom:$(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=Ve,Te==="resume"?(O.resume(),oe=0,ce.style.display="none"):Te==="pause"&&(O.pause(),i&&(te.textContent=c,ce.style.display=""))},j=de=>{let Te=ws({following:O.isFollowing(),deltaY:de.deltaY,nearBottom:$(),resumeWhenNearBottom:!0});Te==="pause"?(O.pause(),i&&(te.textContent=c,ce.style.display="")):Te==="resume"&&(O.resume(),oe=0,ce.style.display="none")},xe=()=>{i&&(J.scrollTop=J.scrollHeight,O.resume(),oe=0,ce.style.display="none")},ue=de=>{let Te=de.target;if(!Te||Te.closest("button"))return;let Ve=Te.closest("[data-event-id]");if(!Ve)return;let vt=Ve.getAttribute("data-event-id");vt&&P(vt)},Ze=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),ge==null||ge.focus(),ge==null||ge.select();return}de.key==="Escape"&&(ge&&document.activeElement===ge?(mt(),ge.blur(),H.focus()):n&&n())};He&&He.addEventListener("click",Ce),re&&re.addEventListener("change",be),ge&&ge.addEventListener("input",at),Be&&Be.addEventListener("click",mt),J.addEventListener("scroll",At),J.addEventListener("wheel",j,{passive:!0}),J.addEventListener("click",ue),ce.addEventListener("click",xe),H.addEventListener("keydown",Ze);function qe(){E&&clearTimeout(E),we!==null&&(cancelAnimationFrame(we),we=null),ae=!1,Re.clear(),He&&He.removeEventListener("click",Ce),re&&re.removeEventListener("change",be),ge&&ge.removeEventListener("input",at),Be&&Be.removeEventListener("click",mt),J.removeEventListener("scroll",At),J.removeEventListener("wheel",j),J.removeEventListener("click",ue),ce.removeEventListener("click",xe),H.removeEventListener("keydown",Ze)}return{element:H,update:Pe,destroy:qe}}}function dd(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=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`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 c=document.createElement("div");c.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 d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",d.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(g)}else d.textContent=a;if(c.append(p,d),i.append(u,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",n),i.append(f)}return i}var pd=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.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:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>dd(e,r)});if(p)return p}return dd(e,r)};var da=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},xr=new da;xr.register("PersonaArtifactCard",pd);function fu(e){var s;let r=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 n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function ud(e,r){var He,ge,Be,st;let t=(ge=(He=e.features)==null?void 0:He.artifacts)==null?void 0:ge.layout,s=((Be=t==null?void 0:t.toolbarPreset)!=null?Be:"default")==="document",o=(st=t==null?void 0:t.panePadding)==null?void 0:st.trim(),a=e.markdown?Vr(e.markdown):null,i=So(e.sanitize),u=z=>{let U=a?a(z):wo(z);return i?i(U):U},c=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=()=>{c==null||c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var z;p(),(z=r.onDismiss)==null||z.call(r)});let d=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");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let g=h("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var z;p(),(z=r.onDismiss)==null||z.call(r)});let T="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?Pt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Pt({icon:"eye",label:"Rendered view"}),M=s?Pt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Pt({icon:"code-2",label:"Source"}),H=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,E=!!(L&&W&&W.length>0),K=null,Q,X=null,O=null;if(s&&(w||L)&&!E){if(Q=w?As({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let z=ye("chevron-down",14,"currentColor",2);z&&Q.appendChild(z)}}else s&&E?(K=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=w?As({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),X=Pt({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"}}),K.append(Q,X)):s?Q=Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):Q=Pt({icon:"copy",label:"Copy"});let oe=s?Pt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"refresh-cw",label:"Refresh"}),Ee=s?Pt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"x",label:"Close"}),ae=()=>{var J,ce,fe;let z=(J=ie.find(te=>te.id===Z))!=null?J:ie[ie.length-1],U=(ce=z==null?void 0:z.id)!=null?ce:null,se=(z==null?void 0:z.artifactType)==="markdown"&&(fe=z.markdown)!=null?fe:"",N=z?JSON.stringify({component:z.component,props:z.props},null,2):"";return{markdown:se,jsonPayload:N,id:U}},we=async()=>{var J;let{markdown:z,jsonPayload:U}=ae(),se=(J=ie.find(ce=>ce.id===Z))!=null?J:ie[ie.length-1],N=(se==null?void 0:se.artifactType)==="markdown"?z:se?U:"";try{await navigator.clipboard.writeText(N)}catch{}};if(Q.addEventListener("click",async()=>{let z=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(z&&E){let{markdown:U,jsonPayload:se,id:N}=ae();try{await z({actionId:"primary",artifactId:N,markdown:U,jsonPayload:se})}catch{}return}await we()}),X&&(W!=null&&W.length)){let z=()=>{var se;return(se=d.closest("[data-persona-root]"))!=null?se:document.body},U=()=>{O=Nr({items:W.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:N,jsonPayload:J,id:ce}=ae(),fe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{fe?await fe({actionId:se,artifactId:ce,markdown:N,jsonPayload:J}):se==="markdown"||se==="md"?await navigator.clipboard.writeText(N):se==="json"||se==="source"?await navigator.clipboard.writeText(J):await navigator.clipboard.writeText(N||J)}catch{}},anchor:K!=null?K:X,position:"bottom-right",portal:z()})};d.isConnected?U():requestAnimationFrame(U),X.addEventListener("click",se=>{se.stopPropagation(),O==null||O.toggle()})}oe.addEventListener("click",async()=>{var z;try{await((z=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:z.call(t))}catch{}V()}),Ee.addEventListener("click",()=>{var z;p(),(z=r.onDismiss)==null||z.call(r)});let $e=()=>{s&&(S.setAttribute("aria-pressed",T==="rendered"?"true":"false"),M.setAttribute("aria-pressed",T==="source"?"true":"false"))};S.addEventListener("click",()=>{T="rendered",$e(),V()}),M.addEventListener("click",()=>{T="source",$e(),V()});let he=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),C.append(S,M),K?H.append(K,oe,Ee):H.append(Q,oe,Ee),f.append(C,he,H),$e()):(f.appendChild(g),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let We=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"),Re=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(We.style.paddingLeft=o,We.style.paddingRight=o,Re.style.padding=o),d.appendChild(f),d.appendChild(We),d.appendChild(Re);let ie=[],Z=null,me=!1,V=()=>{var N,J,ce,fe;let z=s&&ie.length<=1;We.classList.toggle("persona-hidden",z),We.replaceChildren();for(let te of ie){let pe=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");pe.type="button",pe.textContent=te.title||te.id.slice(0,8),te.id===Z&&pe.classList.add("persona-bg-persona-container","persona-border-persona-border"),pe.addEventListener("click",()=>r.onSelect(te.id)),We.appendChild(pe)}Re.replaceChildren();let U=Z&&ie.find(te=>te.id===Z)||ie[ie.length-1];if(!U)return;if(s){let te=U.artifactType==="markdown"?"MD":(N=U.component)!=null?N:"Component",kt=(U.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${kt} \xB7 ${te}`}else g.textContent="Artifacts";if(U.artifactType==="markdown"){if(s&&T==="source"){let pe=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");pe.textContent=(J=U.markdown)!=null?J:"",Re.appendChild(pe);return}let te=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");te.innerHTML=u((ce=U.markdown)!=null?ce:""),Re.appendChild(te);return}let se=U.component?xr.get(U.component):void 0;if(se){let pe={message:{id:U.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let kt=se((fe=U.props)!=null?fe:{},pe);if(kt){Re.appendChild(kt);return}}catch{}}Re.appendChild(fu(U))},re=()=>{var U;let z=ie.length>0;if(d.classList.toggle("persona-hidden",!z),c){let se=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,J=((U=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?U:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;z&&J&&me?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(z){var U,se,N;ie=z.artifacts,Z=(N=(se=z.selectedId)!=null?se:(U=z.artifacts[z.artifacts.length-1])==null?void 0:U.id)!=null?N:null,ie.length>0&&(me=!0),V(),re()},setMobileOpen(z){me=z,!z&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):re()}}}function Pn(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function md(e,r){var o,a,i,u;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"),!Pn(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function hu(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 Ts(e,r){var u,c,p,d,f,g,x,T,C,S;if(!Pn(r)){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"),hu(e),md(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.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",(d=t==null?void 0:t.paneWidth)!=null?d:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=t==null?void 0:t.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(T=t==null?void 0:t.documentToolbarIconColor)==null?void 0:T.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=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),md(e,r)}var gd=["panel","seamless"];function Ms(e,r){var i,u,c,p,d,f;for(let g of gd)e.classList.remove(`persona-artifact-appearance-${g}`);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"),!Pn(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=gd.includes(n)?n:"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=(d=t==null?void 0:t.paneShadow)==null?void 0:d.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 g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function fd(e,r){var t,n,s;return!r||!Pn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function yu(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function bu(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function xu(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function vu(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function hd(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function yd(e,r,t,n,s,o){let a=yu(s,200),i=vu(r,t,n,200);i=Math.max(a,i);let u=bu(o);return u!==null&&(i=Math.min(i,u)),xu(e,a,i)}var bd={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"}},pa=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,T,C;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(T=bd[a])!=null?T:bd.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,u.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var W,E;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${S.name}`;let H=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=S.label,M.appendChild(H);let w=(W=S.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=`${r.id}-${a}-${S.name}`,L.name=S.name,L.placeholder=(E=S.placeholder)!=null?E:"",S.required&&(L.required=!0),M.appendChild(L),p.appendChild(M)});let d=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=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");g.type="submit",g.textContent=(C=i.submitLabel)!=null?C:"Submit",d.appendChild(f),d.appendChild(g),p.appendChild(d),o.replaceChildren(u,p),p.addEventListener("submit",async S=>{var L,W;S.preventDefault();let M=(L=t.formEndpoint)!=null?L:"/form",H=new FormData(p),w={};H.forEach((E,K)=>{w[K]=E}),w.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let E=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let K=await E.json();f.textContent=(W=K.message)!=null?W:"Thanks! We'll be in touch soon.",K.success&&K.nextPrompt&&await n.sendMessage(String(K.nextPrompt))}catch(E){f.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var ua=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},ks=new ua;var xd=()=>{let e=new Map,r=(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:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Cu=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},wu=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},Ls=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Cu(e),t=wu(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},ma=e=>typeof e=="string"?e:e==null?"":String(e),ro={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ma(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ma(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:ma(t.text)}}},vd=e=>Array.isArray(e)?e.map(r=>String(r)):[],Is=e=>{let r=new Set(vd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(vd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.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((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",u)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var Su=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Au=e=>e.map(r=>({...r,streaming:!1})),ga=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Su(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Au(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};import{parse as Eu,STR as Tu,OBJ as Mu}from"partial-json";function ku(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Lu(e,r){if(!ku(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function fa(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=Eu(t,Tu|Mu),o=Lu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Iu(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ha(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=xr.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:n,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 Pu(){let e=fa();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ya(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function ba(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var Wu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function xa(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=Wu}=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 d=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,g.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,g.appendChild(T),f.appendChild(g);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 S=[];for(let W=1;W<=5;W++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${c[W-1]}`),E.title=c[W-1],E.dataset.rating=String(W),E.innerHTML=`
|
|
15
|
+
`,t.addEventListener("click",r);let n=o=>{var $,v,T,B,E,K,Q,G,j,re,Te,oe,Ce,Ne;let a=($=o.launcher)!=null?$:{},i=Yt(o),u=t.querySelector("[data-role='launcher-title']");if(u){let he=(v=a.title)!=null?v:"Chat Assistant";u.textContent=he,u.setAttribute("title",he)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let he=(T=a.subtitle)!=null?T:"Get answers fast";c.textContent=he,c.setAttribute("title",he)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let he=(B=a.agentIconSize)!=null?B:"40px";if(d.style.height=he,d.style.width=he,d.innerHTML="",a.agentIconName){let ke=parseFloat(he)||24,Be=fe(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);Be?(d.appendChild(Be),d.style.display=""):(d.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(K=a.agentIconText)!=null?K:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let he=(Q=a.agentIconSize)!=null?Q:"40px";f.style.height=he,f.style.width=he,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let he=(G=a.callToActionIconSize)!=null?G:"32px";g.style.height=he,g.style.width=he,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let ke=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,ke=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Be=parseFloat(he)||24,ue=Math.max(Be-ke,8),Y=fe(a.callToActionIconName,ue,"currentColor",2);Y?g.appendChild(Y):g.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else g.textContent=(re=a.callToActionIconText)!=null?re:"\u2197"}let x=a.position&&zn[a.position]?zn[a.position]:zn["bottom-right"],M="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",w="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?w:`${M} ${x}`,i||(t.style.zIndex=String((Te=a.zIndex)!=null?Te:hn));let S="1px solid var(--persona-border, #e5e7eb)",k="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=(oe=a.border)!=null?oe:S,t.style.boxShadow=(Ce=a.shadow)!=null?Ce:k,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",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var yn={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))"},Sr=e=>{var G,j,re,Te,oe,Ce,Ne,he,ke,Be,ue,Y,ye,de,we,Me,ae,Le,Ie,P,q,ie,F,U,me,Je,ee,le,Pt,mt,ze,Xt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(G=r==null?void 0:r.launcher)!=null?G:{},o=(j=s.headerIconSize)!=null?j:"48px",a=(re=s.closeButtonSize)!=null?re:"32px",i=(Te=s.closeButtonPlacement)!=null?Te:"inline",u=(oe=s.headerIconHidden)!=null?oe:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let Xe=parseFloat(o)||24,ge=fe(c,Xe*.6,"currentColor",1);ge?p.replaceChildren(ge):p.textContent=(Ne=(Ce=r==null?void 0:r.launcher)==null?void 0:Ce.agentIconText)!=null?Ne:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let Xe=h("img");Xe.src=r.launcher.iconUrl,Xe.alt="",Xe.className="persona-rounded-xl persona-object-cover",Xe.style.height=o,Xe.style.width=o,p.replaceChildren(Xe)}else p.textContent=(Be=(ke=r==null?void 0:r.launcher)==null?void 0:ke.agentIconText)!=null?Be:"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=yn.titleColor,f.textContent=(Y=(ue=r==null?void 0:r.launcher)==null?void 0:ue.title)!=null?Y:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=yn.subtitleColor,g.textContent=(de=(ye=r==null?void 0:r.launcher)==null?void 0:ye.subtitle)!=null?de:"Here to help you get answers fast",d.append(f,g),u?n.append(d):n.append(p,d);let x=(we=s.clearChat)!=null?we:{},M=(Me=x.enabled)!=null?Me:!0,w=(ae=x.placement)!=null?ae:"inline",S=null,k=null;if(M){let Xe=(Le=x.size)!=null?Le:"32px",ge=(Ie=x.iconName)!=null?Ie:"refresh-cw",Ge=(P=x.iconColor)!=null?P:"",Wt=(q=x.backgroundColor)!=null?q:"",Rt=(ie=x.borderWidth)!=null?ie:"",W=(F=x.borderColor)!=null?F:"",X=(U=x.borderRadius)!=null?U:"",Se=(me=x.paddingX)!=null?me:"",Fe=(Je=x.paddingY)!=null?Je:"",Ve=(ee=x.tooltipText)!=null?ee:"Clear chat",I=(le=x.showTooltip)!=null?le:!0;k=h("div",w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),w==="top-right"&&(k.style.right="48px"),S=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"),S.style.height=Xe,S.style.width=Xe,S.type="button",S.setAttribute("aria-label",Ve),S.style.color=Ge||yn.actionIconColor;let te=fe(ge,"20px","currentColor",1);if(te&&(te.style.display="block",S.appendChild(te)),Wt&&(S.style.backgroundColor=Wt,S.classList.remove("hover:persona-bg-gray-100")),Rt||W){let Z=Rt||"0px",Ye=W||"transparent";S.style.border=`${Z} solid ${Ye}`,S.classList.remove("persona-border-none")}if(X&&(S.style.borderRadius=X,S.classList.remove("persona-rounded-full")),Se?(S.style.paddingLeft=Se,S.style.paddingRight=Se):(S.style.paddingLeft="",S.style.paddingRight=""),Fe?(S.style.paddingTop=Fe,S.style.paddingBottom=Fe):(S.style.paddingTop="",S.style.paddingBottom=""),k.appendChild(S),I&&Ve&&S&&k){let Z=null,Ye=()=>{if(Z||!S)return;let ne=S.ownerDocument,pe=ne.body;if(!pe)return;Z=Kn(ne,"div","persona-clear-chat-tooltip"),Z.textContent=Ve;let He=Kn(ne,"div");He.className="persona-clear-chat-tooltip-arrow",Z.appendChild(He);let at=S.getBoundingClientRect();Z.style.position="fixed",Z.style.zIndex=String(Cr),Z.style.left=`${at.left+at.width/2}px`,Z.style.top=`${at.top-8}px`,Z.style.transform="translate(-50%, -100%)",pe.appendChild(Z)},Pe=()=>{Z&&Z.parentNode&&(Z.parentNode.removeChild(Z),Z=null)};k.addEventListener("mouseenter",Ye),k.addEventListener("mouseleave",Pe),S.addEventListener("focus",Ye),S.addEventListener("blur",Pe),k._cleanupTooltip=()=>{Pe(),k&&(k.removeEventListener("mouseenter",Ye),k.removeEventListener("mouseleave",Pe)),S&&(S.removeEventListener("focus",Ye),S.removeEventListener("blur",Pe))}}w==="inline"&&n.appendChild(k)}let $=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&w==="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"),v=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");v.style.height=a,v.style.width=a,v.type="button";let T=(Pt=s.closeButtonTooltipText)!=null?Pt:"Close chat",B=(mt=s.closeButtonShowTooltip)!=null?mt:!0;v.setAttribute("aria-label",T),v.style.display=t?"":"none";let E=(ze=s.closeButtonIconName)!=null?ze:"x",K=(Xt=s.closeButtonIconText)!=null?Xt:"\xD7";v.style.color=s.closeButtonColor||yn.actionIconColor;let Q=fe(E,"28px","currentColor",1);if(Q?(Q.style.display="block",v.appendChild(Q)):v.textContent=K,s.closeButtonBackgroundColor?(v.style.backgroundColor=s.closeButtonBackgroundColor,v.classList.remove("hover:persona-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Xe=s.closeButtonBorderWidth||"0px",ge=s.closeButtonBorderColor||"transparent";v.style.border=`${Xe} solid ${ge}`,v.classList.remove("persona-border-none")}else v.style.border="",v.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(v.style.borderRadius=s.closeButtonBorderRadius,v.classList.remove("persona-rounded-full")):(v.style.borderRadius="",v.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(v.style.paddingLeft=s.closeButtonPaddingX,v.style.paddingRight=s.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),s.closeButtonPaddingY?(v.style.paddingTop=s.closeButtonPaddingY,v.style.paddingBottom=s.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),$.appendChild(v),B&&T){let Xe=null,ge=()=>{if(Xe)return;let Wt=v.ownerDocument,Rt=Wt.body;if(!Rt)return;Xe=Kn(Wt,"div","persona-clear-chat-tooltip"),Xe.textContent=T;let W=Kn(Wt,"div");W.className="persona-clear-chat-tooltip-arrow",Xe.appendChild(W);let X=v.getBoundingClientRect();Xe.style.position="fixed",Xe.style.zIndex=String(Cr),Xe.style.left=`${X.left+X.width/2}px`,Xe.style.top=`${X.top-8}px`,Xe.style.transform="translate(-50%, -100%)",Rt.appendChild(Xe)},Ge=()=>{Xe&&Xe.parentNode&&(Xe.parentNode.removeChild(Xe),Xe=null)};$.addEventListener("mouseenter",ge),$.addEventListener("mouseleave",Ge),v.addEventListener("focus",ge),v.addEventListener("blur",Ge),$._cleanupTooltip=()=>{Ge(),$.removeEventListener("mouseenter",ge),$.removeEventListener("mouseleave",Ge),v.removeEventListener("focus",ge),v.removeEventListener("blur",Ge)}}return i!=="top-right"&&n.appendChild($),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:g,closeButton:v,closeButtonWrapper:$,clearChatButton:S,clearChatButtonWrapper:k}},oo=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function zr(e){let{items:r,onSelect:t,anchor:n,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(Cr)):(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 g of r){if(g.dividerBefore){let w=document.createElement("hr");a.appendChild(w)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let w=fe(g.icon,16,"currentColor",1.5);w&&x.appendChild(w)}let M=document.createElement("span");M.textContent=g.label,x.appendChild(M),x.addEventListener("click",w=>{w.stopPropagation(),p(),t(g.id)}),a.appendChild(x)}let i=null;function u(){if(!o)return;let g=n.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!n.contains(x.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function d(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:d,destroy:f}}function Nt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=fe(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[p,d]of Object.entries(i))u.setAttribute(p,d);return u}function Ns(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=fe(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let d=h("span");if(d.textContent=t,p.appendChild(d),i&&p.addEventListener("click",i),u)for(let[f,g]of Object.entries(u))p.setAttribute(f,g);return p}function Fs(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let d;p.icon?d=Nt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,u(),n(p.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",p.label),d.title=p.label,d.textContent=p.label,d.addEventListener("click",()=>{a=p.id,u(),n(p.id)})),d.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:d}),o.appendChild(d)}function c(p){a=p,u()}return{element:o,setSelected:c}}function ba(e){var g,x;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let d=fe(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),u&&(c.style.borderRadius=(g=u.borderRadius)!=null?g:"10px",c.style.padding=(x=u.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var M,w;c.style.backgroundColor=(M=u.background)!=null?M:"",c.style.borderColor=(w=u.border)!=null?w:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=zr({items:n,onSelect:M=>{c.setAttribute("aria-expanded","false"),s(M)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",M=>{M.stopPropagation();let w=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",w?"false":"true"),f.toggle()}),c.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c.click())}),{element:c,setLabel:M=>{p.textContent=M,c.setAttribute("aria-label",M)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Qc=e=>{var n;let r=Sr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.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 r};function Up(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){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=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=fe(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=zr({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var ed=e=>{var k,$,v,T,B,E,K,Q,G;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(k=r==null?void 0:r.launcher)!=null?k:{},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 u=s==null?void 0:s.titleMenu,c,p;if(u)c=ba({label:($=a.title)!=null?$:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=yn.titleColor,p=(v=c.querySelector(".persona-combo-btn-label"))!=null?v:c;else{if(c=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=yn.titleColor,p.textContent=(T=a.title)!=null?T:"Chat Assistant",c.appendChild(p),Up(c,s==null?void 0:s.trailingActions,(B=s==null?void 0:s.onAction)!=null?B:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let re=s.onTitleClick;c.addEventListener("click",Te=>{Te.target.closest("button")||re()}),c.addEventListener("keydown",Te=>{(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),re())})}let j=s==null?void 0:s.titleRowHover;j&&(c.style.borderRadius=(E=j.borderRadius)!=null?E:"10px",c.style.padding=(K=j.padding)!=null?K:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var re,Te;c.style.backgroundColor=(re=j.background)!=null?re:"",c.style.borderColor=(Te=j.border)!=null?Te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(Q=a.closeButtonSize)!=null?Q:"32px",f=h("div",""),g=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");g.style.height=d,g.style.width=d,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||yn.actionIconColor;let x=(G=a.closeButtonIconName)!=null?G:"x",M=fe(x,"28px","currentColor",1);M?g.appendChild(M):g.textContent="\xD7",n&&g.addEventListener("click",n),f.appendChild(g),i.appendChild(f);let w=h("div");w.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:w,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},xa={default:Qc,minimal:ed},td=e=>{var r;return(r=xa[e])!=null?r:xa.default},Go=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),p=h("div");p.style.display="none";let d=h("span"),f=h("span"),g=h("button");g.style.display="none";let x=h("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:d,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=td(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Ko=e=>{var ae,Le,Ie,P,q,ie,F,U,me,Je,ee,le,Pt,mt,ze,Xt,Xe,ge,Ge,Wt,Rt,W,X,Se,Fe,Ve,I;let{config:r}=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 n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),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 o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(Le=(ae=r==null?void 0:r.copy)==null?void 0:ae.inputPlaceholder)!=null?Le:"Type your message\u2026",o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let te=Math.min(o.scrollHeight,u);o.style.height=`${te}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(Ie=r==null?void 0:r.sendButton)!=null?Ie:{},d=(P=p.useIcon)!=null?P:!1,f=(q=p.iconText)!=null?q:"\u2191",g=p.iconName,x=(ie=p.tooltipText)!=null?ie:"Send message",M=(F=p.showTooltip)!=null?F:!1,w=(U=p.size)!=null?U:"40px",S=p.backgroundColor,k=p.textColor,$=h("div","persona-send-button-wrapper"),v=h("button",d?"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");if(v.type="submit",v.setAttribute("data-persona-composer-submit",""),d){if(v.style.width=w,v.style.height=w,v.style.minWidth=w,v.style.minHeight=w,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",k?v.style.color=k:v.style.color="var(--persona-button-primary-fg, #ffffff)",g){let te=parseFloat(w)||24,Z=(k==null?void 0:k.trim())||"currentColor",Ye=fe(g,te,Z,2);Ye?v.appendChild(Ye):v.textContent=f}else v.textContent=f;S?v.style.backgroundColor=S:v.classList.add("persona-bg-persona-primary")}else v.textContent=(Je=(me=r==null?void 0:r.copy)==null?void 0:me.sendButtonLabel)!=null?Je:"Send",k?v.style.color=k:v.classList.add("persona-text-white");if(p.borderWidth&&(v.style.borderWidth=p.borderWidth,v.style.borderStyle="solid"),p.borderColor&&(v.style.borderColor=p.borderColor),p.paddingX?(v.style.paddingLeft=p.paddingX,v.style.paddingRight=p.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),p.paddingY?(v.style.paddingTop=p.paddingY,v.style.paddingBottom=p.paddingY):(v.style.paddingTop="",v.style.paddingBottom=""),M&&x){let te=h("div","persona-send-button-tooltip");te.textContent=x,$.appendChild(te)}$.appendChild(v);let T=(ee=r==null?void 0:r.voiceRecognition)!=null?ee:{},B=T.enabled===!0,E=null,K=null,Q=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),G=((le=T.provider)==null?void 0:le.type)==="runtype";if(B&&(Q||G)){K=h("div","persona-send-button-wrapper"),E=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),E.type="button",E.setAttribute("data-persona-composer-mic",""),E.setAttribute("aria-label","Start voice recognition");let te=(Pt=T.iconName)!=null?Pt:"mic",Z=(mt=T.iconSize)!=null?mt:w,Ye=parseFloat(Z)||24,Pe=(ze=T.backgroundColor)!=null?ze:S,ne=(Xt=T.iconColor)!=null?Xt:k;E.style.width=Z,E.style.height=Z,E.style.minWidth=Z,E.style.minHeight=Z,E.style.fontSize="18px",E.style.lineHeight="1",ne?E.style.color=ne:E.style.color="var(--persona-text, #111827)";let He=fe(te,Ye,ne||"currentColor",1.5);He?E.appendChild(He):E.textContent="\u{1F3A4}",Pe&&(E.style.backgroundColor=Pe),T.borderWidth&&(E.style.borderWidth=T.borderWidth,E.style.borderStyle="solid"),T.borderColor&&(E.style.borderColor=T.borderColor),T.paddingX&&(E.style.paddingLeft=T.paddingX,E.style.paddingRight=T.paddingX),T.paddingY&&(E.style.paddingTop=T.paddingY,E.style.paddingBottom=T.paddingY),K.appendChild(E);let at=(Xe=T.tooltipText)!=null?Xe:"Start voice recognition";if(((ge=T.showTooltip)!=null?ge:!1)&&at){let ft=h("div","persona-send-button-tooltip");ft.textContent=at,K.appendChild(ft)}}let re=(Ge=r==null?void 0:r.attachments)!=null?Ge:{},Te=re.enabled===!0,oe=null,Ce=null,Ne=null,he=null;if(Te){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",Ne=h("input"),Ne.type="file",Ne.accept=((Wt=re.allowedTypes)!=null?Wt:ir).join(","),Ne.multiple=((Rt=re.maxFiles)!=null?Rt:4)>1,Ne.style.display="none",Ne.setAttribute("aria-label","Attach files"),Ce=h("div","persona-send-button-wrapper"),oe=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),oe.type="button",oe.setAttribute("aria-label",(W=re.buttonTooltipText)!=null?W:"Attach file");let te=(X=re.buttonIconName)!=null?X:"paperclip",Z=w,Ye=parseFloat(Z)||40,Pe=Math.round(Ye*.6);oe.style.width=Z,oe.style.height=Z,oe.style.minWidth=Z,oe.style.minHeight=Z,oe.style.fontSize="18px",oe.style.lineHeight="1",oe.style.backgroundColor="transparent",oe.style.color="var(--persona-primary, #111827)",oe.style.border="none",oe.style.borderRadius="6px",oe.style.transition="background-color 0.15s ease",oe.addEventListener("mouseenter",()=>{oe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),oe.addEventListener("mouseleave",()=>{oe.style.backgroundColor="transparent"});let ne=fe(te,Pe,"currentColor",1.5);ne?oe.appendChild(ne):oe.textContent="\u{1F4CE}",oe.addEventListener("click",at=>{at.preventDefault(),Ne==null||Ne.click()}),Ce.appendChild(oe);let pe=(Se=re.buttonTooltipText)!=null?Se:"Attach file",He=h("div","persona-send-button-tooltip");He.textContent=pe,Ce.appendChild(He)}s.addEventListener("click",te=>{te.target!==v&&te.target!==$&&te.target!==E&&te.target!==K&&te.target!==oe&&te.target!==Ce&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),Ne&&s.append(Ne),s.append(o);let ke=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Be=h("div","persona-flex persona-items-center persona-gap-2");Ce&&Be.append(Ce);let ue=h("div","persona-flex persona-items-center persona-gap-1");K&&ue.append(K),ue.append($),ke.append(Be,ue),s.append(ke);let Y=(Fe=r==null?void 0:r.statusIndicator)!=null?Fe:{},ye=Y.align==="left"?"persona-text-left":Y.align==="center"?"persona-text-center":"persona-text-right",de=h("div",`persona-mt-2 ${ye} persona-text-xs persona-text-persona-muted`);de.setAttribute("data-persona-composer-status","");let we=(Ve=Y.visible)!=null?Ve:!0;de.style.display=we?"":"none";let Me=(I=Y.idleText)!=null?I:"Online";if(Y.idleLink){let te=h("a");te.href=Y.idleLink,te.target="_blank",te.rel="noopener noreferrer",te.textContent=Me,te.style.color="inherit",te.style.textDecoration="none",de.appendChild(te)}else de.textContent=Me;return t.append(n,s,de),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:v,sendButtonWrapper:$,micButton:E,micButtonWrapper:K,statusText:de,attachmentButton:oe,attachmentButtonWrapper:Ce,attachmentInput:Ne,attachmentPreviewsContainer:he,actionsRow:ke,leftActions:Be,rightActions:ue}};var nd=e=>{var c,p,d,f,g,x,M,w,S;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Yt(e)){let k=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),$=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return k.appendChild($),{wrapper:k,panel:$}}if(!r){let k=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),v=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return k.style.width=v,$.style.width="100%",k.appendChild($),{wrapper:k,panel:$}}let n=(g=e==null?void 0:e.launcher)!=null?g:{},s=n.position&&zn[n.position]?zn[n.position]:zn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((M=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?M:hn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(S=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?S:e==null?void 0:e.launcherWidth,u=i!=null?i:Pn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},rd=(e,r=!0)=>{var w,S,k,$,v,T,B,E,K;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-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(w=e==null?void 0:e.layout)==null?void 0:w.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=n?Go(e,n,{showClose:r}):Sr({config:e,showClose:r}),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=Yt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=($=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?$:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(T=(v=e==null?void 0:e.copy)==null?void 0:v.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",u.append(c,p);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,d);let x=Ko({config:e}),M=((K=e==null?void 0:e.layout)==null?void 0:K.showFooter)!==!1;return s?oo(t,o,e):(o.header.style.display="none",oo(t,o,e)),t.append(a),M||(x.footer.style.display="none"),t.append(x.footer),{container:t,body:a,messagesWrapper:d,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,introTitle:c,introSubtitle:p,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:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions}};var Vp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Jp=320,Gp=320,Kp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Yp=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Jp}px`,c.style.maxHeight=`${Gp}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),Vp(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},so=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="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 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="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},sd=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:so};if(r){let s=r(n);if(s!==null)return s}return so()},Xp=(e,r)=>{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"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},od=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Zp=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){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},ad=(e,r,t)=>{var g,x,M,w,S,k;let n=(g=r.showCopy)!=null?g:!0,s=(x=r.showUpvote)!=null?x:!0,o=(M=r.showDownvote)!=null?M:!0;if(!n&&!s&&!o){let $=h("div");return $.style.display="none",$.id=`actions-${e.id}`,$.setAttribute("data-actions-for",e.id),$}let a=(w=r.visibility)!=null?w:"hover",i=(S=r.align)!=null?S:"right",u=(k=r.layout)!=null?k:"pill-inside",c={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"}[u],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=($,v,T)=>{let B=Nt({icon:$,label:v,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",T),B};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},Yo=(e,r,t,n,s,o)=>{var G,j,re,Te,oe,Ce,Ne;let a=t!=null?t:{},i=(G=a.layout)!=null?G:"bubble",u=a.avatar,c=a.timestamp,p=(j=u==null?void 0:u.show)!=null?j:!1,d=(re=c==null?void 0:c.show)!=null?re:!1,f=(Te=u==null?void 0:u.position)!=null?Te:"left",g=(oe=c==null?void 0:c.position)!=null?oe:"below",x=Zp(e.role,i),M=h("div",x.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let w=Kp(e),S=(Ne=(Ce=e.content)==null?void 0:Ce.trim())!=null?Ne:"",$=w.length>0&&S===As,v=document.createElement("div");v.classList.add("persona-message-content");let T=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),B=null;if($?(B=document.createElement("div"),B.innerHTML=T,B.style.display="none",v.appendChild(B)):v.innerHTML=T,d&&g==="inline"&&e.createdAt){let he=od(e,c);he.classList.add("persona-ml-2","persona-inline"),v.appendChild(he)}if(w.length>0){let he=Yp(w,!$&&!!S,()=>{$&&B&&(B.style.display="")});he?M.appendChild(he):$&&B&&(B.style.display="")}if(M.appendChild(v),d&&g==="below"&&e.createdAt){let he=od(e,c);he.classList.add("persona-mt-1"),M.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=sd("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&M.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=ad(e,n,s);M.appendChild(he)}if(!p||e.role==="system")return M;let K=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Q=Xp(u,e.role);return f==="right"||f==="left"&&e.role==="user"?K.append(M,Q):K.append(Q,M),M.classList.remove("persona-max-w-[85%]"),M.classList.add("persona-max-w-[calc(85%-2.5rem)]"),K},Qp=(e,r,t,n,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}):Yo(e,r,t,n,s,o)};var ao=new Set,eu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),tu=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
|
|
16
|
+
`):""},id=(e,r)=>{let t=ao.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),o=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=fe(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},va=(e,r)=>{var Ce,Ne,he,ke,Be,ue,Y,ye,de,we,Me;let t=e.reasoning,n=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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let s=(Ne=(Ce=r==null?void 0:r.features)==null?void 0:Ce.reasoningDisplay)!=null?Ne:{},o=s.expandable!==!1,a=o&&ao.has(e.id),i=t.status!=="complete",u=tu(e,(he=s.previewMaxLines)!=null?he:3),c=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");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(ke=r==null?void 0:r.reasoning)!=null?ke:{},x=String((Be=t.startedAt)!=null?Be:Date.now()),M=()=>{let ae=h("span","");return ae.setAttribute("data-tool-elapsed",x),ae.textContent=Cs(t),ae},w=(ue=g.renderCollapsedSummary)==null?void 0:ue.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:u,isActive:i,config:r!=null?r:{},elapsed:Cs(t),createElapsedElement:M});typeof w=="string"&&w.trim()?(d.textContent=w,p.appendChild(d)):w instanceof HTMLElement?p.appendChild(w):(d.textContent=f,p.appendChild(d));let S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=Pc(t),p.appendChild(S);let k=(Y=s.loadingAnimation)!=null?Y:"none",$=g.activeTextTemplate,v=g.completeTextTemplate,T=i?$:v,B=w instanceof HTMLElement,E=(ae,Le,Ie)=>{let P=Ie;for(let q of Le){let ie=h("span","persona-tool-char");ie.style.setProperty("--char-index",String(P)),ie.textContent=q===" "?"\xA0":q,ae.appendChild(ie),P++}return P},K=(ae,Le)=>{d.textContent="";let Ie=ws(ae,""),P=0;for(let q of Ie){let ie=q.styles.length>0?(()=>{let F=h("span",q.styles.map(U=>`persona-tool-text-${U}`).join(" "));return d.appendChild(F),F})():d;if(q.isDuration&&i)ie.appendChild(M());else{let F=q.isDuration?Cs(t):q.text;Le?P=E(ie,F,P):ie.appendChild(document.createTextNode(F))}}};if(!B&&T)if(S.style.display="none",d.style.display="",i&&k!=="none"){let ae=(ye=g.loadingAnimationDuration)!=null?ye:2e3;d.setAttribute("data-preserve-animation","true"),k==="pulse"?(d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),K(T,!1)):(d.classList.add(`persona-tool-loading-${k}`),d.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&d.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&d.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),K(T,!0))}else K(T,!1);else if(!B&&i&&k!=="none"){d.style.display="";let ae=(de=g.loadingAnimationDuration)!=null?de:2e3;if(d.setAttribute("data-preserve-animation","true"),k==="pulse")d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${ae}ms`);else{d.classList.add(`persona-tool-loading-${k}`),d.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&d.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&d.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Le=d.textContent||f;d.textContent="",E(d,Le,0)}t.status==="complete"&&(d.style.display="none")}else B||(t.status==="complete"?d.style.display="none":d.style.display="");let Q=null;if(o){Q=h("div","persona-flex persona-items-center");let Le=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);Le?Q.appendChild(Le):Q.textContent=a?"Hide":"Show";let Ie=h("div","persona-flex persona-items-center persona-ml-auto");Ie.append(Q),c.append(p,Ie)}else c.append(p);let G=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(G.setAttribute("data-persona-collapsed-preview","reasoning"),G.style.display="none",G.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&u){let ae=(Me=(we=r==null?void 0:r.reasoning)==null?void 0:we.renderCollapsedPreview)==null?void 0:Me.call(we,{message:e,reasoning:t,defaultPreview:u,isActive:i,config:r!=null?r:{}});eu(G,ae)||(G.textContent=u),G.style.display=""}if(!a&&i&&s.activeMinHeight&&(n.style.minHeight=s.activeMinHeight),!o)return n.append(c,G),n;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 re=t.chunks.join(""),Te=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Te.textContent=re||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(Te),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),Q){Q.innerHTML="";let Le=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);Le?Q.appendChild(Le):Q.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",G.style.display=a?"none":G.textContent||G.childNodes.length?"":"none"})(),n.append(c,G,j),n};var io=new Set,nu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),ru=(e,r)=>{var o;let t=e.toolCall;if(!t)return"";let n=((o=t.chunks)!=null?o:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
|
|
17
|
+
`);let s=Qr(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
|
|
18
|
+
`):""},ou=(e,r)=>{var p,d,f,g,x;let t=e.toolCall,n=(p=r==null?void 0:r.features)==null?void 0:p.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=ru(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=t?Wc(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=(g=r==null?void 0:r.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((x=t.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&u.activeTextTemplate?c=ra(t,u.activeTextTemplate,c):!i&&u.completeTextTemplate&&(c=ra(t,u.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},ld=(e,r,t)=>{var p;let n=io.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=s.toggleTextColor||s.headerTextColor||"currentColor",f=fe(n?"chevron-up":"chevron-down",16,d,2);f?c.appendChild(f):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Ca=(e,r)=>{var re,Te,oe,Ce,Ne,he,ke,Be,ue;let t=e.toolCall,n=(re=r==null?void 0:r.toolCall)!=null?re:{},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),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=(oe=(Te=r==null?void 0:r.features)==null?void 0:Te.toolCallDisplay)!=null?oe:{},a=o.expandable!==!1,i=a&&io.has(e.id),{summary:u,previewText:c,isActive:p}=ou(e,r),d=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");d.type="button",a&&(d.setAttribute("aria-expanded",i?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(d.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(d.style.paddingLeft=n.headerPaddingX,d.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(d.style.paddingTop=n.headerPaddingY,d.style.paddingBottom=n.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(g.style.color=n.headerTextColor);let x=String((Ce=t.startedAt)!=null?Ce:Date.now()),M=()=>{let Y=h("span","");return Y.setAttribute("data-tool-elapsed",x),Y.textContent=No(t),Y},w=(he=n.renderCollapsedSummary)==null?void 0:he.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(Ne=o.collapsedMode)!=null?Ne:"tool-call",isActive:p,config:r!=null?r:{},elapsed:No(t),createElapsedElement:M});typeof w=="string"&&w.trim()?(g.textContent=w,f.appendChild(g)):w instanceof HTMLElement?f.appendChild(w):(g.textContent=u,f.appendChild(g));let S=(ke=o.loadingAnimation)!=null?ke:"none",k=n.activeTextTemplate,$=n.completeTextTemplate,v=p?k:$,T=w instanceof HTMLElement,B=(Y,ye,de)=>{let we=de;for(let Me of ye){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(we)),ae.textContent=Me===" "?"\xA0":Me,Y.appendChild(ae),we++}return we},E=(Y,ye)=>{var ae;g.textContent="";let de=((ae=t.name)==null?void 0:ae.trim())||"tool",we=ws(Y,de),Me=0;for(let Le of we){let Ie=Le.styles.length>0?(()=>{let P=h("span",Le.styles.map(q=>`persona-tool-text-${q}`).join(" "));return g.appendChild(P),P})():g;if(Le.isDuration&&p)Ie.appendChild(M());else{let P=Le.isDuration?No(t):Le.text;ye?Me=B(Ie,P,Me):Ie.appendChild(document.createTextNode(P))}}};if(!T)if(p&&S!=="none"){let Y=(Be=n.loadingAnimationDuration)!=null?Be:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${Y}ms`),v&&E(v,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${Y}ms`),S==="shimmer-color"&&(n.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),v)E(v,!0);else{let ye=g.textContent||u;g.textContent="",B(g,ye,0)}}else v&&E(v,!1);let K=null;if(a){K=h("div","persona-flex persona-items-center");let Y=n.toggleTextColor||n.headerTextColor||"currentColor",ye=fe(i?"chevron-up":"chevron-down",16,Y,2);ye?K.appendChild(ye):K.textContent=i?"Hide":"Show";let de=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(K),d.append(f,de)}else d.append(f);let Q=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(Q.setAttribute("data-persona-collapsed-preview","tool"),Q.style.display="none",Q.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let Y=(ue=n.renderCollapsedPreview)==null?void 0:ue.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:p,config:r!=null?r:{}});nu(Q,Y)||(Q.textContent=c),Q.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(d,Q),s;let G=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(G.style.display=i?"":"none",n.contentBackgroundColor&&(G.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(G.style.color=n.contentTextColor),n.contentPaddingX&&(G.style.paddingLeft=n.contentPaddingX,G.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(G.style.paddingTop=n.contentPaddingY,G.style.paddingBottom=n.contentPaddingY),t.name){let Y=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?Y.style.color=n.contentTextColor:n.headerTextColor&&(Y.style.color=n.headerTextColor),Y.textContent=t.name,G.appendChild(Y)}if(t.args!==void 0){let Y=h("div","persona-space-y-1"),ye=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ye.style.color=n.labelTextColor),ye.textContent="Arguments";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(de.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(de.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(de.style.color=n.codeBlockTextColor),de.textContent=Qr(t.args),Y.append(ye,de),G.appendChild(Y)}if(t.chunks&&t.chunks.length){let Y=h("div","persona-space-y-1"),ye=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ye.style.color=n.labelTextColor),ye.textContent="Activity";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(de.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(de.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(de.style.color=n.codeBlockTextColor),de.textContent=t.chunks.join(""),Y.append(ye,de),G.appendChild(Y)}if(t.status==="complete"&&t.result!==void 0){let Y=h("div","persona-space-y-1"),ye=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ye.style.color=n.labelTextColor),ye.textContent="Result";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(de.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(de.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(de.style.color=n.codeBlockTextColor),de.textContent=Qr(t.result),Y.append(ye,de),G.appendChild(Y)}if(t.status==="complete"&&typeof t.duration=="number"){let Y=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(Y.style.color=n.contentTextColor),Y.textContent=`Duration: ${t.duration}ms`,G.appendChild(Y)}return(()=>{if(d.setAttribute("aria-expanded",i?"true":"false"),K){K.innerHTML="";let Y=n.toggleTextColor||n.headerTextColor||"currentColor",ye=fe(i?"chevron-up":"chevron-down",16,Y,2);ye?K.appendChild(ye):K.textContent=i?"Hide":"Show"}G.style.display=i?"":"none",Q.style.display=i?"none":Q.textContent||Q.childNodes.length?"":"none"})(),s.append(d,Q,G),s};var wa=(e,r)=>{var M,w,S,k,$,v,T,B,E,K,Q,G;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.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=(M=n==null?void 0:n.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(w=n==null?void 0:n.borderColor)!=null?w:"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 u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=n==null?void 0:n.titleColor)!=null?S:"currentColor",p=fe(u,20,c,2);p&&i.appendChild(p);let d=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(g.style.color=n.titleColor),g.textContent=(k=n==null?void 0:n.title)!=null?k:"Approval Required",f.appendChild(g),!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"),f.appendChild(j)}d.appendChild(f);let x=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(x.style.color=n.descriptionColor),x.textContent=t.description,d.appendChild(x),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");n!=null&&n.parameterBackgroundColor&&(j.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(j.style.color=n.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=Qr(t.parameters),d.appendChild(j)}if(s){let j=h("div","persona-flex persona-gap-2 persona-mt-2");j.setAttribute("data-approval-buttons","true");let re=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");re.type="button",re.style.backgroundColor=($=n==null?void 0:n.approveButtonColor)!=null?$:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(v=n==null?void 0:n.approveButtonTextColor)!=null?v:"#ffffff",re.setAttribute("data-approval-action","approve");let Te=fe("shield-check",14,(T=n==null?void 0:n.approveButtonTextColor)!=null?T:"#ffffff",2);Te&&(Te.style.marginRight="4px",re.appendChild(Te));let oe=document.createTextNode((B=n==null?void 0:n.approveLabel)!=null?B:"Approve");re.appendChild(oe);let Ce=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");Ce.type="button",Ce.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",Ce.style.color=(K=n==null?void 0:n.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",Ce.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ce.setAttribute("data-approval-action","deny");let Ne=fe("shield-x",14,(Q=n==null?void 0:n.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",2);Ne&&(Ne.style.marginRight="4px",Ce.appendChild(Ne));let he=document.createTextNode((G=n==null?void 0:n.denyLabel)!=null?G:"Deny");Ce.appendChild(he),j.append(re,Ce),d.appendChild(j)}return a.append(i,d),o.appendChild(a),o};var cd=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let p=document.createDocumentFragment(),d=s?s.isStreaming():!1,f=g=>{switch(g){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'}};n.forEach(g=>{let x=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");x.type="button",x.textContent=g,x.disabled=d,i!=null&&i.fontFamily&&(x.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),p.appendChild(x),r.push(x)}),e.appendChild(p)}}};var Xo=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Zo=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function lo(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var su={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)"}},au={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},iu=["flowName","stepName","reasoningText","text","name","tool","toolName"],lu=100;function cu(e,r){let t={...su,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return au}function du(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function pu(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function uu(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.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 mu(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function gu(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function fu(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.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]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function Sa(e,r,t,n,s,o,a,i){var f;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");lo(c,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(d()),c;function d(){var re,Te;let g=h("div",""),x=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");x.setAttribute("data-event-id",e.id);let M=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),w=fe(u?"chevron-down":"chevron-right","14px","currentColor",2);w&&M.appendChild(w);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(re=n.timestampFormat)!=null?re:"relative";S.textContent=k==="relative"?du(e.timestamp,t):pu(e.timestamp);let $=null;n.showSequenceNumbers!==!1&&($=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),$.textContent=String(r+1));let v=cu(e.type,n.badgeColors),T=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");T.style.backgroundColor=v.bg,T.style.color=v.text,T.style.borderColor=v.text+"50",T.textContent=e.type;let B=(Te=n.descriptionFields)!=null?Te:iu,E=uu(e.payload,B),K=null;E&&(K=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),K.textContent=E);let Q=h("div","persona-flex-1 persona-min-w-0"),G=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=fe("clipboard","12px","currentColor",1.5);return j&&G.appendChild(j),G.addEventListener("click",async oe=>{oe.stopPropagation(),await mu(gu(e)),G.innerHTML="";let Ce=fe("check","12px","currentColor",1.5);Ce&&G.appendChild(Ce),setTimeout(()=>{G.innerHTML="";let Ne=fe("clipboard","12px","currentColor",1.5);Ne&&G.appendChild(Ne)},1500)}),x.appendChild(M),x.appendChild(S),$&&x.appendChild($),x.appendChild(T),K&&x.appendChild(K),x.appendChild(Q),x.appendChild(G),g.appendChild(x),u&&g.appendChild(fu(e,a,i)),g}}function dd(e){var g,x,M,w,S;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(g=s==null?void 0:s.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(x=a==null?void 0:a.iconName)!=null?x:"arrow-down",c=(M=a==null?void 0:a.label)!=null?M:"",p=(S=(w=s==null?void 0:s.features)==null?void 0:w.eventStream)!=null?S:{},d=o.find(k=>k.renderEventStreamView);if(d!=null&&d.renderEventStreamView&&s){let k=d.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=p.classNames,$=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");lo($,k==null?void 0:k.panel);let v=[],T="",B="",E=null,K=[],Q={},G=0,j=Rs(),re=0,Te=0,oe=!1,Ce=null,Ne=!1,he=0,ke=new Set,Be=new Map,ue="",Y="",ye=null,de,we,Me,ae,Le;function Ie(){let ne=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),pe=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");lo(pe,k==null?void 0:k.headerBar);let He=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");He.textContent="Events",de=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"),de.textContent="0";let at=h("div","persona-flex-1");we=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 Ft=h("option","");Ft.value="",Ft.textContent="All events",we.appendChild(Ft),Me=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"),Me.type="button",Me.title="Copy All";let jt=fe("clipboard-copy","12px","currentColor",1.5);jt&&Me.appendChild(jt);let xt=h("span","persona-text-xs");xt.textContent="Copy All",Me.appendChild(xt),pe.appendChild(He),pe.appendChild(de),pe.appendChild(at),pe.appendChild(we),pe.appendChild(Me);let nt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");lo(nt,k==null?void 0:k.searchBar);let vt=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),qe=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");vt&&qe.appendChild(vt),ae=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),lo(ae,k==null?void 0:k.searchInput),ae.type="text",ae.placeholder="Search event payloads...",Le=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"),Le.type="button",Le.style.display="none";let zt=fe("x","12px","currentColor",2);return zt&&Le.appendChild(zt),nt.appendChild(qe),nt.appendChild(ae),nt.appendChild(Le),ne.appendChild(pe),ne.appendChild(nt),ne}let P,q=o.find(ne=>ne.renderEventStreamToolbar);if(q!=null&&q.renderEventStreamToolbar&&s){let ne=q.renderEventStreamToolbar({config:s,defaultRenderer:()=>Ie(),eventCount:r.getSize(),filteredCount:0,onFilterChange:pe=>{T=pe,Xt(),Ge()},onSearchChange:pe=>{B=pe,Xt(),Ge()}});P=ne!=null?ne:Ie()}else P=Ie();let ie=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");ie.style.display="none";let F=h("div","persona-flex-1 persona-min-h-0 persona-relative"),U=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");U.style.height="100%";let me=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");lo(me,k==null?void 0:k.scrollIndicator),me.style.display="none",me.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Je=fe(u,"14px","currentColor",2);Je&&me.appendChild(Je);let ee=h("span","");ee.textContent=c,me.appendChild(ee);let le=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");le.style.display="none",F.appendChild(U),F.appendChild(le),F.appendChild(me),$.setAttribute("tabindex","0"),$.appendChild(P),$.appendChild(ie),$.appendChild(F);function Pt(){let ne=r.getAll(),pe={};for(let xt of ne)pe[xt.type]=(pe[xt.type]||0)+1;let He=Object.keys(pe).sort(),at=He.length!==K.length||!He.every((xt,nt)=>xt===K[nt]),Ft=!at&&He.some(xt=>pe[xt]!==Q[xt]),ft=ne.length!==Object.values(Q).reduce((xt,nt)=>xt+nt,0);if(!at&&!Ft&&!ft||(K=He,Q=pe,!we))return;let jt=we.value;if(we.options[0].textContent="All events",at){for(;we.options.length>1;)we.remove(1);for(let xt of He){let nt=h("option","");nt.value=xt,nt.textContent=`${xt} (${pe[xt]||0})`,we.appendChild(nt)}jt&&He.includes(jt)?we.value=jt:jt&&(we.value="",T="")}else for(let xt=1;xt<we.options.length;xt++){let nt=we.options[xt];nt.textContent=`${nt.value} (${pe[nt.value]||0})`}}function mt(){let ne=r.getAll();if(T&&(ne=ne.filter(pe=>pe.type===T)),B){let pe=B.toLowerCase();ne=ne.filter(He=>He.type.toLowerCase().includes(pe)||He.payload.toLowerCase().includes(pe))}return ne}function ze(){return T!==""||B!==""}function Xt(){G=0,re=0,j.resume(),me.style.display="none"}function Xe(ne){ke.has(ne)?ke.delete(ne):ke.add(ne),ye=ne;let pe=U.scrollTop,He=j.isFollowing();Ne=!0,j.pause(),Ge(),U.scrollTop=pe,He&&j.resume(),Ne=!1}function ge(){return Uo(U,50)}function Ge(){Te=Date.now(),oe=!1,Pt();let ne=r.getEvictedCount();ne>0?(ie.textContent=`${ne.toLocaleString()} older events truncated`,ie.style.display=""):ie.style.display="none",v=mt();let pe=v.length,He=r.getSize()>0;de&&(de.textContent=String(r.getSize())),pe===0&&He&&ze()?(le.textContent=B?`No events matching '${B}'`:"No events matching filter",le.style.display="",U.style.display="none"):(le.style.display="none",U.style.display=""),Me&&(Me.title=ze()?`Copy Filtered (${pe})`:"Copy All"),i&&!j.isFollowing()&&pe>G&&(re+=pe-G,ee.textContent=c?`${c}${re>0?` (${re})`:""}`:"",me.style.display=""),G=pe;let at=r.getAll(),Ft=at.length>0?at[0].timestamp:0,ft=new Set(v.map(nt=>nt.id));for(let nt of ke)ft.has(nt)||ke.delete(nt);let jt=T!==ue||B!==Y,xt=Be.size===0&&v.length>0;if(jt||xt||v.length===0){U.innerHTML="",Be.clear();let nt=document.createDocumentFragment();for(let vt=0;vt<v.length;vt++){let qe=Sa(v[vt],vt,Ft,p,ke,Xe,o,s);Be.set(v[vt].id,qe),nt.appendChild(qe)}U.appendChild(nt),ue=T,Y=B,ye=null}else{if(ye!==null){let vt=Be.get(ye);if(vt&&vt.parentNode===U){let qe=v.findIndex(zt=>zt.id===ye);if(qe>=0){let zt=Sa(v[qe],qe,Ft,p,ke,Xe,o,s);U.insertBefore(zt,vt),vt.remove(),Be.set(ye,zt)}}ye=null}let nt=new Set(v.map(vt=>vt.id));for(let[vt,qe]of Be)nt.has(vt)||(qe.remove(),Be.delete(vt));for(let vt=0;vt<v.length;vt++){let qe=v[vt];if(!Be.has(qe.id)){let zt=Sa(qe,vt,Ft,p,ke,Xe,o,s);Be.set(qe.id,zt),U.appendChild(zt)}}}j.isFollowing()&&(U.scrollTop=U.scrollHeight)}function Wt(){if(Date.now()-Te>=lu){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ge();return}oe||(oe=!0,Ce=requestAnimationFrame(()=>{Ce=null,Ge()}))}let Rt=(ne,pe)=>{if(!Me)return;Me.innerHTML="";let He=fe(ne,"12px","currentColor",1.5);He&&Me.appendChild(He);let at=h("span","persona-text-xs");at.textContent="Copy All",Me.appendChild(at),setTimeout(()=>{Me.innerHTML="";let Ft=fe("clipboard-copy","12px","currentColor",1.5);Ft&&Me.appendChild(Ft);let ft=h("span","persona-text-xs");ft.textContent="Copy All",Me.appendChild(ft),Me.disabled=!1},pe)},W=async()=>{if(Me){Me.disabled=!0;try{let ne;ze()?ne=v:t?(ne=await t(),ne.length===0&&(ne=r.getAll())):ne=r.getAll();let pe=ne.map(He=>{try{return JSON.parse(He.payload)}catch{return He.payload}});await navigator.clipboard.writeText(JSON.stringify(pe,null,2)),Rt("check",1500)}catch{Rt("x",1500)}}},X=()=>{we&&(T=we.value,Xt(),Ge())},Se=()=>{!ae||!Le||(Le.style.display=ae.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{B=ae.value,Xt(),Ge()},150))},Fe=()=>{!ae||!Le||(ae.value="",B="",Le.style.display="none",E&&clearTimeout(E),Xt(),Ge())},Ve=()=>{if(Ne)return;let ne=U.scrollTop,{action:pe,nextLastScrollTop:He}=Hs({following:j.isFollowing(),currentScrollTop:ne,lastScrollTop:he,nearBottom:ge(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=He,pe==="resume"?(j.resume(),re=0,me.style.display="none"):pe==="pause"&&(j.pause(),i&&(ee.textContent=c,me.style.display=""))},I=ne=>{let pe=Bs({following:j.isFollowing(),deltaY:ne.deltaY,nearBottom:ge(),resumeWhenNearBottom:!0});pe==="pause"?(j.pause(),i&&(ee.textContent=c,me.style.display="")):pe==="resume"&&(j.resume(),re=0,me.style.display="none")},te=()=>{i&&(U.scrollTop=U.scrollHeight,j.resume(),re=0,me.style.display="none")},Z=ne=>{let pe=ne.target;if(!pe||pe.closest("button"))return;let He=pe.closest("[data-event-id]");if(!He)return;let at=He.getAttribute("data-event-id");at&&Xe(at)},Ye=ne=>{if((ne.metaKey||ne.ctrlKey)&&ne.key==="f"){ne.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}ne.key==="Escape"&&(ae&&document.activeElement===ae?(Fe(),ae.blur(),$.focus()):n&&n())};Me&&Me.addEventListener("click",W),we&&we.addEventListener("change",X),ae&&ae.addEventListener("input",Se),Le&&Le.addEventListener("click",Fe),U.addEventListener("scroll",Ve),U.addEventListener("wheel",I,{passive:!0}),U.addEventListener("click",Z),me.addEventListener("click",te),$.addEventListener("keydown",Ye);function Pe(){E&&clearTimeout(E),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),oe=!1,Be.clear(),Me&&Me.removeEventListener("click",W),we&&we.removeEventListener("change",X),ae&&ae.removeEventListener("input",Se),Le&&Le.removeEventListener("click",Fe),U.removeEventListener("scroll",Ve),U.removeEventListener("wheel",I),U.removeEventListener("click",Z),me.removeEventListener("click",te),$.removeEventListener("keydown",Ye)}return{element:$,update:Wt,destroy:Pe}}}function pd(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=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`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 c=document.createElement("div");c.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 d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",d.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(g)}else d.textContent=a;if(c.append(p,d),i.append(u,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",n),i.append(f)}return i}var ud=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.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:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>pd(e,r)});if(p)return p}return pd(e,r)};var Aa=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},Ar=new Aa;Ar.register("PersonaArtifactCard",ud);function hu(e){var s;let r=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 n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function md(e,r){var Me,ae,Le,Ie;let t=(ae=(Me=e.features)==null?void 0:Me.artifacts)==null?void 0:ae.layout,s=((Le=t==null?void 0:t.toolbarPreset)!=null?Le:"default")==="document",o=(Ie=t==null?void 0:t.panePadding)==null?void 0:Ie.trim(),a=e.markdown?Zr(e.markdown):null,i=Bo(e.sanitize),u=P=>{let q=a?a(P):Ho(P);return i?i(q):q},c=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=()=>{c==null||c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};c&&c.addEventListener("click",()=>{var P;p(),(P=r.onDismiss)==null||P.call(r)});let d=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");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let g=h("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var P;p(),(P=r.onDismiss)==null||P.call(r)});let M="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?Nt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Nt({icon:"eye",label:"Rendered view"}),k=s?Nt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Nt({icon:"code-2",label:"Source"}),$=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),v=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,T=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,B=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(T&&B&&B.length>0),K=null,Q,G=null,j=null;if(s&&(v||T)&&!E){if(Q=v?Ns({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Nt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T){let P=fe("chevron-down",14,"currentColor",2);P&&Q.appendChild(P)}}else s&&E?(K=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=v?Ns({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Nt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G=Nt({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"}}),K.append(Q,G)):s?Q=Nt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):Q=Nt({icon:"copy",label:"Copy"});let re=s?Nt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Nt({icon:"refresh-cw",label:"Refresh"}),Te=s?Nt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Nt({icon:"x",label:"Close"}),oe=()=>{var U,me,Je;let P=(U=ue.find(ee=>ee.id===Y))!=null?U:ue[ue.length-1],q=(me=P==null?void 0:P.id)!=null?me:null,ie=(P==null?void 0:P.artifactType)==="markdown"&&(Je=P.markdown)!=null?Je:"",F=P?JSON.stringify({component:P.component,props:P.props},null,2):"";return{markdown:ie,jsonPayload:F,id:q}},Ce=async()=>{var U;let{markdown:P,jsonPayload:q}=oe(),ie=(U=ue.find(me=>me.id===Y))!=null?U:ue[ue.length-1],F=(ie==null?void 0:ie.artifactType)==="markdown"?P:ie?q:"";try{await navigator.clipboard.writeText(F)}catch{}};if(Q.addEventListener("click",async()=>{let P=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(P&&E){let{markdown:q,jsonPayload:ie,id:F}=oe();try{await P({actionId:"primary",artifactId:F,markdown:q,jsonPayload:ie})}catch{}return}await Ce()}),G&&(B!=null&&B.length)){let P=()=>{var ie;return(ie=d.closest("[data-persona-root]"))!=null?ie:document.body},q=()=>{j=zr({items:B.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:F,jsonPayload:U,id:me}=oe(),Je=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Je?await Je({actionId:ie,artifactId:me,markdown:F,jsonPayload:U}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(F):ie==="json"||ie==="source"?await navigator.clipboard.writeText(U):await navigator.clipboard.writeText(F||U)}catch{}},anchor:K!=null?K:G,position:"bottom-right",portal:P()})};d.isConnected?q():requestAnimationFrame(q),G.addEventListener("click",ie=>{ie.stopPropagation(),j==null||j.toggle()})}re.addEventListener("click",async()=>{var P;try{await((P=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:P.call(t))}catch{}de()}),Te.addEventListener("click",()=>{var P;p(),(P=r.onDismiss)==null||P.call(r)});let Ne=()=>{s&&(S.setAttribute("aria-pressed",M==="rendered"?"true":"false"),k.setAttribute("aria-pressed",M==="source"?"true":"false"))};S.addEventListener("click",()=>{M="rendered",Ne(),de()}),k.addEventListener("click",()=>{M="source",Ne(),de()});let he=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),w.append(S,k),K?$.append(K,re,Te):$.append(Q,re,Te),f.append(w,he,$),Ne()):(f.appendChild(g),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ke=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"),Be=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ke.style.paddingLeft=o,ke.style.paddingRight=o,Be.style.padding=o),d.appendChild(f),d.appendChild(ke),d.appendChild(Be);let ue=[],Y=null,ye=!1,de=()=>{var F,U,me,Je;let P=s&&ue.length<=1;ke.classList.toggle("persona-hidden",P),ke.replaceChildren();for(let ee of ue){let le=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");le.type="button",le.textContent=ee.title||ee.id.slice(0,8),ee.id===Y&&le.classList.add("persona-bg-persona-container","persona-border-persona-border"),le.addEventListener("click",()=>r.onSelect(ee.id)),ke.appendChild(le)}Be.replaceChildren();let q=Y&&ue.find(ee=>ee.id===Y)||ue[ue.length-1];if(!q)return;if(s){let ee=q.artifactType==="markdown"?"MD":(F=q.component)!=null?F:"Component",Pt=(q.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${Pt} \xB7 ${ee}`}else g.textContent="Artifacts";if(q.artifactType==="markdown"){if(s&&M==="source"){let le=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");le.textContent=(U=q.markdown)!=null?U:"",Be.appendChild(le);return}let ee=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ee.innerHTML=u((me=q.markdown)!=null?me:""),Be.appendChild(ee);return}let ie=q.component?Ar.get(q.component):void 0;if(ie){let le={message:{id:q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Pt=ie((Je=q.props)!=null?Je:{},le);if(Pt){Be.appendChild(Pt);return}}catch{}}Be.appendChild(hu(q))},we=()=>{var q;let P=ue.length>0;if(d.classList.toggle("persona-hidden",!P),c){let ie=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,U=((q=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?q:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;P&&U&&ye?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(P){var q,ie,F;ue=P.artifacts,Y=(F=(ie=P.selectedId)!=null?ie:(q=P.artifacts[P.artifacts.length-1])==null?void 0:q.id)!=null?F:null,ue.length>0&&(ye=!0),de(),we()},setMobileOpen(P){ye=P,!P&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):we()}}}function Wn(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function gd(e,r){var o,a,i,u;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"),!Wn(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function yu(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 Os(e,r){var u,c,p,d,f,g,x,M,w,S;if(!Wn(r)){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"),yu(e),gd(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.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",(d=t==null?void 0:t.paneWidth)!=null?d:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=t==null?void 0:t.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(M=t==null?void 0:t.documentToolbarIconColor)==null?void 0:M.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(w=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),gd(e,r)}var fd=["panel","seamless"];function $s(e,r){var i,u,c,p,d,f;for(let g of fd)e.classList.remove(`persona-artifact-appearance-${g}`);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"),!Wn(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=fd.includes(n)?n:"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=(d=t==null?void 0:t.paneShadow)==null?void 0:d.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 g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function hd(e,r){var t,n,s;return!r||!Wn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function bu(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function xu(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function vu(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Cu(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function yd(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function bd(e,r,t,n,s,o){let a=bu(s,200),i=Cu(r,t,n,200);i=Math.max(a,i);let u=xu(o);return u!==null&&(i=Math.min(i,u)),vu(e,a,i)}var xd={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"}},Ea=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,M,w;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(M=xd[a])!=null?M:xd.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,u.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var B,E;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${r.id}-${a}-${S.name}`;let $=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");$.textContent=S.label,k.appendChild($);let v=(B=S.type)!=null?B:"text",T;v==="textarea"?(T=document.createElement("textarea"),T.rows=3):(T=document.createElement("input"),T.type=v),T.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",T.id=`${r.id}-${a}-${S.name}`,T.name=S.name,T.placeholder=(E=S.placeholder)!=null?E:"",S.required&&(T.required=!0),k.appendChild(T),p.appendChild(k)});let d=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=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");g.type="submit",g.textContent=(w=i.submitLabel)!=null?w:"Submit",d.appendChild(f),d.appendChild(g),p.appendChild(d),o.replaceChildren(u,p),p.addEventListener("submit",async S=>{var T,B;S.preventDefault();let k=(T=t.formEndpoint)!=null?T:"/form",$=new FormData(p),v={};$.forEach((E,K)=>{v[K]=E}),v.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let E=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let K=await E.json();f.textContent=(B=K.message)!=null?B:"Thanks! We'll be in touch soon.",K.success&&K.nextPrompt&&await n.sendMessage(String(K.nextPrompt))}catch(E){f.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Ta=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},_s=new Ta;var vd=()=>{let e=new Map,r=(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:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var wu=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Su=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},js=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=wu(e),t=Su(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},Ma=e=>typeof e=="string"?e:e==null?"":String(e),co={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ma(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Ma(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Ma(t.text)}}},Cd=e=>Array.isArray(e)?e.map(r=>String(r)):[],zs=e=>{let r=new Set(Cd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Cd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.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((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",u)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var Au=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Eu=e=>e.map(r=>({...r,streaming:!1})),ka=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Au(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Eu(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};import{parse as Tu,STR as Mu,OBJ as ku}from"partial-json";function Lu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Iu(e,r){if(!Lu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function La(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=Tu(t,Mu|ku),o=Iu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Pu(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ia(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Ar.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:n,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 Wu(){let e=La();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Pa(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Wa(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var Ru=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ra(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=Ru}=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 d=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,g.appendChild(x);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,g.appendChild(M),f.appendChild(g);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let B=1;B<=5;B++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${B} star${B>1?"s":""}: ${c[B-1]}`),E.title=c[B-1],E.dataset.rating=String(B),E.innerHTML=`
|
|
19
19
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
20
20
|
<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>
|
|
21
21
|
</svg>
|
|
22
|
-
`,E.addEventListener("click",()=>{d=W,S.forEach((K,Q)=>{let X=Q<W;K.classList.toggle("selected",X),K.setAttribute("aria-checked",Q===W-1?"true":"false")})}),S.push(E),C.appendChild(E)}f.appendChild(C);let M=null;if(u){let W=document.createElement("div");W.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),W.appendChild(M),f.appendChild(W)}let H=document.createElement("div");H.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(d===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let W=(M==null?void 0:M.value.trim())||void 0;await r(d,W),p.remove()}catch(W){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),H.appendChild(w),H.appendChild(L),f.appendChild(H),p.appendChild(f),p}function va(e){let{onSubmit:r,onDismiss:t,title:n="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:u=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,x.appendChild(T);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,x.appendChild(C),g.appendChild(x);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,M.appendChild(H),M.appendChild(w);let L=document.createElement("div");L.className="persona-feedback-numbers";let W=[];for(let O=0;O<=10;O++){let oe=document.createElement("button");oe.type="button",oe.className="persona-feedback-rating-btn persona-feedback-number-btn",oe.setAttribute("role","radio"),oe.setAttribute("aria-checked","false"),oe.setAttribute("aria-label",`Rating ${O} out of 10`),oe.textContent=String(O),oe.dataset.rating=String(O),O<=6?oe.classList.add("persona-feedback-detractor"):O<=8?oe.classList.add("persona-feedback-passive"):oe.classList.add("persona-feedback-promoter"),oe.addEventListener("click",()=>{f=O,W.forEach((Ee,ae)=>{Ee.classList.toggle("selected",ae===O),Ee.setAttribute("aria-checked",ae===O?"true":"false")})}),W.push(oe),L.appendChild(oe)}S.appendChild(M),S.appendChild(L),g.appendChild(S);let E=null;if(u){let O=document.createElement("div");O.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=o,E.rows=3,E.setAttribute("aria-label","Additional comments"),O.appendChild(E),g.appendChild(O)}let K=document.createElement("div");K.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=i,Q.addEventListener("click",()=>{t==null||t(),d.remove()});let X=document.createElement("button");return X.type="button",X.className="persona-feedback-btn persona-feedback-btn-submit",X.textContent=a,X.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}X.disabled=!0,X.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await r(f,O),d.remove()}catch(O){X.disabled=!1,X.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),K.appendChild(Q),K.appendChild(X),g.appendChild(K),d.appendChild(g),d}var oo="persona-chat-history",Ru=30*1e3,Hu={"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 Bu(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=Hu[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function Ps(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function Du(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Nu(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ca=e=>!e||typeof e!="object"?{}:{...e},Cd=e=>e.map(r=>({...r,streaming:!1})),wd=(e,r,t)=>{let n=e!=null&&e.markdown?Vr(e.markdown):null,s=So(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 c,p,d;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let f=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?u=n(a):u=wo(a),s?s(u):u}};function Sd(e){var i,u,c,p;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ye(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let d=h("span","persona-drop-overlay-label");d.textContent=e.label,r.appendChild(d)}return r}var wa=(e,r,t)=>{var Ba,Da,Na,Fa,Oa,$a,_a,ja,za,qa,Ua,Va,Ja,Ga,Ya,Ka,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,mi,gi,fi,hi,yi,bi,xi,vi;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 n=Zs(r),s=ks.getForInstance(n.plugins);n.components&&xr.registerAll(n.components);let o=xd(),a=(Ba=n.storageAdapter)!=null?Ba:ga(),i={},u=null,c=!1,p=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:A}=m;return A&&(c=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=p(m);y.metadata&&(i=Ca(y.metadata)),(Da=y.messages)!=null&&Da.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(Na=l.messages)!=null&&Na.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},lo()},g=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ls],x=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ro.message,ro.messageAndClick],T=Is({parsers:g,handlers:x,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let C=(Oa=(Fa=n.launcher)==null?void 0:Fa.enabled)!=null?Oa:!0,S=(_a=($a=n.launcher)==null?void 0:$a.autoExpand)!=null?_a:!1,M=(ja=n.autoFocusInput)!=null?ja:!1,H=S,w=C,L=(qa=(za=n.layout)==null?void 0:za.header)==null?void 0:qa.layout,W=!1,E=C?S:!0,K=!1,Q=null,X=()=>{K=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{K&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),K=!1)},1e4)},O=wd(n,T,X),oe=(Va=(Ua=n.features)==null?void 0:Ua.showReasoning)!=null?Va:!0,Ee=(Ga=(Ja=n.features)==null?void 0:Ja.showToolCalls)!=null?Ga:!0,ae=(Ka=(Ya=n.features)==null?void 0:Ya.showEventStreamToggle)!=null?Ka:!1,we=(Za=(Xa=n.features)==null?void 0:Xa.scrollToBottom)!=null?Za:{},he=`${(ei=typeof n.persistState=="object"?(Qa=n.persistState)==null?void 0:Qa.keyPrefix:void 0)!=null?ei:"persona-"}event-stream`,We=ae?new $o(he):null,Re=(ri=(ni=(ti=n.features)==null?void 0:ti.eventStream)==null?void 0:ni.maxEvents)!=null?ri:2e3,ie=ae?new Oo(Re,We):null,Z=null,me=!1,V=null,re=0;We==null||We.open().then(()=>ie==null?void 0:ie.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let He={onCopy:l=>{var m,y;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onCopy)==null||y.call(m,l)},onFeedback:l=>{var m,y;o.emit("message:feedback",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},ge=(oi=n.statusIndicator)!=null?oi:{},Be=l=>{var m,y,A,I;return l==="idle"?(m=ge.idleText)!=null?m:tn.idle:l==="connecting"?(y=ge.connectingText)!=null?y:tn.connecting:l==="connected"?(A=ge.connectedText)!=null?A:tn.connected:l==="error"?(I=ge.errorText)!=null?I:tn.error:tn[l]};function st(l,m,y,A){if(A==="idle"&&y.idleLink){l.textContent="";let I=document.createElement("a");I.href=y.idleLink,I.target="_blank",I.rel="noopener noreferrer",I.textContent=m,I.style.color="inherit",I.style.textDecoration="none",l.appendChild(I)}else l.textContent=m}let{wrapper:z,panel:U}=td(n),se=nd(n,C),{container:N,body:J,messagesWrapper:ce,suggestions:fe,textarea:te,sendButton:pe,sendButtonWrapper:kt,composerForm:dt,statusText:Wt,introTitle:Jt,introSubtitle:P,closeButton:$,iconHolder:ne,headerTitle:Pe,headerSubtitle:Fe,header:Ce,footer:be,actionsRow:at,leftActions:mt,rightActions:At}=se,j=se.micButton,xe=se.micButtonWrapper,ue=se.attachmentButton,Ze=se.attachmentButtonWrapper,qe=se.attachmentInput,de=se.attachmentPreviewsContainer;N.classList.add("persona-relative"),J.classList.add("persona-relative");let Te=12,Ve=()=>{var l;return(l=we.label)!=null?l:""},vt=()=>{var l;return(l=we.iconName)!=null?l:"arrow-down"},Ot=()=>we.enabled!==!1,pt=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");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let $t=h("span","persona-flex persona-items-center"),ht=h("span","");pt.append($t,ht),N.appendChild(pt);let Qe=()=>{let m=be.style.display==="none"?0:be.offsetHeight;pt.style.bottom=`${m+Te}px`};Qe();let yt=()=>{let l=!!Ve();pt.setAttribute("aria-label",Ve()||"Jump to latest"),pt.title=Ve(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),$t.innerHTML="";let m=ye(vt(),"14px","currentColor",2);m?($t.appendChild(m),$t.style.display=""):$t.style.display="none",ht.textContent=Ve(),ht.style.display=l?"":"none"};yt();let je=null,_t=null,zn=s.find(l=>l.renderHeader);if(zn!=null&&zn.renderHeader){let l=zn.renderHeader({config:n,defaultRenderer:()=>{let m=br({config:n,showClose:C});return Zr(N,m,n),m.header},onClose:()=>It(!1,"user")});if(l){let m=N.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),Ce=l)}}let Kn=()=>{var m,y,A,I;if(!ie)return;if(me=!0,!Z&&ie&&(Z=cd({buffer:ie,getFullHistory:()=>ie.getAllFromStore(),onClose:()=>Wn(),config:n,plugins:s})),Z&&(J.style.display="none",(m=be.parentNode)==null||m.insertBefore(Z.element,be),Z.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${fn.actionIconColor}`;let R=(I=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:I.toggleButtonActive;R&&R.split(/\s+/).forEach(B=>B&&tt.classList.add(B))}let l=()=>{if(!me)return;let R=Date.now();R-re>=200&&(Z==null||Z.update(),re=R),V=requestAnimationFrame(l)};re=0,V=requestAnimationFrame(l),tr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Wn=()=>{var l,m,y;if(me){if(me=!1,Z&&Z.element.remove(),J.style.display="",tt){tt.style.boxShadow="";let A=(y=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(I=>I&&tt.classList.remove(I))}V!==null&&(cancelAnimationFrame(V),V=null),tr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(ae){let l=(ai=(si=n.features)==null?void 0:si.eventStream)==null?void 0:ai.classNames,m="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"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");tt=h("button",m),tt.style.width="28px",tt.style.height="28px",tt.style.color=fn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let y=ye("activity","18px","currentColor",1.5);y&&tt.appendChild(y);let A=se.clearChatButtonWrapper,I=se.closeButtonWrapper,R=A||I;R&&R.parentNode===Ce?Ce.insertBefore(tt,R):Ce.appendChild(tt),tt.addEventListener("click",()=>{me?Wn():Kn()})}let Cr=l=>{var A,I,R;let m=n.attachments;if(!(m!=null&&m.enabled))return;let y=l.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 B=l.querySelector("[data-persona-composer-form]");B!=null&&B.parentNode?B.parentNode.insertBefore(y,B):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let B=h("input");B.type="file",B.accept=((A=m.allowedTypes)!=null?A:or).join(","),B.multiple=((I=m.maxFiles)!=null?I:4)>1,B.style.display="none",B.setAttribute("aria-label",(R=m.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(B)}},qn=s.find(l=>l.renderComposer);if(qn!=null&&qn.renderComposer){let l=n.composer,m=qn.renderComposer({config:n,defaultRenderer:()=>No({config:n}).footer,onSubmit:y=>{var B;if(!D||D.isStreaming())return;let A=y.trim(),I=(B=je==null?void 0:je.hasAttachments())!=null?B:!1;if(!A&&!I)return;let R;I&&(R=[],R.push(...je.getContentParts()),A&&R.push(us(A))),D.sendMessage(A,{contentParts:R}),I&&je.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{qe==null||qe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((ii=n.voiceRecognition)==null?void 0:ii.enabled)===!0?()=>{_t==null||_t()}:void 0});m&&(be.replaceWith(m),be=m)}let wr=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),I=l.querySelector("[data-persona-composer-mic]"),R=l.querySelector("[data-persona-composer-status]");m&&(dt=m),y&&(te=y),A&&(pe=A),I&&(j=I,xe=I.parentElement),R&&(Wt=R);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(fe=B);let G=l.querySelector(".persona-attachment-button");G&&(ue=G,Ze=G.parentElement),qe=l.querySelector('input[type="file"]'),de=l.querySelector(".persona-attachment-previews");let F=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(at=F)};Cr(be),wr(be);let An=(li=n.layout)==null?void 0:li.contentMaxWidth;if(An&&dt&&(dt.style.maxWidth=An,dt.style.marginLeft="auto",dt.style.marginRight="auto"),An&&fe&&(fe.style.maxWidth=An,fe.style.marginLeft="auto",fe.style.marginRight="auto"),An&&de&&(de.style.maxWidth=An,de.style.marginLeft="auto",de.style.marginRight="auto"),(ci=n.attachments)!=null&&ci.enabled&&qe&&de){je=Xr.fromConfig(n.attachments),je.setPreviewsContainer(de),qe.addEventListener("change",y=>{let A=y.target;je==null||je.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=Sd(l);N.appendChild(m)}(()=>{var A,I;let l=(I=(A=n.layout)==null?void 0:A.slots)!=null?I:{},m=R=>{switch(R){case"body-top":return N.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ce;case"footer-top":return fe;case"composer":return dt;case"footer-bottom":return Wt;default:return null}},y=(R,B)=>{var G;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")Ce.insertBefore(B,Ce.firstChild);else if(R==="header-right")Ce.appendChild(B);else{let F=Ce.querySelector(".persona-flex-col");F?(G=F.parentNode)==null||G.insertBefore(B,F.nextSibling):Ce.appendChild(B)}break;case"body-top":{let F=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(B):J.insertBefore(B,J.firstChild);break}case"body-bottom":J.appendChild(B);break;case"footer-top":fe.replaceWith(B);break;case"footer-bottom":Wt.replaceWith(B);break;default:break}};for(let[R,B]of Object.entries(l))if(B)try{let G=B({config:n,defaultContent:()=>m(R)});G&&y(R,G)}catch(G){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,G)}})();let ar=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let I=A.getAttribute("data-message-id");if(!I)return;let R=y.getAttribute("data-bubble-type");R==="reasoning"?(eo.has(I)?eo.delete(I):eo.add(I),ad(I,A)):R==="tool"&&(to.has(I)?to.delete(I):to.add(I),id(I,A,n)),Tn.delete(I)};ce.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ar(l))}),ce.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ar(l))});let Xn=new Map;ce.addEventListener("click",l=>{var B;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let I=A.getAttribute("data-actions-for");if(!I)return;let R=y.getAttribute("data-action");if(R==="copy"){let F=D.getMessages().find(ve=>ve.id===I);if(F&&He.onCopy){let ve=F.content||"";navigator.clipboard.writeText(ve).then(()=>{y.classList.add("persona-message-action-success");let Se=ye("check",14,"currentColor",2);Se&&(y.innerHTML="",y.appendChild(Se)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Me=ye("copy",14,"currentColor",2);Me&&(y.innerHTML="",y.appendChild(Me))},2e3)}).catch(Se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Se)}),He.onCopy(F)}}else if(R==="upvote"||R==="downvote"){let F=((B=Xn.get(I))!=null?B:null)===R,ve=R==="upvote"?"thumbs-up":"thumbs-down";if(F){Xn.delete(I),y.classList.remove("persona-message-action-active");let Se=ye(ve,14,"currentColor",2);Se&&(y.innerHTML="",y.appendChild(Se))}else{let Se=R==="upvote"?"downvote":"upvote",Me=A.querySelector(`[data-action="${Se}"]`);if(Me){Me.classList.remove("persona-message-action-active");let Ge=ye(Se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(Me.innerHTML="",Me.appendChild(Ge))}Xn.set(I,R),y.classList.add("persona-message-action-active");let ke=ye(ve,14,"currentColor",2);ke&&(ke.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ke)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ue=D.getMessages().find(lt=>lt.id===I);Ue&&He.onFeedback&&He.onFeedback({type:R,messageId:Ue.id,message:Ue})}}}),ce.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".persona-approval-bubble");if(!A)return;let I=A.getAttribute("data-message-id");if(!I)return;let R=y.getAttribute("data-approval-action");if(!R)return;let B=R==="approve"?"approved":"denied",F=D.getMessages().find(Se=>Se.id===I);if(!(F!=null&&F.approval))return;let ve=A.querySelector("[data-approval-buttons]");ve&&ve.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),D.resolveApproval(F.approval,B)});let it=null,hn=null,Rn={artifacts:[],selectedId:null},nn=!1,ir={current:null};ce.addEventListener("click",l=>{var Me,ke,Ne,Ue,lt;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Ne=(ke=(Me=n.features)==null?void 0:Me.artifacts)==null?void 0:ke.onArtifactAction)==null?void 0:Ne.call(ke,{type:"download",artifactId:A}))===!0)return;let R=D.getArtifactById(A),B=R==null?void 0:R.markdown,G=(R==null?void 0:R.title)||"artifact";if(!B){let Ge=y.closest("[data-open-artifact]"),_=Ge==null?void 0:Ge.closest("[data-message-id]"),Oe=_==null?void 0:_.getAttribute("data-message-id");if(Oe){let Ae=D.getMessages().find(ze=>ze.id===Oe);if(Ae!=null&&Ae.rawContent)try{let ze=JSON.parse(Ae.rawContent);B=(Ue=ze==null?void 0:ze.props)==null?void 0:Ue.markdown,G=((lt=ze==null?void 0:ze.props)==null?void 0:lt.title)||G}catch{}}}if(!B)return;let F=new Blob([B],{type:"text/markdown"}),ve=URL.createObjectURL(F),Se=document.createElement("a");Se.href=ve,Se.download=`${G}.md`,Se.click(),URL.revokeObjectURL(ve)}),ce.addEventListener("click",l=>{var R,B,G;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((G=(B=(R=n.features)==null?void 0:R.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:G.call(B,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),nn=!1,D.selectArtifact(A),bn())}),ce.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let yn=null,Et=null,rn=null,En=null,lr=()=>{};function Zn(){En==null||En(),En=null}let cr=()=>{var B;if(!yn||!Et)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((B=e.ownerDocument.defaultView)!=null?B:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){Et.style.removeProperty("position"),Et.style.removeProperty("left"),Et.style.removeProperty("top"),Et.style.removeProperty("bottom"),Et.style.removeProperty("width"),Et.style.removeProperty("z-index");return}let A=yn.firstElementChild;if(!A||A===Et)return;let I=10;Et.style.position="absolute",Et.style.top="0",Et.style.bottom="0",Et.style.width=`${I}px`,Et.style.zIndex="5";let R=A.offsetWidth-I/2;Et.style.left=`${Math.max(0,R)}px`},Un=()=>{},bn=()=>{var y,A,I,R,B;if(!it||!Pn(n))return;Ts(e,n),Ms(e,n),Un();let l=(R=(I=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:I.narrowHostMaxWidth)!=null?R:520,m=U.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),it.update(Rn),nn?(it.setMobileOpen(!1),it.element.classList.add("persona-hidden"),(B=it.backdrop)==null||B.classList.add("persona-hidden")):Rn.artifacts.length>0&&(it.element.classList.remove("persona-hidden"),it.setMobileOpen(!0)),lr()};if(Pn(n)){U.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(N),it=ud(n,{onSelect:y=>{var A;return(A=ir.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{nn=!0,bn()}}),it.element.classList.add("persona-hidden"),yn=m,m.appendChild(l),m.appendChild(it.element),it.backdrop&&U.appendChild(it.backdrop),U.appendChild(m),lr=()=>{var A,I,R,B;if(!yn||!it)return;if(!(((R=(I=(A=n.features)==null?void 0:A.artifacts)==null?void 0:I.layout)==null?void 0:R.resizable)===!0)){rn==null||rn(),rn=null,Zn(),Et&&(Et.remove(),Et=null),it.element.style.removeProperty("width"),it.element.style.removeProperty("maxWidth");return}if(!Et){let G=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");G.setAttribute("role","separator"),G.setAttribute("aria-orientation","vertical"),G.setAttribute("aria-label","Resize artifacts panel"),G.tabIndex=0;let F=e.ownerDocument,ve=(B=F.defaultView)!=null?B:window,Se=Me=>{var _,Oe;if(!it||Me.button!==0||e.classList.contains("persona-artifact-narrow-host")||ve.innerWidth<=640)return;Me.preventDefault(),Zn();let ke=Me.clientX,Ne=it.element.getBoundingClientRect().width,Ue=(Oe=(_=n.features)==null?void 0:_.artifacts)==null?void 0:Oe.layout,lt=_e=>{let Ae=yn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),St=ze?0:hd(yn,ve),xt=ze?0:G.getBoundingClientRect().width||6,Ut=Ne-(_e.clientX-ke),Xt=yd(Ut,Ae,St,xt,Ue==null?void 0:Ue.resizableMinWidth,Ue==null?void 0:Ue.resizableMaxWidth);it.element.style.width=`${Xt}px`,it.element.style.maxWidth="none",cr()},Ge=()=>{F.removeEventListener("pointermove",lt),F.removeEventListener("pointerup",Ge),F.removeEventListener("pointercancel",Ge),En=null;try{G.releasePointerCapture(Me.pointerId)}catch{}};En=Ge,F.addEventListener("pointermove",lt),F.addEventListener("pointerup",Ge),F.addEventListener("pointercancel",Ge);try{G.setPointerCapture(Me.pointerId)}catch{}};G.addEventListener("pointerdown",Se),Et=G,yn.insertBefore(G,it.element),rn=()=>{G.removeEventListener("pointerdown",Se)}}if(Et){let G=Rn.artifacts.length>0&&!nn;Et.classList.toggle("persona-hidden",!G),cr()}},Un=()=>{var ve,Se,Me,ke,Ne,Ue,lt,Ge,_,Oe,_e,Ae,ze,St;if(!C||!it||((Se=(ve=n.launcher)==null?void 0:ve.sidebarMode)!=null?Se:!1)||Kt(n)&&_n(n).reveal==="emerge")return;let A=(Me=e.ownerDocument.defaultView)!=null?Me:window,I=(Ne=(ke=n.launcher)==null?void 0:ke.mobileFullscreen)!=null?Ne:!0,R=(lt=(Ue=n.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?lt:640;if(I&&A.innerWidth<=R||!fd(n,C))return;let B=(Oe=(_=(Ge=n.launcher)==null?void 0:Ge.width)!=null?_:n.launcherWidth)!=null?Oe:In,G=(St=(ze=(Ae=(_e=n.features)==null?void 0:_e.artifacts)==null?void 0:Ae.layout)==null?void 0:ze.expandedPanelWidth)!=null?St:"min(720px, calc(100vw - 24px))";Rn.artifacts.length>0&&!nn?(U.style.width=G,U.style.maxWidth=G):(U.style.width=B,U.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(hn=new ResizeObserver(()=>{bn()}),hn.observe(U))}else U.appendChild(N);e.appendChild(z);let Vn=()=>{var xt,Ut,Xt,Ie,dn,Qt,On,ot,gt,pn,rr,Ye,Tt,Lr,Ir,Qo,es,ts,_s,js,jt,ns,yo;let l=Kt(n),m=(Ut=(xt=n.launcher)==null?void 0:xt.sidebarMode)!=null?Ut:!1,y=l||m||((Ie=(Xt=n.launcher)==null?void 0:Xt.fullHeight)!=null?Ie:!1),A=((dn=n.launcher)==null?void 0:dn.enabled)===!1,I=(On=(Qt=n.theme)==null?void 0:Qt.components)==null?void 0:On.panel,R=xs(n),B=(un,Ln)=>{var Ur;return un==null||un===""?Ln:(Ur=Io(R,un))!=null?Ur:un},G=(ot=e.ownerDocument.defaultView)!=null?ot:window,F=(pn=(gt=n.launcher)==null?void 0:gt.mobileFullscreen)!=null?pn:!0,ve=(Ye=(rr=n.launcher)==null?void 0:rr.mobileBreakpoint)!=null?Ye:640,Se=G.innerWidth<=ve,Me=F&&Se&&C,ke=(Lr=(Tt=n.launcher)==null?void 0:Tt.position)!=null?Lr:"bottom-left",Ne=ke==="bottom-left"||ke==="top-left",Ue=(Qo=(Ir=n.launcher)==null?void 0:Ir.zIndex)!=null?Qo:gn,lt=m||Me?"none":"1px solid var(--persona-border)",Ge=Me?"none":m?Ne?"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))";l&&!Me&&(Ge="none",lt="none");let _=m||Me?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Oe=B(I==null?void 0:I.border,lt),_e=B(I==null?void 0:I.shadow,Ge),Ae=B(I==null?void 0:I.borderRadius,_);if(e.style.cssText="",z.style.cssText="",U.style.cssText="",N.style.cssText="",J.style.cssText="",be.style.cssText="",Me){z.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"),z.style.cssText=`
|
|
22
|
+
`,E.addEventListener("click",()=>{d=B,S.forEach((K,Q)=>{let G=Q<B;K.classList.toggle("selected",G),K.setAttribute("aria-checked",Q===B-1?"true":"false")})}),S.push(E),w.appendChild(E)}f.appendChild(w);let k=null;if(u){let B=document.createElement("div");B.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),B.appendChild(k),f.appendChild(B)}let $=document.createElement("div");$.className="persona-feedback-actions";let v=document.createElement("button");v.type="button",v.className="persona-feedback-btn persona-feedback-btn-skip",v.textContent=i,v.addEventListener("click",()=>{t==null||t(),p.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=a,T.addEventListener("click",async()=>{if(d===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let B=(k==null?void 0:k.value.trim())||void 0;await r(d,B),p.remove()}catch(B){T.disabled=!1,T.textContent=a,console.error("[CSAT Feedback] Failed to submit:",B)}}),$.appendChild(v),$.appendChild(T),f.appendChild($),p.appendChild(f),p}function Ha(e){let{onSubmit:r,onDismiss:t,title:n="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:u=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,x.appendChild(M);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=s,x.appendChild(w),g.appendChild(x);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let $=document.createElement("span");$.className="persona-feedback-label-low",$.textContent=c;let v=document.createElement("span");v.className="persona-feedback-label-high",v.textContent=p,k.appendChild($),k.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-numbers";let B=[];for(let j=0;j<=10;j++){let re=document.createElement("button");re.type="button",re.className="persona-feedback-rating-btn persona-feedback-number-btn",re.setAttribute("role","radio"),re.setAttribute("aria-checked","false"),re.setAttribute("aria-label",`Rating ${j} out of 10`),re.textContent=String(j),re.dataset.rating=String(j),j<=6?re.classList.add("persona-feedback-detractor"):j<=8?re.classList.add("persona-feedback-passive"):re.classList.add("persona-feedback-promoter"),re.addEventListener("click",()=>{f=j,B.forEach((Te,oe)=>{Te.classList.toggle("selected",oe===j),Te.setAttribute("aria-checked",oe===j?"true":"false")})}),B.push(re),T.appendChild(re)}S.appendChild(k),S.appendChild(T),g.appendChild(S);let E=null;if(u){let j=document.createElement("div");j.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=o,E.rows=3,E.setAttribute("aria-label","Additional comments"),j.appendChild(E),g.appendChild(j)}let K=document.createElement("div");K.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=i,Q.addEventListener("click",()=>{t==null||t(),d.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=a,G.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let j=(E==null?void 0:E.value.trim())||void 0;await r(f,j),d.remove()}catch(j){G.disabled=!1,G.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),K.appendChild(Q),K.appendChild(G),g.appendChild(K),d.appendChild(g),d}var po="persona-chat-history",Hu=30*1e3,Bu={"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 Du(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=Bu[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function qs(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function Nu(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Fu(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ba=e=>!e||typeof e!="object"?{}:{...e},wd=e=>e.map(r=>({...r,streaming:!1})),Sd=(e,r,t)=>{let n=e!=null&&e.markdown?Zr(e.markdown):null,s=Bo(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 c,p,d;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let f=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?u=n(a):u=Ho(a),s?s(u):u}};function Ad(e){var i,u,c,p;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=fe(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let d=h("span","persona-drop-overlay-label");d.textContent=e.label,r.appendChild(d)}return r}var Da=(e,r,t)=>{var kt,ot,qt,Tt,Zt,st,ht,Qt,On,Lt,Vt,Ja,Ga,Ka,Ya,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,mi,gi,fi,hi,yi,bi,xi,vi,Ci;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 n=ua(r),s=_s.getForInstance(n.plugins);n.components&&Ar.registerAll(n.components);let o=vd(),a=(kt=n.storageAdapter)!=null?kt:ka(),i={},u=null,c=!1,p=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:A}=m;return A&&(c=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=p(m);y.metadata&&(i=Ba(y.metadata)),(ot=y.messages)!=null&&ot.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(qt=l.messages)!=null&&qt.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},fo()},g=n.actionParsers&&n.actionParsers.length?n.actionParsers:[js],x=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[co.message,co.messageAndClick],M=zs({parsers:g,handlers:x,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let w=(Zt=(Tt=n.launcher)==null?void 0:Tt.enabled)!=null?Zt:!0,S=(ht=(st=n.launcher)==null?void 0:st.autoExpand)!=null?ht:!1,k=(Qt=n.autoFocusInput)!=null?Qt:!1,$=S,v=w,T=(Lt=(On=n.layout)==null?void 0:On.header)==null?void 0:Lt.layout,B=!1,E=w?S:!0,K=!1,Q=null,G=()=>{K=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{K&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),K=!1)},1e4)},j=Sd(n,M,G),re=(Ja=(Vt=n.features)==null?void 0:Vt.showReasoning)!=null?Ja:!0,Te=(Ka=(Ga=n.features)==null?void 0:Ga.showToolCalls)!=null?Ka:!0,oe=(Xa=(Ya=n.features)==null?void 0:Ya.showEventStreamToggle)!=null?Xa:!1,Ce=(Qa=(Za=n.features)==null?void 0:Za.scrollToBottom)!=null?Qa:{},he=`${(ti=typeof n.persistState=="object"?(ei=n.persistState)==null?void 0:ei.keyPrefix:void 0)!=null?ti:"persona-"}event-stream`,ke=oe?new Zo(he):null,Be=(oi=(ri=(ni=n.features)==null?void 0:ni.eventStream)==null?void 0:ri.maxEvents)!=null?oi:2e3,ue=oe?new Xo(Be,ke):null,Y=null,ye=!1,de=null,we=0;ke==null||ke.open().then(()=>ue==null?void 0:ue.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Me={onCopy:l=>{var m,y;o.emit("message:copy",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onCopy)==null||y.call(m,l)},onFeedback:l=>{var m,y;o.emit("message:feedback",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},ae=(si=n.statusIndicator)!=null?si:{},Le=l=>{var m,y,A,L;return l==="idle"?(m=ae.idleText)!=null?m:rn.idle:l==="connecting"?(y=ae.connectingText)!=null?y:rn.connecting:l==="connected"?(A=ae.connectedText)!=null?A:rn.connected:l==="error"?(L=ae.errorText)!=null?L:rn.error:rn[l]};function Ie(l,m,y,A){if(A==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=m,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=m}let{wrapper:P,panel:q}=nd(n),ie=rd(n,w),{container:F,body:U,messagesWrapper:me,suggestions:Je,textarea:ee,sendButton:le,sendButtonWrapper:Pt,composerForm:mt,statusText:ze,introTitle:Xt,introSubtitle:Xe,closeButton:ge,iconHolder:Ge,headerTitle:Wt,headerSubtitle:Rt,header:W,footer:X,actionsRow:Se,leftActions:Fe,rightActions:Ve}=ie,I=ie.micButton,te=ie.micButtonWrapper,Z=ie.attachmentButton,Ye=ie.attachmentButtonWrapper,Pe=ie.attachmentInput,ne=ie.attachmentPreviewsContainer;F.classList.add("persona-relative"),U.classList.add("persona-relative");let pe=12,He=()=>{var l;return(l=Ce.label)!=null?l:""},at=()=>{var l;return(l=Ce.iconName)!=null?l:"arrow-down"},Ft=()=>Ce.enabled!==!1,ft=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");ft.type="button",ft.style.display="none",ft.setAttribute("data-persona-scroll-to-bottom","true");let jt=h("span","persona-flex persona-items-center"),xt=h("span","");ft.append(jt,xt),F.appendChild(ft);let nt=()=>{let m=X.style.display==="none"?0:X.offsetHeight;ft.style.bottom=`${m+pe}px`};nt();let vt=()=>{let l=!!He();ft.setAttribute("aria-label",He()||"Jump to latest"),ft.title=He(),ft.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),jt.innerHTML="";let m=fe(at(),"14px","currentColor",2);m?(jt.appendChild(m),jt.style.display=""):jt.style.display="none",xt.textContent=He(),xt.style.display=l?"":"none"};vt();let qe=null,zt=null,qn=s.find(l=>l.renderHeader);if(qn!=null&&qn.renderHeader){let l=qn.renderHeader({config:n,defaultRenderer:()=>{let m=Sr({config:n,showClose:w});return oo(F,m,n),m.header},onClose:()=>Ht(!1,"user")});if(l){let m=F.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),W=l)}}let Xn=()=>{var m,y,A,L;if(!ue)return;if(ye=!0,!Y&&ue&&(Y=dd({buffer:ue,getFullHistory:()=>ue.getAllFromStore(),onClose:()=>Rn(),config:n,plugins:s})),Y&&(U.style.display="none",(m=X.parentNode)==null||m.insertBefore(Y.element,X),Y.update()),it){it.style.boxShadow=`inset 0 0 0 1.5px ${yn.actionIconColor}`;let H=(L=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;H&&H.split(/\s+/).forEach(D=>D&&it.classList.add(D))}let l=()=>{if(!ye)return;let H=Date.now();H-we>=200&&(Y==null||Y.update(),we=H),de=requestAnimationFrame(l)};we=0,de=requestAnimationFrame(l),nr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Rn=()=>{var l,m,y;if(ye){if(ye=!1,Y&&Y.element.remove(),U.style.display="",it){it.style.boxShadow="";let A=(y=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&it.classList.remove(L))}de!==null&&(cancelAnimationFrame(de),de=null),nr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},it=null;if(oe){let l=(ii=(ai=n.features)==null?void 0:ai.eventStream)==null?void 0:ii.classNames,m="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"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");it=h("button",m),it.style.width="28px",it.style.height="28px",it.style.color=yn.actionIconColor,it.type="button",it.setAttribute("aria-label","Event Stream"),it.title="Event Stream";let y=fe("activity","18px","currentColor",1.5);y&&it.appendChild(y);let A=ie.clearChatButtonWrapper,L=ie.closeButtonWrapper,H=A||L;H&&H.parentNode===W?W.insertBefore(it,H):W.appendChild(it),it.addEventListener("click",()=>{ye?Rn():Xn()})}let Tr=l=>{var A,L,H;let m=n.attachments;if(!(m!=null&&m.enabled))return;let y=l.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 D=l.querySelector("[data-persona-composer-form]");D!=null&&D.parentNode?D.parentNode.insertBefore(y,D):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let D=h("input");D.type="file",D.accept=((A=m.allowedTypes)!=null?A:ir).join(","),D.multiple=((L=m.maxFiles)!=null?L:4)>1,D.style.display="none",D.setAttribute("aria-label",(H=m.buttonTooltipText)!=null?H:"Attach files"),l.appendChild(D)}},Un=s.find(l=>l.renderComposer);if(Un!=null&&Un.renderComposer){let l=n.composer,m=Un.renderComposer({config:n,defaultRenderer:()=>Ko({config:n}).footer,onSubmit:y=>{var D;if(!O||O.isStreaming())return;let A=y.trim(),L=(D=qe==null?void 0:qe.hasAttachments())!=null?D:!1;if(!A&&!L)return;let H;L&&(H=[],H.push(...qe.getContentParts()),A&&H.push(Es(A))),O.sendMessage(A,{contentParts:H}),L&&qe.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Pe==null||Pe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((li=n.voiceRecognition)==null?void 0:li.enabled)===!0?()=>{zt==null||zt()}:void 0});m&&(X.replaceWith(m),X=m)}let Mr=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),H=l.querySelector("[data-persona-composer-status]");m&&(mt=m),y&&(ee=y),A&&(le=A),L&&(I=L,te=L.parentElement),H&&(ze=H);let D=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");D&&(Je=D);let V=l.querySelector(".persona-attachment-button");V&&(Z=V,Ye=V.parentElement),Pe=l.querySelector('input[type="file"]'),ne=l.querySelector(".persona-attachment-previews");let _=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");_&&(Se=_)};Tr(X),Mr(X);let Tn=(ci=n.layout)==null?void 0:ci.contentMaxWidth;if(Tn&&mt&&(mt.style.maxWidth=Tn,mt.style.marginLeft="auto",mt.style.marginRight="auto"),Tn&&Je&&(Je.style.maxWidth=Tn,Je.style.marginLeft="auto",Je.style.marginRight="auto"),Tn&&ne&&(ne.style.maxWidth=Tn,ne.style.marginLeft="auto",ne.style.marginRight="auto"),(di=n.attachments)!=null&&di.enabled&&Pe&&ne){qe=ro.fromConfig(n.attachments),qe.setPreviewsContainer(ne),Pe.addEventListener("change",y=>{let A=y.target;qe==null||qe.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=Ad(l);F.appendChild(m)}(()=>{var A,L;let l=(L=(A=n.layout)==null?void 0:A.slots)!=null?L:{},m=H=>{switch(H){case"body-top":return F.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return me;case"footer-top":return Je;case"composer":return mt;case"footer-bottom":return ze;default:return null}},y=(H,D)=>{var V;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")W.insertBefore(D,W.firstChild);else if(H==="header-right")W.appendChild(D);else{let _=W.querySelector(".persona-flex-col");_?(V=_.parentNode)==null||V.insertBefore(D,_.nextSibling):W.appendChild(D)}break;case"body-top":{let _=U.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(D):U.insertBefore(D,U.firstChild);break}case"body-bottom":U.appendChild(D);break;case"footer-top":Je.replaceWith(D);break;case"footer-bottom":ze.replaceWith(D);break;default:break}};for(let[H,D]of Object.entries(l))if(D)try{let V=D({config:n,defaultContent:()=>m(H)});V&&y(H,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,V)}})();let cr=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let H=y.getAttribute("data-bubble-type");H==="reasoning"?(ao.has(L)?ao.delete(L):ao.add(L),id(L,A)):H==="tool"&&(io.has(L)?io.delete(L):io.add(L),ld(L,A,n)),kn.delete(L)};me.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cr(l))}),me.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cr(l))});let Zn=new Map;me.addEventListener("click",l=>{var D;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let H=y.getAttribute("data-action");if(H==="copy"){let _=O.getMessages().find(be=>be.id===L);if(_&&Me.onCopy){let be=_.content||"";navigator.clipboard.writeText(be).then(()=>{y.classList.add("persona-message-action-success");let xe=fe("check",14,"currentColor",2);xe&&(y.innerHTML="",y.appendChild(xe)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Ae=fe("copy",14,"currentColor",2);Ae&&(y.innerHTML="",y.appendChild(Ae))},2e3)}).catch(xe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",xe)}),Me.onCopy(_)}}else if(H==="upvote"||H==="downvote"){let _=((D=Zn.get(L))!=null?D:null)===H,be=H==="upvote"?"thumbs-up":"thumbs-down";if(_){Zn.delete(L),y.classList.remove("persona-message-action-active");let xe=fe(be,14,"currentColor",2);xe&&(y.innerHTML="",y.appendChild(xe))}else{let xe=H==="upvote"?"downvote":"upvote",Ae=A.querySelector(`[data-action="${xe}"]`);if(Ae){Ae.classList.remove("persona-message-action-active");let Qe=fe(xe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Qe&&(Ae.innerHTML="",Ae.appendChild(Qe))}Zn.set(L,H),y.classList.add("persona-message-action-active");let Ee=fe(be,14,"currentColor",2);Ee&&(Ee.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(Ee)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ke=O.getMessages().find(ut=>ut.id===L);Ke&&Me.onFeedback&&Me.onFeedback({type:H,messageId:Ke.id,message:Ke})}}}),me.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".persona-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let H=y.getAttribute("data-approval-action");if(!H)return;let D=H==="approve"?"approved":"denied",_=O.getMessages().find(xe=>xe.id===L);if(!(_!=null&&_.approval))return;let be=A.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(Ae=>{Ae.disabled=!0,Ae.style.opacity="0.5",Ae.style.cursor="not-allowed"}),O.resolveApproval(_.approval,D)});let pt=null,bn=null,Hn={artifacts:[],selectedId:null},on=!1,dr={current:null};me.addEventListener("click",l=>{var Ae,Ee,De,Ke,ut;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((De=(Ee=(Ae=n.features)==null?void 0:Ae.artifacts)==null?void 0:Ee.onArtifactAction)==null?void 0:De.call(Ee,{type:"download",artifactId:A}))===!0)return;let H=O.getArtifactById(A),D=H==null?void 0:H.markdown,V=(H==null?void 0:H.title)||"artifact";if(!D){let Qe=y.closest("[data-open-artifact]"),z=Qe==null?void 0:Qe.closest("[data-message-id]"),$e=z==null?void 0:z.getAttribute("data-message-id");if($e){let ve=O.getMessages().find(Ue=>Ue.id===$e);if(ve!=null&&ve.rawContent)try{let Ue=JSON.parse(ve.rawContent);D=(Ke=Ue==null?void 0:Ue.props)==null?void 0:Ke.markdown,V=((ut=Ue==null?void 0:Ue.props)==null?void 0:ut.title)||V}catch{}}}if(!D)return;let _=new Blob([D],{type:"text/markdown"}),be=URL.createObjectURL(_),xe=document.createElement("a");xe.href=be,xe.download=`${V}.md`,xe.click(),URL.revokeObjectURL(be)}),me.addEventListener("click",l=>{var H,D,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((V=(D=(H=n.features)==null?void 0:H.artifacts)==null?void 0:D.onArtifactAction)==null?void 0:V.call(D,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),on=!1,O.selectArtifact(A),vn())}),me.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let xn=null,At=null,sn=null,Mn=null,pr=()=>{};function Qn(){Mn==null||Mn(),Mn=null}let ur=()=>{var D;if(!xn||!At)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((D=e.ownerDocument.defaultView)!=null?D:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){At.style.removeProperty("position"),At.style.removeProperty("left"),At.style.removeProperty("top"),At.style.removeProperty("bottom"),At.style.removeProperty("width"),At.style.removeProperty("z-index");return}let A=xn.firstElementChild;if(!A||A===At)return;let L=10;At.style.position="absolute",At.style.top="0",At.style.bottom="0",At.style.width=`${L}px`,At.style.zIndex="5";let H=A.offsetWidth-L/2;At.style.left=`${Math.max(0,H)}px`},Vn=()=>{},vn=()=>{var y,A,L,H,D;if(!pt||!Wn(n))return;Os(e,n),$s(e,n),Vn();let l=(H=(L=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?H:520,m=q.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),pt.update(Hn),on?(pt.setMobileOpen(!1),pt.element.classList.add("persona-hidden"),(D=pt.backdrop)==null||D.classList.add("persona-hidden")):Hn.artifacts.length>0&&(pt.element.classList.remove("persona-hidden"),pt.setMobileOpen(!0)),pr()};if(Wn(n)){q.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(F),pt=md(n,{onSelect:y=>{var A;return(A=dr.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{on=!0,vn()}}),pt.element.classList.add("persona-hidden"),xn=m,m.appendChild(l),m.appendChild(pt.element),pt.backdrop&&q.appendChild(pt.backdrop),q.appendChild(m),pr=()=>{var A,L,H,D;if(!xn||!pt)return;if(!(((H=(L=(A=n.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:H.resizable)===!0)){sn==null||sn(),sn=null,Qn(),At&&(At.remove(),At=null),pt.element.style.removeProperty("width"),pt.element.style.removeProperty("maxWidth");return}if(!At){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let _=e.ownerDocument,be=(D=_.defaultView)!=null?D:window,xe=Ae=>{var z,$e;if(!pt||Ae.button!==0||e.classList.contains("persona-artifact-narrow-host")||be.innerWidth<=640)return;Ae.preventDefault(),Qn();let Ee=Ae.clientX,De=pt.element.getBoundingClientRect().width,Ke=($e=(z=n.features)==null?void 0:z.artifacts)==null?void 0:$e.layout,ut=je=>{let ve=xn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),St=Ue?0:yd(xn,be),Ct=Ue?0:V.getBoundingClientRect().width||6,Jt=De-(je.clientX-Ee),en=bd(Jt,ve,St,Ct,Ke==null?void 0:Ke.resizableMinWidth,Ke==null?void 0:Ke.resizableMaxWidth);pt.element.style.width=`${en}px`,pt.element.style.maxWidth="none",ur()},Qe=()=>{_.removeEventListener("pointermove",ut),_.removeEventListener("pointerup",Qe),_.removeEventListener("pointercancel",Qe),Mn=null;try{V.releasePointerCapture(Ae.pointerId)}catch{}};Mn=Qe,_.addEventListener("pointermove",ut),_.addEventListener("pointerup",Qe),_.addEventListener("pointercancel",Qe);try{V.setPointerCapture(Ae.pointerId)}catch{}};V.addEventListener("pointerdown",xe),At=V,xn.insertBefore(V,pt.element),sn=()=>{V.removeEventListener("pointerdown",xe)}}if(At){let V=Hn.artifacts.length>0&&!on;At.classList.toggle("persona-hidden",!V),ur()}},Vn=()=>{var be,xe,Ae,Ee,De,Ke,ut,Qe,z,$e,je,ve,Ue,St;if(!w||!pt||((xe=(be=n.launcher)==null?void 0:be.sidebarMode)!=null?xe:!1)||Yt(n)&&jn(n).reveal==="emerge")return;let A=(Ae=e.ownerDocument.defaultView)!=null?Ae:window,L=(De=(Ee=n.launcher)==null?void 0:Ee.mobileFullscreen)!=null?De:!0,H=(ut=(Ke=n.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?ut:640;if(L&&A.innerWidth<=H||!hd(n,w))return;let D=($e=(z=(Qe=n.launcher)==null?void 0:Qe.width)!=null?z:n.launcherWidth)!=null?$e:Pn,V=(St=(Ue=(ve=(je=n.features)==null?void 0:je.artifacts)==null?void 0:ve.layout)==null?void 0:Ue.expandedPanelWidth)!=null?St:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!on?(q.style.width=V,q.style.maxWidth=V):(q.style.width=D,q.style.maxWidth=D)},typeof ResizeObserver!="undefined"&&(bn=new ResizeObserver(()=>{vn()}),bn.observe(q))}else q.appendChild(F);e.appendChild(P);let Jn=()=>{var Ct,Jt,en,Re,un,tn,$n,dt,yt,mn,ar,et,Et,Br,Dr,us,ms,gs,ta,na,Ut,fs,Lo;let l=Yt(n),m=(Jt=(Ct=n.launcher)==null?void 0:Ct.sidebarMode)!=null?Jt:!1,y=l||m||((Re=(en=n.launcher)==null?void 0:en.fullHeight)!=null?Re:!1),A=((un=n.launcher)==null?void 0:un.enabled)===!1,L=($n=(tn=n.theme)==null?void 0:tn.components)==null?void 0:$n.panel,H=Ws(n),D=(gn,In)=>{var Xr;return gn==null||gn===""?In:(Xr=jo(H,gn))!=null?Xr:gn},V=(dt=e.ownerDocument.defaultView)!=null?dt:window,_=(mn=(yt=n.launcher)==null?void 0:yt.mobileFullscreen)!=null?mn:!0,be=(et=(ar=n.launcher)==null?void 0:ar.mobileBreakpoint)!=null?et:640,xe=V.innerWidth<=be,Ae=_&&xe&&w,Ee=(Br=(Et=n.launcher)==null?void 0:Et.position)!=null?Br:"bottom-left",De=Ee==="bottom-left"||Ee==="top-left",Ke=(us=(Dr=n.launcher)==null?void 0:Dr.zIndex)!=null?us:hn,ut=m||Ae?"none":"1px solid var(--persona-border)",Qe=Ae?"none":m?De?"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))";l&&!Ae&&(Qe="none",ut="none");let z=m||Ae?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",$e=D(L==null?void 0:L.border,ut),je=D(L==null?void 0:L.shadow,Qe),ve=D(L==null?void 0:L.borderRadius,z);if(e.style.cssText="",P.style.cssText="",q.style.cssText="",F.style.cssText="",U.style.cssText="",X.style.cssText="",Ae){P.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"),P.style.cssText=`
|
|
23
23
|
position: fixed !important;
|
|
24
24
|
inset: 0 !important;
|
|
25
25
|
width: 100% !important;
|
|
@@ -29,9 +29,9 @@ import{Marked as ap}from"marked";var ip=e=>{if(e)return e},ss=e=>{var s,o;let r=
|
|
|
29
29
|
padding: 0 !important;
|
|
30
30
|
display: flex !important;
|
|
31
31
|
flex-direction: column !important;
|
|
32
|
-
z-index: ${
|
|
32
|
+
z-index: ${Ke} !important;
|
|
33
33
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
34
|
-
`,
|
|
34
|
+
`,q.style.cssText=`
|
|
35
35
|
position: relative !important;
|
|
36
36
|
display: flex !important;
|
|
37
37
|
flex-direction: column !important;
|
|
@@ -44,7 +44,7 @@ import{Marked as ap}from"marked";var ip=e=>{if(e)return e},ss=e=>{var s,o;let r=
|
|
|
44
44
|
padding: 0 !important;
|
|
45
45
|
box-shadow: none !important;
|
|
46
46
|
border-radius: 0 !important;
|
|
47
|
-
`,
|
|
47
|
+
`,F.style.cssText=`
|
|
48
48
|
display: flex !important;
|
|
49
49
|
flex-direction: column !important;
|
|
50
50
|
flex: 1 1 0% !important;
|
|
@@ -55,20 +55,20 @@ import{Marked as ap}from"marked";var ip=e=>{if(e)return e},ss=e=>{var s,o;let r=
|
|
|
55
55
|
overflow: hidden !important;
|
|
56
56
|
border-radius: 0 !important;
|
|
57
57
|
border: none !important;
|
|
58
|
-
`,
|
|
58
|
+
`,U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",X.style.flexShrink="0",B=!0;return}let Ue=(gs=(ms=n==null?void 0:n.launcher)==null?void 0:ms.width)!=null?gs:n==null?void 0:n.launcherWidth,St=Ue!=null?Ue:Pn;if(!m&&!l)A&&y?(q.style.width="100%",q.style.maxWidth="100%"):(q.style.width=St,q.style.maxWidth=St);else if(l)if(jn(n).reveal==="emerge"){let In=jn(n).width;q.style.width=In,q.style.maxWidth=In}else q.style.width="100%",q.style.maxWidth="100%";if(Vn(),q.style.boxShadow=je,q.style.borderRadius=ve,F.style.border=$e,F.style.borderRadius=ve,l&&!Ae&&(L==null?void 0:L.border)===void 0&&(F.style.border="none",jn(n).side==="right"?F.style.borderLeft="1px solid var(--persona-border)":F.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),P.style.display="flex",P.style.flexDirection="column",P.style.flex="1 1 0%",P.style.minHeight="0",P.style.maxHeight="100%",P.style.height="100%",A&&(P.style.overflow="hidden"),q.style.display="flex",q.style.flexDirection="column",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.maxHeight="100%",q.style.height="100%",q.style.overflow="hidden",F.style.display="flex",F.style.flexDirection="column",F.style.flex="1 1 0%",F.style.minHeight="0",F.style.maxHeight="100%",F.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",X.style.flexShrink="0"),P.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"),!m&&!A&&!l&&((ta=zn[Ee])!=null?ta:zn["bottom-right"]).split(" ").forEach(In=>P.classList.add(In)),m){let gn=(Ut=(na=n.launcher)==null?void 0:na.sidebarWidth)!=null?Ut:"420px";P.style.cssText=`
|
|
59
59
|
position: fixed !important;
|
|
60
60
|
top: 0 !important;
|
|
61
61
|
bottom: 0 !important;
|
|
62
|
-
width: ${
|
|
62
|
+
width: ${gn} !important;
|
|
63
63
|
height: 100vh !important;
|
|
64
64
|
max-height: 100vh !important;
|
|
65
65
|
margin: 0 !important;
|
|
66
66
|
padding: 0 !important;
|
|
67
67
|
display: flex !important;
|
|
68
68
|
flex-direction: column !important;
|
|
69
|
-
z-index: ${
|
|
70
|
-
${
|
|
71
|
-
`,
|
|
69
|
+
z-index: ${Ke} !important;
|
|
70
|
+
${De?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
71
|
+
`,q.style.cssText=`
|
|
72
72
|
position: relative !important;
|
|
73
73
|
display: flex !important;
|
|
74
74
|
flex-direction: column !important;
|
|
@@ -79,9 +79,9 @@ import{Marked as ap}from"marked";var ip=e=>{if(e)return e},ss=e=>{var s,o;let r=
|
|
|
79
79
|
min-height: 0 !important;
|
|
80
80
|
margin: 0 !important;
|
|
81
81
|
padding: 0 !important;
|
|
82
|
-
box-shadow: ${
|
|
83
|
-
border-radius: ${
|
|
84
|
-
`,
|
|
82
|
+
box-shadow: ${je} !important;
|
|
83
|
+
border-radius: ${ve} !important;
|
|
84
|
+
`,q.style.setProperty("width","100%","important"),q.style.setProperty("max-width","100%","important"),F.style.cssText=`
|
|
85
85
|
display: flex !important;
|
|
86
86
|
flex-direction: column !important;
|
|
87
87
|
flex: 1 1 0% !important;
|
|
@@ -90,29 +90,29 @@ import{Marked as ap}from"marked";var ip=e=>{if(e)return e},ss=e=>{var s,o;let r=
|
|
|
90
90
|
min-height: 0 !important;
|
|
91
91
|
max-height: 100% !important;
|
|
92
92
|
overflow: hidden !important;
|
|
93
|
-
border-radius: ${
|
|
94
|
-
border: ${
|
|
95
|
-
`,
|
|
93
|
+
border-radius: ${ve} !important;
|
|
94
|
+
border: ${$e} !important;
|
|
95
|
+
`,X.style.cssText=`
|
|
96
96
|
flex-shrink: 0 !important;
|
|
97
97
|
border-top: none !important;
|
|
98
98
|
padding: 8px 16px 12px 16px !important;
|
|
99
|
-
`}if(!A&&!l){let un="max-height: -moz-available !important; max-height: stretch !important;",Ln=m?"":"padding-top: 1.25em !important;",Ur=m?"":`z-index: ${(yo=(ns=n.launcher)==null?void 0:ns.zIndex)!=null?yo:gn} !important;`;z.style.cssText+=un+Ln+Ur}};Vn(),Dr(e,n),Ts(e,n),Ms(e,n);let Ct=[],Bt=null,Dt=null;Ct.push(()=>{Bt==null||Bt(),Bt=null,Dt==null||Dt(),Dt=null}),hn&&Ct.push(()=>{hn==null||hn.disconnect(),hn=null}),Ct.push(()=>{rn==null||rn(),rn=null,Zn(),Et&&(Et.remove(),Et=null),it==null||it.element.style.removeProperty("width"),it==null||it.element.style.removeProperty("maxWidth")}),ae&&Ct.push(()=>{V!==null&&(cancelAnimationFrame(V),V=null),Z==null||Z.destroy(),Z=null,ie==null||ie.destroy(),ie=null,We=null});let xn=null,dr=()=>{xn&&(xn(),xn=null),n.colorScheme==="auto"&&(xn=ta(()=>{Dr(e,n)}))};dr(),Ct.push(()=>{xn&&(xn(),xn=null)});let Hn=ld(fe),vn=null,D,Bn=!1,Tn=Gc(),pr=0,an=vs(),ln=0,le=null,Cn=!1,Qn=!1,_o=4,ao=24,jo=80,Or=new Map,et={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},io=(pi=(di=n.voiceRecognition)==null?void 0:di.autoResume)!=null?pi:!1,Mn=l=>{o.emit("voice:state",{active:et.active,source:l,timestamp:Date.now()})},cn=()=>{f(l=>({...l,voiceState:{active:et.active,timestamp:Date.now(),manuallyDeactivated:et.manuallyDeactivated}}))},zo=()=>{var A,I;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Ca(i.voiceState),m=!!l.active,y=Number((I=l.timestamp)!=null?I:0);et.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<Ru&&setTimeout(()=>{var R,B;et.active||(et.manuallyDeactivated=!1,((B=(R=n.voiceRecognition)==null?void 0:R.provider)==null?void 0:B.type)==="runtype"?D.toggleVoice().then(()=>{et.active=D.isVoiceActive(),Mn("restore"),D.isVoiceActive()&&gr()}):Tr("restore"))},1e3)},qo=()=>D?Cd(D.getMessages()).filter(l=>!l.__skipPersist):[];function lo(l){if(!(a!=null&&a.save))return;let y={messages:l?Cd(l):D?qo():[],metadata:i};try{let A=a.save(y);A instanceof Promise&&A.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let er=null,Uo=()=>z.querySelector("#persona-scroll-container")||J,Sr=()=>{er!==null&&(cancelAnimationFrame(er),er=null),Cn=!1},co=()=>{le!==null&&(cancelAnimationFrame(le),le=null),Qn=!1,Sr()},tr=()=>{if(!Ot()||me){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==N&&N.appendChild(pt),Qe();let l=Wo(J)>0;pt.style.display=an.isFollowing()||!l?"none":""},po=()=>{an.pause()&&(co(),tr())},ur=()=>{an.resume(),tr()},mr=(l=!1)=>{an.isFollowing()&&(!l&&!Bn||(le!==null&&(cancelAnimationFrame(le),le=null),Qn=!0,le=requestAnimationFrame(()=>{le=null,Qn=!1,an.isFollowing()&&Vo(Uo(),l?220:140)})))},Vo=(l,m=500)=>{let y=l.scrollTop,A=Wo(l),I=A-y;if(Math.abs(I)<1){ln=l.scrollTop;return}if(Math.abs(I)>=jo){Sr(),Cn=!0,l.scrollTop=A,ln=l.scrollTop,Cn=!1;return}Sr();let R=performance.now();Cn=!0;let B=F=>1-Math.pow(1-F,3),G=F=>{if(!an.isFollowing()){Sr();return}let ve=Wo(l);ve!==A&&(A=ve,I=A-y);let Se=F-R,Me=Math.min(Se/m,1),ke=B(Me),Ne=y+I*ke;l.scrollTop=Ne,ln=l.scrollTop,Me<1?er=requestAnimationFrame(G):(l.scrollTop=A,ln=l.scrollTop,er=null,Cn=!1)};er=requestAnimationFrame(G)},Jo=l=>{let m=new Map;l.forEach(y=>{let A=Or.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Or.clear(),m.forEach((y,A)=>{Or.set(A,y)})},Ar=(l,m,y)=>{var Me,ke,Ne,Ue,lt,Ge;let A=document.createElement("div"),R=(()=>{var Oe;let _=s.find(_e=>_e.renderLoadingIndicator);if(_!=null&&_.renderLoadingIndicator)return _.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),B=(_,Oe)=>Oe==null?!1:typeof Oe=="string"?(_.textContent=Oe,!0):(_.appendChild(Oe),!0),G=new Set;if(m.forEach(_=>{var Ut,Xt;G.add(_.id);let Oe=Jc(_,pr),_e=Yc(Tn,_.id,Oe);if(_e){A.appendChild(_e.cloneNode(!0));return}let Ae=null,ze=s.find(Ie=>!!(_.variant==="reasoning"&&Ie.renderReasoning||_.variant==="tool"&&Ie.renderToolCall||_.variant==="approval"&&Ie.renderApproval||!_.variant&&Ie.renderMessage)),St=(Ut=n.layout)==null?void 0:Ut.messages;if(ze)if(_.variant==="reasoning"&&_.reasoning&&ze.renderReasoning){if(!oe)return;Ae=ze.renderReasoning({message:_,defaultRenderer:()=>aa(_,n),config:n})}else if(_.variant==="tool"&&_.toolCall&&ze.renderToolCall){if(!Ee)return;Ae=ze.renderToolCall({message:_,defaultRenderer:()=>ia(_,n),config:n})}else if(_.variant==="approval"&&_.approval&&ze.renderApproval){if(n.approval===!1)return;Ae=ze.renderApproval({message:_,defaultRenderer:()=>la(_,n),config:n})}else ze.renderMessage&&(Ae=ze.renderMessage({message:_,defaultRenderer:()=>{let Ie=Fo(_,y,St,n.messageActions,He,{loadingIndicatorRenderer:R,widgetConfig:n});return _.role!=="user"&&pa(Ie,_,n,D),Ie},config:n}));if(!Ae&&_.role==="assistant"&&!_.variant&&n.enableComponentStreaming!==!1&&ya(_)){let dn=ba(_);if(dn){let Qt=ha(dn,{config:n,message:_,transform:y});if(Qt)if(n.wrapComponentDirectiveInBubble!==!1){let ot=document.createElement("div");if(ot.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(" "),ot.id=`bubble-${_.id}`,ot.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let gt=document.createElement("div");gt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),ot.appendChild(gt)}ot.appendChild(Qt),Ae=ot}else{let ot=document.createElement("div");if(ot.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ot.id=`bubble-${_.id}`,ot.setAttribute("data-message-id",_.id),ot.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let gt=document.createElement("div");gt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),ot.appendChild(gt)}ot.appendChild(Qt),Ae=ot}}}if(!Ae)if(_.variant==="reasoning"&&_.reasoning){if(!oe)return;Ae=aa(_,n)}else if(_.variant==="tool"&&_.toolCall){if(!Ee)return;Ae=ia(_,n)}else if(_.variant==="approval"&&_.approval){if(n.approval===!1)return;Ae=la(_,n)}else{let Ie=(Xt=n.layout)==null?void 0:Xt.messages;Ie!=null&&Ie.renderUserMessage&&_.role==="user"?Ae=Ie.renderUserMessage({message:_,config:n,streaming:!!_.streaming}):Ie!=null&&Ie.renderAssistantMessage&&_.role==="assistant"?Ae=Ie.renderAssistantMessage({message:_,config:n,streaming:!!_.streaming}):Ae=Fo(_,y,Ie,n.messageActions,He,{loadingIndicatorRenderer:R,widgetConfig:n}),_.role!=="user"&&Ae&&pa(Ae,_,n,D)}let xt=document.createElement("div");xt.className="persona-flex",xt.id=`wrapper-${_.id}`,xt.setAttribute("data-wrapper-id",_.id),_.role==="user"&&xt.classList.add("persona-justify-end"),(Ae==null?void 0:Ae.getAttribute("data-persona-component-directive"))==="true"&&xt.classList.add("persona-w-full"),xt.appendChild(Ae),Kc(Tn,_.id,Oe,xt),A.appendChild(xt)}),(ke=(Me=n.features)==null?void 0:Me.toolCallDisplay)!=null&&ke.grouped){let _=[],Oe=[];m.forEach(_e=>{if(_e.variant==="tool"&&_e.toolCall&&Ee){Oe.push(_e);return}Oe.length>1&&_.push(Oe),Oe=[]}),Oe.length>1&&_.push(Oe),_.forEach((_e,Ae)=>{var Qt,On;let ze=_e.map(ot=>Array.from(A.children).find(gt=>gt instanceof HTMLElement&>.getAttribute("data-wrapper-id")===ot.id)).filter(ot=>!!ot);if(ze.length<2)return;let St=document.createElement("div");St.className="persona-flex",St.id=`wrapper-tool-group-${Ae}-${_e[0].id}`,St.setAttribute("data-wrapper-id",`tool-group-${Ae}-${_e[0].id}`);let xt=document.createElement("div");xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",xt.setAttribute("data-persona-tool-group","true");let Ut=document.createElement("div");Ut.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Xt=`Called ${_e.length} tools`,Ie=(On=(Qt=n.toolCall)==null?void 0:Qt.renderGroupedSummary)==null?void 0:On.call(Qt,{messages:_e,toolCalls:_e.map(ot=>ot.toolCall).filter(ot=>!!ot),defaultSummary:Xt,config:n});B(Ut,Ie)||(Ut.textContent=Xt);let dn=document.createElement("div");dn.className="persona-tool-group-stack persona-flex persona-flex-col",xt.append(Ut,dn),St.appendChild(xt),ze[0].before(St),ze.forEach((ot,gt)=>{let pn=document.createElement("div");pn.className="persona-tool-group-item persona-relative",pn.setAttribute("data-persona-tool-group-item","true"),gt<ze.length-1&&pn.setAttribute("data-persona-tool-group-connector","true"),pn.appendChild(ot),dn.appendChild(pn)})})}Xc(Tn,G);let F=m.some(_=>_.role==="assistant"&&_.streaming),ve=m[m.length-1],Se=(ve==null?void 0:ve.role)==="assistant"&&!ve.streaming&&ve.variant!=="approval";if(Bn&&m.some(_=>_.role==="user")&&!F&&!Se){let _={config:n,streaming:!0,location:"standalone",defaultRenderer:Qr},Oe=s.find(Ae=>Ae.renderLoadingIndicator),_e=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(_e=Oe.renderLoadingIndicator(_)),_e===null&&((Ne=n.loadingIndicator)!=null&&Ne.render)&&(_e=n.loadingIndicator.render(_)),_e===null&&(_e=Qr()),_e){let Ae=document.createElement("div"),ze=((Ue=n.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;Ae.className=ze?["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(" "),Ae.setAttribute("data-typing-indicator","true"),Ae.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ae.appendChild(_e);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-typing-indicator",St.setAttribute("data-wrapper-id","typing-indicator"),St.appendChild(Ae),A.appendChild(St)}}if(!Bn&&m.length>0){let _=m[m.length-1],Oe={config:n,lastMessage:_,messageCount:m.length},_e=s.find(ze=>ze.renderIdleIndicator),Ae=null;if(_e!=null&&_e.renderIdleIndicator&&(Ae=_e.renderIdleIndicator(Oe)),Ae===null&&((lt=n.loadingIndicator)!=null&<.renderIdle)&&(Ae=n.loadingIndicator.renderIdle(Oe)),Ae){let ze=document.createElement("div"),St=((Ge=n.loadingIndicator)==null?void 0:Ge.showBubble)!==!1;ze.className=St?["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(" "),ze.setAttribute("data-idle-indicator","true"),ze.appendChild(Ae);let xt=document.createElement("div");xt.className="persona-flex",xt.id="wrapper-idle-indicator",xt.setAttribute("data-wrapper-id","idle-indicator"),xt.appendChild(ze),A.appendChild(xt)}}Vc(l,A)},Er=()=>{var F,ve,Se,Me,ke;if(!C)return;let l=Kt(n),m=(F=e.ownerDocument.defaultView)!=null?F:window,y=(Se=(ve=n.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Se:640,A=(ke=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?ke:!0,I=m.innerWidth<=y,R=A&&I&&C,B=_n(n).reveal;E?(z.style.removeProperty("display"),z.style.display=l?"flex":"",z.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-95","persona-opacity-0"),U.classList.add("persona-scale-100","persona-opacity-100"),b?b.element.style.display="none":k&&(k.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!R?(z.style.removeProperty("display"),z.style.display="flex",z.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(z.style.setProperty("display","none","important"),z.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(z.style.display="",z.classList.add("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100"),U.classList.add("persona-scale-95","persona-opacity-0")),b?b.element.style.display=l?"none":"":k&&(k.style.display=l?"none":""))},It=(l,m="user")=>{var R,B;if(!C||E===l)return;let y=E;E=l,Er();let A=(()=>{var Ne,Ue,lt,Ge,_,Oe,_e;let G=(Ue=(Ne=n.launcher)==null?void 0:Ne.sidebarMode)!=null?Ue:!1,F=(lt=e.ownerDocument.defaultView)!=null?lt:window,ve=(_=(Ge=n.launcher)==null?void 0:Ge.mobileFullscreen)!=null?_:!0,Se=(_e=(Oe=n.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?_e:640,Me=F.innerWidth<=Se,ke=Kt(n)&&ve&&Me;return G||ve&&Me&&C||ke})();if(E&&A){if(!Bt){let G=e.getRootNode(),F=G instanceof ShadowRoot?G.host:e.closest(".persona-host");F&&(Bt=na(F,(B=(R=n.launcher)==null?void 0:R.zIndex)!=null?B:gn))}Dt||(Dt=ra(e.ownerDocument))}else E||(Bt==null||Bt(),Bt=null,Dt==null||Dt(),Dt=null);E&&(v(),mr(!0));let I={open:E,source:m,timestamp:Date.now()};E&&!y?o.emit("widget:opened",I):!E&&y&&o.emit("widget:closed",I),o.emit("widget:state",{open:E,launcherEnabled:C,voiceActive:et.active,streaming:D.isStreaming()})},$r=l=>{pe.disabled=l,j&&(j.disabled=l),Hn.buttons.forEach(m=>{m.disabled=l}),be.dataset.personaComposerStreaming=l?"true":"false",be.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},_r=()=>{et.active||te&&te.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>_r(),200)});let uo=()=>{var y,A,I,R,B,G,F,ve,Se,Me,ke;Jt.textContent=(A=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}",P.textContent=(R=(I=n.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",te.placeholder=(G=(B=n.copy)==null?void 0:B.inputPlaceholder)!=null?G:"How can I help...";let l=J.querySelector("[data-persona-intro-card]");if(l){let Ne=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;l.style.display=Ne?"":"none",Ne?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}(Se=(ve=n.sendButton)==null?void 0:ve.useIcon)!=null&&Se||(pe.textContent=(ke=(Me=n.copy)==null?void 0:Me.sendButtonLabel)!=null?ke:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let Jn=null,Go=()=>{Jn==null&&(Jn=setInterval(()=>{let l=ce.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Jn),Jn=null;return}let m=Date.now();l.forEach(y=>{let A=Number(y.getAttribute("data-tool-elapsed"));A&&(y.textContent=is(m-A))})},100))};if(D=new ko(n,{onMessagesChanged(l){Ar(ce,l,O),Go(),D&&(l.some(I=>I.role==="user")?Hn.render([],D,te,l):Hn.render(n.suggestionChips,D,te,l,n.suggestionChipsConfig)),mr(!Bn),Jo(l);let m=[...l].reverse().find(A=>A.role==="user"),y=et.lastUserMessageId;m&&m.id!==y&&(et.lastUserMessageId=m.id,o.emit("user:message",m)),et.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),lo(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};st(Wt,(I=>{var R,B,G,F;return I==="idle"?(R=m.idleText)!=null?R:tn.idle:I==="connecting"?(B=m.connectingText)!=null?B:tn.connecting:I==="connected"?(G=m.connectedText)!=null?G:tn.connected:I==="error"?(F=m.errorText)!=null?F:tn.error:tn[I]})(l),m,l)},onStreamingChanged(l){Bn=l,$r(l),D&&Ar(ce,D.getMessages(),O),l||mr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":Nn(),Ko();break;case"speaking":Nn(),Xo();break;default:l==="idle"&&D.isBargeInActive()?(Nn(),gr(),j==null||j.setAttribute("aria-label","End voice session")):(et.active=!1,Nn(),Mn("system"),cn());break}},onArtifactsState(l){Rn=l,bn()}}),ir.current=D,((mi=(ui=n.voiceRecognition)==null?void 0:ui.provider)==null?void 0:mi.type)==="runtype")try{D.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&D.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ie||n.onSSEEvent)&&D.setSSEEventCallback((l,m)=>{var y;(y=n.onSSEEvent)==null||y.call(n,l,m),ie==null||ie.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=Ca(l.metadata),T.syncFromMetadata()),(m=l.messages)!=null&&m.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let mo=l=>{var I;l.preventDefault();let m=te.value.trim(),y=(I=je==null?void 0:je.hasAttachments())!=null?I:!1;if(!m&&!y)return;let A;y&&(A=[],A.push(...je.getContentParts()),m&&A.push(us(m))),te.value="",te.style.height="auto",D.sendMessage(m,{contentParts:A}),y&&je.clearAttachments()},go=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),pe.click())},fo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!je)return;let m=Bu(l.clipboardData);m.length!==0&&(l.preventDefault(),await je.handleFiles(m))},on=null,wn=!1,nr=null,Je=null,ho=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Tr=(l="user")=>{var R,B,G,F,ve,Se,Me;if(wn||D.isStreaming())return;let m=ho();if(!m)return;on=new m;let A=(B=((R=n.voiceRecognition)!=null?R:{}).pauseDuration)!=null?B:2e3;on.continuous=!0,on.interimResults=!0,on.lang="en-US";let I=te.value;on.onresult=ke=>{let Ne="",Ue="";for(let Ge=0;Ge<ke.results.length;Ge++){let _=ke.results[Ge],Oe=_[0].transcript;_.isFinal?Ne+=Oe+" ":Ue=Oe}let lt=I+Ne+Ue;te.value=lt,nr&&clearTimeout(nr),(Ne||Ue)&&(nr=window.setTimeout(()=>{let Ge=te.value.trim();Ge&&on&&wn&&(Dn(),te.value="",te.style.height="auto",D.sendMessage(Ge,{viaVoice:!0}))},A))},on.onerror=ke=>{ke.error!=="no-speech"&&Dn()},on.onend=()=>{if(wn){let ke=te.value.trim();ke&&ke!==I.trim()&&(te.value="",te.style.height="auto",D.sendMessage(ke,{viaVoice:!0})),Dn()}};try{if(on.start(),wn=!0,et.active=!0,l!=="system"&&(et.manuallyDeactivated=!1),Mn(l),cn(),j){let ke=(G=n.voiceRecognition)!=null?G:{};Je={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(F=ke.iconName)!=null?F:"mic",iconSize:parseFloat((Me=(Se=ke.iconSize)!=null?Se:(ve=n.sendButton)==null?void 0:ve.size)!=null?Me:"40")||24};let Ne=ke.recordingBackgroundColor,Ue=ke.recordingIconColor,lt=ke.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=Ue!=null?Ue:"var(--persona-voice-recording-indicator, #ffffff)",Ue){let Ge=j.querySelector("svg");Ge&&Ge.setAttribute("stroke",Ue)}lt&&(j.style.borderColor=lt),j.setAttribute("aria-label","Stop voice recognition")}}catch{Dn("system")}},Dn=(l="user")=>{if(wn){if(wn=!1,nr&&(clearTimeout(nr),nr=null),on){try{on.stop()}catch{}on=null}if(et.active=!1,Mn(l),cn(),j){if(j.classList.remove("persona-voice-recording"),Je){j.style.backgroundColor=Je.backgroundColor,j.style.color=Je.color,j.style.borderColor=Je.borderColor;let m=j.querySelector("svg");m&&m.setAttribute("stroke",Je.color||"currentColor"),Je=null}j.setAttribute("aria-label","Start voice recognition")}}},Yo=(l,m)=>{var _,Oe,_e,Ae,ze,St,xt,Ut;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((_=l==null?void 0:l.provider)==null?void 0:_.type)==="runtype";if(!(y||A))return null;let R=h("div","persona-send-button-wrapper"),B=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let G=(Oe=l==null?void 0:l.iconName)!=null?Oe:"mic",F=(_e=m==null?void 0:m.size)!=null?_e:"40px",ve=(Ae=l==null?void 0:l.iconSize)!=null?Ae:F,Se=parseFloat(ve)||24,Me=(ze=l==null?void 0:l.backgroundColor)!=null?ze:m==null?void 0:m.backgroundColor,ke=(St=l==null?void 0:l.iconColor)!=null?St:m==null?void 0:m.textColor;B.style.width=ve,B.style.height=ve,B.style.minWidth=ve,B.style.minHeight=ve,B.style.fontSize="18px",B.style.lineHeight="1",ke?B.style.color=ke:B.style.color="var(--persona-text, #111827)";let Ue=ye(G,Se,ke||"currentColor",1.5);Ue?B.appendChild(Ue):B.textContent="\u{1F3A4}",Me?B.style.backgroundColor=Me:B.style.backgroundColor="",l!=null&&l.borderWidth&&(B.style.borderWidth=l.borderWidth,B.style.borderStyle="solid"),l!=null&&l.borderColor&&(B.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(B.style.paddingLeft=l.paddingX,B.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(B.style.paddingTop=l.paddingY,B.style.paddingBottom=l.paddingY),R.appendChild(B);let lt=(xt=l==null?void 0:l.tooltipText)!=null?xt:"Start voice recognition";if(((Ut=l==null?void 0:l.showTooltip)!=null?Ut:!1)&<){let Xt=h("div","persona-send-button-tooltip");Xt.textContent=lt,R.appendChild(Xt)}return{micButton:B,micButtonWrapper:R}},jr=()=>{var m,y,A,I,R;if(!j||Je)return;let l=(m=n.voiceRecognition)!=null?m:{};Je={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((R=(I=l.iconSize)!=null?I:(A=n.sendButton)==null?void 0:A.size)!=null?R:"40")||24}},zr=(l,m)=>{var R,B,G,F,ve;if(!j)return;let y=j.querySelector("svg");y&&y.remove();let A=(ve=Je==null?void 0:Je.iconSize)!=null?ve:parseFloat((F=(G=(R=n.voiceRecognition)==null?void 0:R.iconSize)!=null?G:(B=n.sendButton)==null?void 0:B.size)!=null?F:"40")||24,I=ye(l,A,m,1.5);I&&j.appendChild(I)},Mr=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},gr=()=>{var I;if(!j)return;jr();let l=(I=n.voiceRecognition)!=null?I:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,A=l.recordingBorderColor;if(Mr(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let R=j.querySelector("svg");R&&R.setAttribute("stroke",y)}A&&(j.style.borderColor=A),j.setAttribute("aria-label","Stop voice recognition")},Ko=()=>{var G,F,ve,Se,Me,ke,Ne,Ue;if(!j)return;jr();let l=(G=n.voiceRecognition)!=null?G:{},m=D.getVoiceInterruptionMode(),y=(F=l.processingIconName)!=null?F:"loader",A=(Se=(ve=l.processingIconColor)!=null?ve:Je==null?void 0:Je.color)!=null?Se:"",I=(ke=(Me=l.processingBackgroundColor)!=null?Me:Je==null?void 0:Je.backgroundColor)!=null?ke:"",R=(Ue=(Ne=l.processingBorderColor)!=null?Ne:Je==null?void 0:Je.borderColor)!=null?Ue:"";Mr(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=I,j.style.borderColor=R;let B=A||"currentColor";j.style.color=B,zr(y,B),j.setAttribute("aria-label","Processing voice input"),m==="none"&&(j.style.cursor="default")},Xo=()=>{var ve,Se,Me,ke,Ne,Ue,lt,Ge,_,Oe,_e,Ae;if(!j)return;jr();let l=(ve=n.voiceRecognition)!=null?ve:{},m=D.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(Se=l.speakingIconName)!=null?Se:y,I=(Ue=l.speakingIconColor)!=null?Ue:m==="barge-in"?(ke=(Me=l.recordingIconColor)!=null?Me:Je==null?void 0:Je.color)!=null?ke:"":(Ne=Je==null?void 0:Je.color)!=null?Ne:"",R=(_=l.speakingBackgroundColor)!=null?_:m==="barge-in"?(lt=l.recordingBackgroundColor)!=null?lt:"var(--persona-voice-recording-bg, #ef4444)":(Ge=Je==null?void 0:Je.backgroundColor)!=null?Ge:"",B=(Ae=l.speakingBorderColor)!=null?Ae:m==="barge-in"?(Oe=l.recordingBorderColor)!=null?Oe:"":(_e=Je==null?void 0:Je.borderColor)!=null?_e:"";Mr(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=R,j.style.borderColor=B;let G=I||"currentColor";j.style.color=G,zr(A,G);let F=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",F),m==="none"&&(j.style.cursor="default"),m==="barge-in"&&j.classList.add("persona-voice-recording")},Nn=()=>{var l,m,y;j&&(Mr(),Je&&(j.style.backgroundColor=(l=Je.backgroundColor)!=null?l:"",j.style.color=(m=Je.color)!=null?m:"",j.style.borderColor=(y=Je.borderColor)!=null?y:"",zr(Je.iconName,Je.color||"currentColor"),Je=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},kr=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=D.getVoiceStatus(),A=D.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{et.active=!1,et.manuallyDeactivated=!0,cn(),Mn("user"),Nn()});return}D.toggleVoice().then(()=>{et.active=D.isVoiceActive(),et.manuallyDeactivated=!D.isVoiceActive(),cn(),Mn("user"),D.isVoiceActive()?gr():Nn()});return}if(wn){let y=te.value.trim();et.manuallyDeactivated=!0,cn(),Dn("user"),y&&(te.value="",te.style.height="auto",D.sendMessage(y))}else et.manuallyDeactivated=!1,cn(),Tr("user")};_t=kr,j&&(j.addEventListener("click",kr),Ct.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),Nn()):Dn("system"),j&&j.removeEventListener("click",kr)}));let Zo=o.on("assistant:complete",()=>{io&&(et.active||et.manuallyDeactivated||io==="assistant"&&!et.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!et.active&&!et.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.toggleVoice().then(()=>{et.active=D.isVoiceActive(),Mn("auto"),D.isVoiceActive()&&gr()}):Tr("auto"))},600))});Ct.push(Zo);let qr=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});Ct.push(qr);let De=()=>{It(!E,"user")},b=null,k=null;if(C){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>Bo(n,De).element,onToggle:De});m&&(k=m)}k||(b=Bo(n,De))}b?e.appendChild(b.element):k&&e.appendChild(k),Er(),Hn.render(n.suggestionChips,D,te,void 0,n.suggestionChipsConfig),uo(),$r(D.isStreaming()),mr(!0),zo(),M&&(C?E&&setTimeout(()=>_r(),200):setTimeout(()=>_r(),0));let v=()=>{var F,ve,Se,Me,ke,Ne,Ue,lt,Ge,_,Oe,_e,Ae,ze,St,xt,Ut,Xt,Ie,dn,Qt,On;let l=Kt(n),m=(ve=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?ve:!1,y=l||m||((Me=(Se=n.launcher)==null?void 0:Se.fullHeight)!=null?Me:!1),A=(ke=e.ownerDocument.defaultView)!=null?ke:window,I=(Ue=(Ne=n.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ue:!0,R=(Ge=(lt=n.launcher)==null?void 0:lt.mobileBreakpoint)!=null?Ge:640,B=A.innerWidth<=R,G=I&&B&&C;try{if(G){Vn(),Dr(e,n);return}if(W&&(W=!1,Vn(),Dr(e,n)),!C&&!l){U.style.height="",U.style.width="";return}if(!m&&!l){let ot=(Oe=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?Oe:n==null?void 0:n.launcherWidth,gt=ot!=null?ot:In;U.style.width=gt,U.style.maxWidth=gt}if(Un(),!y){let ot=A.innerHeight,gt=64,pn=(Ae=(_e=n.launcher)==null?void 0:_e.heightOffset)!=null?Ae:0,rr=Math.max(200,ot-gt),Ye=Math.min(640,rr),Tt=Math.max(200,Ye-pn);U.style.height=`${Tt}px`}}finally{if(Qe(),Er(),E&&C){let gt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((xt=(St=n.launcher)==null?void 0:St.mobileBreakpoint)!=null?xt:640),pn=(Xt=(Ut=n.launcher)==null?void 0:Ut.sidebarMode)!=null?Xt:!1,rr=(dn=(Ie=n.launcher)==null?void 0:Ie.mobileFullscreen)!=null?dn:!0,Ye=Kt(n)&&rr&>,Tt=pn||rr&>&&C||Ye;if(Tt&&!Dt){let Lr=e.getRootNode(),Ir=Lr instanceof ShadowRoot?Lr.host:e.closest(".persona-host");Ir&&!Bt&&(Bt=na(Ir,(On=(Qt=n.launcher)==null?void 0:Qt.zIndex)!=null?On:gn)),Dt=ra(e.ownerDocument)}else Tt||(Bt==null||Bt(),Bt=null,Dt==null||Dt(),Dt=null)}}};v();let ee=(gi=e.ownerDocument.defaultView)!=null?gi:window;if(ee.addEventListener("resize",v),Ct.push(()=>ee.removeEventListener("resize",v)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Qe()});l.observe(be),Ct.push(()=>l.disconnect())}ln=J.scrollTop;let q=()=>{let l=J.scrollTop,{action:m,nextLastScrollTop:y}=Cs({following:an.isFollowing(),currentScrollTop:l,lastScrollTop:ln,nearBottom:Ro(J,ao),userScrollThreshold:_o,isAutoScrolling:Cn||Qn,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=y,m==="resume"){ur();return}m==="pause"&&po()};J.addEventListener("scroll",q,{passive:!0}),Ct.push(()=>J.removeEventListener("scroll",q));let Le=l=>{let m=ws({following:an.isFollowing(),deltaY:l.deltaY,nearBottom:Ro(J,ao),resumeWhenNearBottom:!0});m==="pause"?po():m==="resume"&&ur()};J.addEventListener("wheel",Le,{passive:!0}),Ct.push(()=>J.removeEventListener("wheel",Le)),pt.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,ln=J.scrollTop,ur(),mr(!0)}),Ct.push(()=>pt.remove()),Ct.push(()=>{co()});let Xe=()=>{$&&(vn&&($.removeEventListener("click",vn),vn=null),C?($.style.display="",vn=()=>{It(!1,"user")},$.addEventListener("click",vn)):$.style.display="none")};Xe(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{D.clearMessages(),Tn.clear(),ur();try{localStorage.removeItem(oo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${oo}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==oo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},T.syncFromMetadata(),ie==null||ie.clear(),Z==null||Z.update()})})(),dt&&dt.addEventListener("submit",mo),te==null||te.addEventListener("keydown",go),te==null||te.addEventListener("paste",fo);let wt="persona-attachment-drop-active",Gt=0,Ht=()=>{Gt=0,N.classList.remove(wt)},Zt=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&je!==null},rt=l=>{!Ps(l.dataTransfer)||!Zt()||(Gt++,Gt===1&&N.classList.add(wt))},ut=l=>{!Ps(l.dataTransfer)||!Zt()||(Gt--,Gt<=0&&Ht())},zt=l=>{!Ps(l.dataTransfer)||!Zt()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Fn=l=>{var y;if(!Ps(l.dataTransfer)||!Zt())return;l.preventDefault(),l.stopPropagation(),Ht();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&je.handleFiles(m)},bt=!0;N.addEventListener("dragenter",rt,bt),N.addEventListener("dragleave",ut,bt),e.addEventListener("dragover",zt,bt),e.addEventListener("drop",Fn,bt);let Nt=e.ownerDocument,Ra=l=>{Zt()&&l.preventDefault()},Ha=l=>{Zt()&&l.preventDefault()};Nt.addEventListener("dragover",Ra),Nt.addEventListener("drop",Ha),Ct.push(()=>{dt&&dt.removeEventListener("submit",mo),te==null||te.removeEventListener("keydown",go),te==null||te.removeEventListener("paste",fo)}),Ct.push(()=>{N.removeEventListener("dragenter",rt,bt),N.removeEventListener("dragleave",ut,bt),e.removeEventListener("dragover",zt,bt),e.removeEventListener("drop",Fn,bt),Nt.removeEventListener("dragover",Ra),Nt.removeEventListener("drop",Ha),Ht()}),Ct.push(()=>{D.cancel()}),b?Ct.push(()=>{b==null||b.destroy()}):k&&Ct.push(()=>{k==null||k.remove()});let qt={update(l){var Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Fi,Oi,$i,_i,ji,zi,qi,Ui,Vi,Ji,Gi,Yi,Ki,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,zl,ql,Ul,Vl,Jl,Gl,Yl,Kl,Xl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc;let m=n.toolCall,y=n.messageActions,A=(Ci=n.layout)==null?void 0:Ci.messages,I=n.colorScheme,R=n.loadingIndicator,B=n.iterationDisplay,G=(wi=n.features)==null?void 0:wi.showReasoning,F=(Si=n.features)==null?void 0:Si.showToolCalls,ve=(Ai=n.features)==null?void 0:Ai.toolCallDisplay,Se=(Ei=n.features)==null?void 0:Ei.reasoningDisplay;n={...n,...l},Vn(),Dr(e,n),Ts(e,n),Ms(e,n),bn(),n.colorScheme!==I&&dr();let Me=ks.getForInstance(n.plugins);s.length=0,s.push(...Me),C=(Mi=(Ti=n.launcher)==null?void 0:Ti.enabled)!=null?Mi:!0,S=(Li=(ki=n.launcher)==null?void 0:ki.autoExpand)!=null?Li:!1,oe=(Pi=(Ii=n.features)==null?void 0:Ii.showReasoning)!=null?Pi:!0,Ee=(Ri=(Wi=n.features)==null?void 0:Wi.showToolCalls)!=null?Ri:!0,we=(Bi=(Hi=n.features)==null?void 0:Hi.scrollToBottom)!=null?Bi:{},yt(),tr();let ke=ae;if(ae=(Ni=(Di=n.features)==null?void 0:Di.showEventStreamToggle)!=null?Ni:!1,ae&&!ke){if(ie||(We=new $o(he),ie=new Oo(Re,We),We.open().then(()=>ie==null?void 0:ie.restore()).catch(()=>{}),D.setSSEEventCallback((Y,ct)=>{var Mt;(Mt=n.onSSEEvent)==null||Mt.call(n,Y,ct),ie.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(ct)})})),!tt&&Ce){let Y=(Oi=(Fi=n.features)==null?void 0:Fi.eventStream)==null?void 0:Oi.classNames,ct="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"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");tt=h("button",ct),tt.style.width="28px",tt.style.height="28px",tt.style.color=fn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Mt=ye("activity","18px","currentColor",1.5);Mt&&tt.appendChild(Mt);let Ke=se.clearChatButtonWrapper,ft=se.closeButtonWrapper,Vt=Ke||ft;Vt&&Vt.parentNode===Ce?Ce.insertBefore(tt,Vt):Ce.appendChild(tt),tt.addEventListener("click",()=>{me?Wn():Kn()})}}else!ae&&ke&&(Wn(),tt&&(tt.remove(),tt=null),ie==null||ie.clear(),We==null||We.destroy(),ie=null,We=null);if((($i=n.launcher)==null?void 0:$i.enabled)===!1&&b&&(b.destroy(),b=null),((_i=n.launcher)==null?void 0:_i.enabled)===!1&&k&&(k.remove(),k=null),((ji=n.launcher)==null?void 0:ji.enabled)!==!1&&!b&&!k){let Y=s.find(ct=>ct.renderLauncher);if(Y!=null&&Y.renderLauncher){let ct=Y.renderLauncher({config:n,defaultRenderer:()=>Bo(n,De).element,onToggle:De});ct&&(k=ct,e.appendChild(k))}k||(b=Bo(n,De),e.appendChild(b.element))}b&&b.update(n),Pe&&((zi=n.launcher)==null?void 0:zi.title)!==void 0&&(Pe.textContent=n.launcher.title),Fe&&((qi=n.launcher)==null?void 0:qi.subtitle)!==void 0&&(Fe.textContent=n.launcher.subtitle);let Ne=(Ui=n.layout)==null?void 0:Ui.header;if((Ne==null?void 0:Ne.layout)!==L&&Ce){let Y=Ne?Do(n,Ne,{showClose:C,onClose:()=>It(!1,"user")}):br({config:n,showClose:C,onClose:()=>It(!1,"user")});Ce.replaceWith(Y.header),Ce=Y.header,ne=Y.iconHolder,Pe=Y.headerTitle,Fe=Y.headerSubtitle,$=Y.closeButton,L=Ne==null?void 0:Ne.layout}else if(Ne&&(ne&&(ne.style.display=Ne.showIcon===!1?"none":""),Pe&&(Pe.style.display=Ne.showTitle===!1?"none":""),Fe&&(Fe.style.display=Ne.showSubtitle===!1?"none":""),$&&($.style.display=Ne.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let Y=Ne.showClearChat;if(Y!==void 0){se.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:ct}=se;ct&&!ct.classList.contains("persona-absolute")&&(Y?ct.classList.remove("persona-ml-auto"):ct.classList.add("persona-ml-auto"))}}let lt=((Vi=n.layout)==null?void 0:Vi.showHeader)!==!1;Ce&&(Ce.style.display=lt?"":"none");let Ge=((Ji=n.layout)==null?void 0:Ji.showFooter)!==!1;be&&(be.style.display=Ge?"":"none"),Qe(),tr(),C!==w?C?It(S,"auto"):(E=!0,Er()):S!==H&&It(S,"auto"),H=S,w=C,v(),Xe();let _e=JSON.stringify(l.toolCall)!==JSON.stringify(m),Ae=JSON.stringify(n.messageActions)!==JSON.stringify(y),ze=JSON.stringify((Gi=n.layout)==null?void 0:Gi.messages)!==JSON.stringify(A),St=((Yi=n.loadingIndicator)==null?void 0:Yi.render)!==(R==null?void 0:R.render)||((Ki=n.loadingIndicator)==null?void 0:Ki.renderIdle)!==(R==null?void 0:R.renderIdle)||((Xi=n.loadingIndicator)==null?void 0:Xi.showBubble)!==(R==null?void 0:R.showBubble),xt=n.iterationDisplay!==B,Ut=((Qi=(Zi=n.features)==null?void 0:Zi.showReasoning)!=null?Qi:!0)!==(G!=null?G:!0)||((tl=(el=n.features)==null?void 0:el.showToolCalls)!=null?tl:!0)!==(F!=null?F:!0)||JSON.stringify((nl=n.features)==null?void 0:nl.toolCallDisplay)!==JSON.stringify(ve)||JSON.stringify((rl=n.features)==null?void 0:rl.reasoningDisplay)!==JSON.stringify(Se);(_e||Ae||ze||St||xt||Ut)&&D&&(pr++,Ar(ce,D.getMessages(),O));let Ie=(ol=n.launcher)!=null?ol:{},dn=(sl=Ie.headerIconHidden)!=null?sl:!1,Qt=(il=(al=n.layout)==null?void 0:al.header)==null?void 0:il.showIcon,On=dn||Qt===!1,ot=Ie.headerIconName,gt=(ll=Ie.headerIconSize)!=null?ll:"48px";if(ne){let Y=N.querySelector(".persona-border-b-persona-divider"),ct=Y==null?void 0:Y.querySelector(".persona-flex-col");if(On)ne.style.display="none",Y&&ct&&!Y.contains(ct)&&Y.insertBefore(ct,Y.firstChild);else{if(ne.style.display="",ne.style.height=gt,ne.style.width=gt,Y&&ct&&(Y.contains(ne)?ne.nextSibling!==ct&&(ne.remove(),Y.insertBefore(ne,ct)):Y.insertBefore(ne,ct)),ot){let Ke=parseFloat(gt)||24,ft=ye(ot,Ke*.6,"#ffffff",2);ft?ne.replaceChildren(ft):ne.textContent=(cl=Ie.agentIconText)!=null?cl:"\u{1F4AC}"}else if(Ie.iconUrl){let Ke=ne.querySelector("img");if(Ke)Ke.src=Ie.iconUrl,Ke.style.height=gt,Ke.style.width=gt;else{let ft=document.createElement("img");ft.src=Ie.iconUrl,ft.alt="",ft.className="persona-rounded-xl persona-object-cover",ft.style.height=gt,ft.style.width=gt,ne.replaceChildren(ft)}}else{let Ke=ne.querySelector("svg"),ft=ne.querySelector("img");(Ke||ft)&&ne.replaceChildren(),ne.textContent=(dl=Ie.agentIconText)!=null?dl:"\u{1F4AC}"}let Mt=ne.querySelector("img");Mt&&(Mt.style.height=gt,Mt.style.width=gt)}}let pn=(ul=(pl=n.layout)==null?void 0:pl.header)==null?void 0:ul.showTitle,rr=(gl=(ml=n.layout)==null?void 0:ml.header)==null?void 0:gl.showSubtitle;if(Pe&&(Pe.style.display=pn===!1?"none":""),Fe&&(Fe.style.display=rr===!1?"none":""),$){((hl=(fl=n.layout)==null?void 0:fl.header)==null?void 0:hl.showCloseButton)===!1?$.style.display="none":$.style.display="";let ct=(yl=Ie.closeButtonSize)!=null?yl:"32px",Mt=(bl=Ie.closeButtonPlacement)!=null?bl:"inline";$.style.height=ct,$.style.width=ct;let{closeButtonWrapper:Ke}=se,ft=Mt==="top-right",Vt=Ke==null?void 0:Ke.classList.contains("persona-absolute");if(Ke&&ft!==Vt)if(Ke.remove(),ft)Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",N.style.position="relative",N.appendChild(Ke);else{let nt=(vl=(xl=Ie.clearChat)==null?void 0:xl.placement)!=null?vl:"inline",Yt=(wl=(Cl=Ie.clearChat)==null?void 0:Cl.enabled)!=null?wl:!0;Ke.className=Yt&&nt==="inline"?"":"persona-ml-auto";let mn=N.querySelector(".persona-border-b-persona-divider");mn&&mn.appendChild(Ke)}if($.style.color=Ie.closeButtonColor||fn.actionIconColor,Ie.closeButtonBackgroundColor?($.style.backgroundColor=Ie.closeButtonBackgroundColor,$.classList.remove("hover:persona-bg-gray-100")):($.style.backgroundColor="",$.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let nt=Ie.closeButtonBorderWidth||"0px",Yt=Ie.closeButtonBorderColor||"transparent";$.style.border=`${nt} solid ${Yt}`,$.classList.remove("persona-border-none")}else $.style.border="",$.classList.add("persona-border-none");Ie.closeButtonBorderRadius?($.style.borderRadius=Ie.closeButtonBorderRadius,$.classList.remove("persona-rounded-full")):($.style.borderRadius="",$.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?($.style.paddingLeft=Ie.closeButtonPaddingX,$.style.paddingRight=Ie.closeButtonPaddingX):($.style.paddingLeft="",$.style.paddingRight=""),Ie.closeButtonPaddingY?($.style.paddingTop=Ie.closeButtonPaddingY,$.style.paddingBottom=Ie.closeButtonPaddingY):($.style.paddingTop="",$.style.paddingBottom="");let en=(Sl=Ie.closeButtonIconName)!=null?Sl:"x",$n=(Al=Ie.closeButtonIconText)!=null?Al:"\xD7";$.innerHTML="";let sn=ye(en,"20px","currentColor",2);sn?$.appendChild(sn):$.textContent=$n;let Ft=(El=Ie.closeButtonTooltipText)!=null?El:"Close chat",Sn=(Tl=Ie.closeButtonShowTooltip)!=null?Tl:!0;if($.setAttribute("aria-label",Ft),Ke&&(Ke._cleanupTooltip&&(Ke._cleanupTooltip(),delete Ke._cleanupTooltip),Sn&&Ft)){let nt=null,Yt=()=>{if(nt||!$)return;let Wr=$.ownerDocument,vo=Wr.body;if(!vo)return;nt=Gn(Wr,"div","persona-clear-chat-tooltip"),nt.textContent=Ft;let Co=Gn(Wr,"div");Co.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Co);let Rr=$.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(hr),nt.style.left=`${Rr.left+Rr.width/2}px`,nt.style.top=`${Rr.top-8}px`,nt.style.transform="translate(-50%, -100%)",vo.appendChild(nt)},mn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Ke.addEventListener("mouseenter",Yt),Ke.addEventListener("mouseleave",mn),$.addEventListener("focus",Yt),$.addEventListener("blur",mn),Ke._cleanupTooltip=()=>{mn(),Ke&&(Ke.removeEventListener("mouseenter",Yt),Ke.removeEventListener("mouseleave",mn)),$&&($.removeEventListener("focus",Yt),$.removeEventListener("blur",mn))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Tt}=se;if(Ye){let Y=(Ml=Ie.clearChat)!=null?Ml:{},ct=(kl=Y.enabled)!=null?kl:!0,Mt=(Il=(Ll=n.layout)==null?void 0:Ll.header)==null?void 0:Il.showClearChat,Ke=Mt!==void 0?Mt:ct,ft=(Pl=Y.placement)!=null?Pl:"inline";if(Tt){Tt.style.display=Ke?"":"none";let{closeButtonWrapper:Vt}=se;Vt&&!Vt.classList.contains("persona-absolute")&&(Ke?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let en=ft==="top-right",$n=Tt.classList.contains("persona-absolute");if(en!==$n&&Ke){if(Tt.remove(),en)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",N.style.position="relative",N.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let Ft=N.querySelector(".persona-border-b-persona-divider"),Sn=se.closeButtonWrapper;Ft&&Sn&&Sn.parentElement===Ft?Ft.insertBefore(Tt,Sn):Ft&&Ft.appendChild(Tt)}let sn=se.closeButtonWrapper;sn&&!sn.classList.contains("persona-absolute")&&(en?sn.classList.add("persona-ml-auto"):sn.classList.remove("persona-ml-auto"))}}if(Ke){let Vt=(Wl=Y.size)!=null?Wl:"32px";Ye.style.height=Vt,Ye.style.width=Vt;let en=(Rl=Y.iconName)!=null?Rl:"refresh-cw",$n=(Hl=Y.iconColor)!=null?Hl:"";Ye.style.color=$n||fn.actionIconColor,Ye.innerHTML="";let sn=ye(en,"20px","currentColor",2);if(sn&&Ye.appendChild(sn),Y.backgroundColor?(Ye.style.backgroundColor=Y.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let nt=Y.borderWidth||"0px",Yt=Y.borderColor||"transparent";Ye.style.border=`${nt} solid ${Yt}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");Y.borderRadius?(Ye.style.borderRadius=Y.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),Y.paddingX?(Ye.style.paddingLeft=Y.paddingX,Ye.style.paddingRight=Y.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),Y.paddingY?(Ye.style.paddingTop=Y.paddingY,Ye.style.paddingBottom=Y.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let Ft=(Bl=Y.tooltipText)!=null?Bl:"Clear chat",Sn=(Dl=Y.showTooltip)!=null?Dl:!0;if(Ye.setAttribute("aria-label",Ft),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),Sn&&Ft)){let nt=null,Yt=()=>{if(nt||!Ye)return;let Wr=Ye.ownerDocument,vo=Wr.body;if(!vo)return;nt=Gn(Wr,"div","persona-clear-chat-tooltip"),nt.textContent=Ft;let Co=Gn(Wr,"div");Co.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Co);let Rr=Ye.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(hr),nt.style.left=`${Rr.left+Rr.width/2}px`,nt.style.top=`${Rr.top-8}px`,nt.style.transform="translate(-50%, -100%)",vo.appendChild(nt)},mn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Tt.addEventListener("mouseenter",Yt),Tt.addEventListener("mouseleave",mn),Ye.addEventListener("focus",Yt),Ye.addEventListener("blur",mn),Tt._cleanupTooltip=()=>{mn(),Tt&&(Tt.removeEventListener("mouseenter",Yt),Tt.removeEventListener("mouseleave",mn)),Ye&&(Ye.removeEventListener("focus",Yt),Ye.removeEventListener("blur",mn))}}}}let Lr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ls],Ir=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ro.message,ro.messageAndClick];T=Is({parsers:Lr,handlers:Ir,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),O=wd(n,T,X),D.updateConfig(n),Ar(ce,D.getMessages(),O),Hn.render(n.suggestionChips,D,te,void 0,n.suggestionChipsConfig),uo(),$r(D.isStreaming());let Qo=((Nl=n.voiceRecognition)==null?void 0:Nl.enabled)===!0,es=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ts=((Ol=(Fl=n.voiceRecognition)==null?void 0:Fl.provider)==null?void 0:Ol.type)==="runtype";if(Qo&&(es||ts))if(!j||!xe){let Y=Yo(n.voiceRecognition,n.sendButton);Y&&(j=Y.micButton,xe=Y.micButtonWrapper,At.insertBefore(xe,kt),j.addEventListener("click",kr),j.disabled=D.isStreaming())}else{let Y=($l=n.voiceRecognition)!=null?$l:{},ct=(_l=n.sendButton)!=null?_l:{},Mt=(jl=Y.iconName)!=null?jl:"mic",Ke=(zl=ct.size)!=null?zl:"40px",ft=(ql=Y.iconSize)!=null?ql:Ke,Vt=parseFloat(ft)||24;j.style.width=ft,j.style.height=ft,j.style.minWidth=ft,j.style.minHeight=ft;let en=(Vl=(Ul=Y.iconColor)!=null?Ul:ct.textColor)!=null?Vl:"currentColor";j.innerHTML="";let $n=ye(Mt,Vt,en,2);$n?j.appendChild($n):j.textContent="\u{1F3A4}";let sn=(Jl=Y.backgroundColor)!=null?Jl:ct.backgroundColor;sn?j.style.backgroundColor=sn:j.style.backgroundColor="",en?j.style.color=en:j.style.color="var(--persona-text, #111827)",Y.borderWidth?(j.style.borderWidth=Y.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),Y.borderColor?j.style.borderColor=Y.borderColor:j.style.borderColor="",Y.paddingX?(j.style.paddingLeft=Y.paddingX,j.style.paddingRight=Y.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),Y.paddingY?(j.style.paddingTop=Y.paddingY,j.style.paddingBottom=Y.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Ft=xe==null?void 0:xe.querySelector(".persona-send-button-tooltip"),Sn=(Gl=Y.tooltipText)!=null?Gl:"Start voice recognition";if(((Yl=Y.showTooltip)!=null?Yl:!1)&&Sn)if(Ft)Ft.textContent=Sn,Ft.style.display="";else{let Yt=document.createElement("div");Yt.className="persona-send-button-tooltip",Yt.textContent=Sn,xe==null||xe.insertBefore(Yt,j)}else Ft&&(Ft.style.display="none");xe.style.display="",j.disabled=D.isStreaming()}else j&&xe&&(xe.style.display="none",((Xl=(Kl=n.voiceRecognition)==null?void 0:Kl.provider)==null?void 0:Xl.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():wn&&Dn());if(((Zl=n.attachments)==null?void 0:Zl.enabled)===!0)if(!Ze||!ue){let Y=(Ql=n.attachments)!=null?Ql:{},Mt=(tc=((ec=n.sendButton)!=null?ec:{}).size)!=null?tc:"40px";de||(de=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),de.style.display="none",dt.insertBefore(de,te)),qe||(qe=document.createElement("input"),qe.type="file",qe.accept=((nc=Y.allowedTypes)!=null?nc:or).join(","),qe.multiple=((rc=Y.maxFiles)!=null?rc:4)>1,qe.style.display="none",qe.setAttribute("aria-label","Attach files"),dt.insertBefore(qe,te)),Ze=h("div","persona-send-button-wrapper"),ue=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ue.type="button",ue.setAttribute("aria-label",(oc=Y.buttonTooltipText)!=null?oc:"Attach file");let Ke=(sc=Y.buttonIconName)!=null?sc:"paperclip",ft=Mt,Vt=parseFloat(ft)||40,en=Math.round(Vt*.6);ue.style.width=ft,ue.style.height=ft,ue.style.minWidth=ft,ue.style.minHeight=ft,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.style.backgroundColor="transparent",ue.style.color="var(--persona-primary, #111827)",ue.style.border="none",ue.style.borderRadius="6px",ue.style.transition="background-color 0.15s ease",ue.addEventListener("mouseenter",()=>{ue.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ue.addEventListener("mouseleave",()=>{ue.style.backgroundColor="transparent"});let $n=ye(Ke,en,"currentColor",1.5);$n?ue.appendChild($n):ue.textContent="\u{1F4CE}",ue.addEventListener("click",Sn=>{Sn.preventDefault(),qe==null||qe.click()}),Ze.appendChild(ue);let sn=(ac=Y.buttonTooltipText)!=null?ac:"Attach file",Ft=h("div","persona-send-button-tooltip");Ft.textContent=sn,Ze.appendChild(Ft),mt.append(Ze),!je&&qe&&de&&(je=Xr.fromConfig(Y),je.setPreviewsContainer(de),qe.addEventListener("change",async()=>{je&&(qe!=null&&qe.files)&&(await je.handleFileSelect(qe.files),qe.value="")})),N.querySelector(".persona-attachment-drop-overlay")||N.appendChild(Sd(Y.dropOverlay))}else{Ze.style.display="";let Y=(ic=n.attachments)!=null?ic:{};qe&&(qe.accept=((lc=Y.allowedTypes)!=null?lc:or).join(","),qe.multiple=((cc=Y.maxFiles)!=null?cc:4)>1),je&&je.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else Ze&&(Ze.style.display="none"),je&&je.clearAttachments(),(dc=N.querySelector(".persona-attachment-drop-overlay"))==null||dc.remove();let jt=(pc=n.sendButton)!=null?pc:{},ns=(uc=jt.useIcon)!=null?uc:!1,yo=(mc=jt.iconText)!=null?mc:"\u2191",un=jt.iconName,Ln=(gc=jt.tooltipText)!=null?gc:"Send message",Ur=(fc=jt.showTooltip)!=null?fc:!1,bo=(hc=jt.size)!=null?hc:"40px",rs=jt.backgroundColor,Pr=jt.textColor;if(ns){if(pe.style.width=bo,pe.style.height=bo,pe.style.minWidth=bo,pe.style.minHeight=bo,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",Pr?pe.style.color=Pr:pe.style.color="var(--persona-button-primary-fg, #ffffff)",un){let Y=parseFloat(bo)||24,ct=(Pr==null?void 0:Pr.trim())||"currentColor",Mt=ye(un,Y,ct,2);Mt?pe.appendChild(Mt):pe.textContent=yo}else pe.textContent=yo;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rs?(pe.style.backgroundColor=rs,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(bc=(yc=n.copy)==null?void 0:yc.sendButtonLabel)!=null?bc:"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.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",rs?(pe.style.backgroundColor=rs,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Pr?pe.style.color=Pr:pe.classList.add("persona-text-white");jt.borderWidth?(pe.style.borderWidth=jt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),jt.borderColor?pe.style.borderColor=jt.borderColor:pe.style.borderColor="",jt.paddingX?(pe.style.paddingLeft=jt.paddingX,pe.style.paddingRight=jt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),jt.paddingY?(pe.style.paddingTop=jt.paddingY,pe.style.paddingBottom=jt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let xo=kt==null?void 0:kt.querySelector(".persona-send-button-tooltip");if(Ur&&Ln)if(xo)xo.textContent=Ln,xo.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=Ln,kt==null||kt.insertBefore(Y,pe)}else xo&&(xo.style.display="none");let os=(xc=n.layout)==null?void 0:xc.contentMaxWidth;os?(ce.style.maxWidth=os,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",dt&&(dt.style.maxWidth=os,dt.style.marginLeft="auto",dt.style.marginRight="auto"),fe&&(fe.style.maxWidth=os,fe.style.marginLeft="auto",fe.style.marginRight="auto")):(ce.style.maxWidth="",ce.style.marginLeft="",ce.style.marginRight="",ce.style.width="",dt&&(dt.style.maxWidth="",dt.style.marginLeft="",dt.style.marginRight=""),fe&&(fe.style.maxWidth="",fe.style.marginLeft="",fe.style.marginRight=""));let fr=(vc=n.statusIndicator)!=null?vc:{},op=(Cc=fr.visible)!=null?Cc:!0;if(Wt.style.display=op?"":"none",D){let Y=D.getStatus();st(Wt,(Mt=>{var Ke,ft,Vt,en;return Mt==="idle"?(Ke=fr.idleText)!=null?Ke:tn.idle:Mt==="connecting"?(ft=fr.connectingText)!=null?ft:tn.connecting:Mt==="connected"?(Vt=fr.connectedText)!=null?Vt:tn.connected:Mt==="error"?(en=fr.errorText)!=null?en:tn.error:tn[Mt]})(Y),fr,Y)}Wt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let sp=fr.align==="left"?"persona-text-left":fr.align==="center"?"persona-text-center":"persona-text-right";Wt.classList.add(sp)},open(){C&&It(!0,"api")},close(){C&&It(!1,"api")},toggle(){C&&It(!E,"api")},clearChat(){nn=!1,D.clearMessages(),Tn.clear(),ur();try{localStorage.removeItem(oo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${oo}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==oo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},T.syncFromMetadata(),ie==null||ie.clear(),Z==null||Z.update()},setMessage(l){return!te||D.isStreaming()?!1:(!E&&C&&It(!0,"system"),te.value=l,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let m=(l==null?void 0:l.trim())||te.value.trim();return m?(!E&&C&&It(!0,"system"),te.value="",te.style.height="auto",D.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return D.isStreaming()?!1:((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(D.isVoiceActive()||(!E&&C&&It(!0,"system"),et.manuallyDeactivated=!1,cn(),D.toggleVoice().then(()=>{et.active=D.isVoiceActive(),Mn("user"),D.isVoiceActive()&&gr()})),!0):wn?!0:ho()?(!E&&C&&It(!0,"system"),et.manuallyDeactivated=!1,cn(),Tr("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{et.active=!1,et.manuallyDeactivated=!0,cn(),Mn("user"),Nn()}),!0):!1:wn?(et.manuallyDeactivated=!0,cn(),Dn("user"),!0):!1},injectMessage(l){return!E&&C&&It(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!E&&C&&It(!0,"system");let m=D.injectAssistantMessage(l);return K&&(K=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),m},injectUserMessage(l){return!E&&C&&It(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!E&&C&&It(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!E&&C&&It(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!E&&C&&It(!0,"system"),D.injectTestEvent(l)},async connectStream(l,m){return D.connectStream(l,m)},__pushEventStreamEvent(l){ie&&ie.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ae||!ie||Kn()},hideEventStream(){me&&Wn()},isEventStreamVisible(){return me},showArtifacts(){Pn(n)&&(nn=!1,bn(),it==null||it.setMobileOpen(!0))},hideArtifacts(){Pn(n)&&(nn=!0,bn())},upsertArtifact(l){return Pn(n)?(nn=!1,D.upsertArtifact(l)):null},selectArtifact(l){Pn(n)&&D.selectArtifact(l)},clearArtifacts(){Pn(n)&&D.clearArtifacts()},focusInput(){return C&&!E||!te?!1:(te.focus(),!0)},async resolveApproval(l,m){let A=D.getMessages().find(I=>{var R;return I.variant==="approval"&&((R=I.approval)==null?void 0:R.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(A.approval,m)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return C&&E},isVoiceActive(){return et.active},getState(){return{open:C&&E,launcherEnabled:C,voiceActive:et.active,streaming:D.isStreaming()}},showCSATFeedback(l){!E&&C&&It(!0,"system");let m=ce.querySelector(".persona-feedback-container");m&&m.remove();let y=xa({onSubmit:async(A,I)=>{var R;D.isClientTokenMode()&&await D.submitCSATFeedback(A,I),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,I)},onDismiss:l==null?void 0:l.onDismiss,...l});ce.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&C&&It(!0,"system");let m=ce.querySelector(".persona-feedback-container");m&&m.remove();let y=va({onSubmit:async(A,I)=>{var R;D.isClientTokenMode()&&await D.submitNPSFeedback(A,I),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,I)},onDismiss:l==null?void 0:l.onDismiss,...l});ce.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return D.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return D.submitNPSFeedback(l,m)},destroy(){Jn!=null&&(clearInterval(Jn),Jn=null),Ct.forEach(l=>l()),z.remove(),b==null||b.destroy(),k==null||k.remove(),vn&&$.removeEventListener("click",vn)}};if((((fi=t==null?void 0:t.debugTools)!=null?fi:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:qt,getMessages:qt.getMessages,getStatus:qt.getStatus,getMetadata:qt.getPersistentMetadata,updateMetadata:qt.updatePersistentMetadata,clearHistory:()=>qt.clearChat(),setVoiceActive:y=>y?qt.startVoiceRecognition():qt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,Ct.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=G=>{let F=G.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&qt.focusInput()};if(window.addEventListener("persona:focusInput",m),Ct.push(()=>{window.removeEventListener("persona:focusInput",m)}),ae){let G=ve=>{let Se=ve.detail;(!(Se!=null&&Se.instanceId)||Se.instanceId===l)&&qt.showEventStream()},F=ve=>{let Se=ve.detail;(!(Se!=null&&Se.instanceId)||Se.instanceId===l)&&qt.hideEventStream()};window.addEventListener("persona:showEventStream",G),window.addEventListener("persona:hideEventStream",F),Ct.push(()=>{window.removeEventListener("persona:showEventStream",G),window.removeEventListener("persona:hideEventStream",F)})}let y=G=>{let F=G.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&qt.showArtifacts()},A=G=>{let F=G.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&qt.hideArtifacts()},I=G=>{let F=G.detail;F!=null&&F.instanceId&&F.instanceId!==l||F!=null&&F.artifact&&qt.upsertArtifact(F.artifact)},R=G=>{let F=G.detail;F!=null&&F.instanceId&&F.instanceId!==l||typeof(F==null?void 0:F.id)=="string"&&qt.selectArtifact(F.id)},B=G=>{let F=G.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&qt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",I),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",B),Ct.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",I),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",B)})}let kn=Du(n.persistState);if(kn&&C){let l=Nu(kn.storage),m=`${kn.keyPrefix}widget-open`,y=`${kn.keyPrefix}widget-voice`,A=`${kn.keyPrefix}widget-voice-mode`;if(l){let I=((hi=kn.persist)==null?void 0:hi.openState)&&l.getItem(m)==="true",R=((yi=kn.persist)==null?void 0:yi.voiceState)&&l.getItem(y)==="true",B=((bi=kn.persist)==null?void 0:bi.voiceState)&&l.getItem(A)==="true";if(I&&setTimeout(()=>{qt.open(),setTimeout(()=>{var G;if(R||B)qt.startVoiceRecognition();else if((G=kn.persist)!=null&&G.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(xi=kn.persist)!=null&&xi.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(vi=kn.persist)!=null&&vi.voiceState&&(o.on("voice:state",G=>{l.setItem(y,G.active?"true":"false")}),o.on("user:message",G=>{l.setItem(A,G.viaVoice?"true":"false")})),kn.clearOnChatClear){let G=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(A)},F=()=>G();window.addEventListener("persona:clear-chat",F),Ct.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return c&&C&&setTimeout(()=>{qt.open()},0),qt};var Fu=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},Ad=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.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"},Ta=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=""},Ed=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Ta(e)},Sa=e=>{e.style.transition=""},Aa=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=""},Ea=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ws=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Ou=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},$u=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},Td=(e,r,t,n,s,o,a)=>{var x,T,C,S,M,H;let i=_n(o),u=i.reveal==="push";Ou(e,r,t,n,u),$u(e,r,t,n,i.side,u),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 c=e.ownerDocument.defaultView,p=(T=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?T:!0,d=(S=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=d:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Aa(r),Sa(n),Ed(n),Ea(t),Ws(s,n),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",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((H=(M=o==null?void 0:o.launcher)==null?void 0:M.zIndex)!=null?H:gn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.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"),Ed(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Aa(r),Sa(n),Ea(t),Ws(s,n);let w=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",W=a?"translateX(0)":L;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=W,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.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",Sa(n),Ta(n),Ws(s,n);let w=Fu(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),W=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${L+w}px`,r.style.transition=W,r.style.transform=E,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`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Aa(r),Ta(n),Ea(t),Ws(s,n);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",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${L}`,n.style.width=L,n.style.maxWidth=L,n.style.minWidth=L,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||E?"hidden":"visible",n.style.transition=W,w&&(n.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")}},_u=(e,r)=>{let t=e.ownerDocument.createElement("div");return Ad(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Ad(t,n)},destroy(){t.remove()}}},ju=(e,r)=>{var M,H,w,L;let{ownerDocument:t}=e,n=e.parentElement;if(!n)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"),u=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),d=(H=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||H?(L=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),u.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),_n(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Td(a,i,u,c,p,r,d)}),f.observe(a))},T=()=>{Td(a,i,u,c,p,r,d),x()},C=a.ownerDocument.defaultView,S=()=>{T()};return C==null||C.addEventListener("resize",S),_n(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),T(),{mode:"docked",host:p,shell:a,syncWidgetState(W){let E=W.launcherEnabled?W.open:!0;d!==E&&(d=E,T())},updateConfig(W){var E,K;r=W,((K=(E=r==null?void 0:r.launcher)==null?void 0:E.enabled)!=null?K:!0)===!1&&(d=!0),T()},destroy(){C==null||C.removeEventListener("resize",S),g(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Rs=(e,r)=>Kt(r)?ju(e,r):_u(e,r);var Ma={},zu=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 r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},qu=()=>{try{if(typeof Ma!="undefined"&&Ma.url)return new URL("../widget.css",Ma.url).href}catch{}return null},Md=(e,r)=>{let t=qu(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.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=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},kd=e=>{var C;let r=zu(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Rs(r,s),a,i=[],u=(S,M)=>{var W,E;let w=!((E=(W=M==null?void 0:M.launcher)==null?void 0:W.enabled)!=null?E:!0)||Kt(M),L=n.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 K=S.attachShadow({mode:"open"});K.appendChild(L),Md(K,n)}else S.appendChild(L),Md(S,n);return r.id&&L.setAttribute("data-persona-instance",r.id),L},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let S=u(o.host,s);a=wa(S,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};d(),(C=e.onReady)==null||C.call(e);let g=S=>{f(),o.destroy(),o=Rs(r,S),s=S,d()},x={update(S){var L,W,E,K,Q,X;let M={...s,...S,launcher:{...(L=s==null?void 0:s.launcher)!=null?L:{},...(W=S==null?void 0:S.launcher)!=null?W:{},dock:{...(K=(E=s==null?void 0:s.launcher)==null?void 0:E.dock)!=null?K:{},...(X=(Q=S==null?void 0:S.launcher)==null?void 0:Q.dock)!=null?X:{}}}},H=Kt(s),w=Kt(M);if(H!==w){g(M);return}s=M,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},T=new Proxy(x,{get(S,M,H){if(M==="host")return o.host;if(M in S)return Reflect.get(S,M,H);let w=a[M];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=T),T};var Rd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Uu=new Set(["button","a","input","select","textarea","details","summary"]),Vu=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ka=/\b(product|card|item|listing|result)\b/i,Ia=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ju=3e3,Gu=100;function Hd(e){let r=typeof e.className=="string"?e.className:"";if(ka.test(r)||e.id&&ka.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&ka.test(n.value))return!0}return!1}function Bd(e){var r;return Ia.test(((r=e.textContent)!=null?r:"").trim())}function Dd(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Yu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ld(e){let r=e.match(Ia);return r?r[0]:null}function Id(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.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 Ku(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var Xu="commerce-card",Zu="result-card";function Pd(e){return!Hd(e)||!Bd(e)||!Dd(e)&&!Yu(e)?0:5200}function Wd(e){var n;return!Hd(e)||Bd(e)||!Dd(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Nd=[{id:Xu,scoreElement(e){return Pd(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Ia.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,p;if(Pd(e)===0)return null;let{title:t,href:n}=Id(e),s=(p=(c=Ld(((u=e.textContent)!=null?u:"").trim()))!=null?c:Ld(r.text))!=null?p:"",o=Ku(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
100
|
-
`)}},{id:
|
|
101
|
-
`)}}];function
|
|
99
|
+
`}if(!A&&!l){let gn="max-height: -moz-available !important; max-height: stretch !important;",In=m?"":"padding-top: 1.25em !important;",Xr=m?"":`z-index: ${(Lo=(fs=n.launcher)==null?void 0:fs.zIndex)!=null?Lo:hn} !important;`;P.style.cssText+=gn+In+Xr}};Jn(),jr(e,n),Os(e,n),$s(e,n);let wt=[],Ot=null,$t=null;wt.push(()=>{Ot==null||Ot(),Ot=null,$t==null||$t(),$t=null}),bn&&wt.push(()=>{bn==null||bn.disconnect(),bn=null}),wt.push(()=>{sn==null||sn(),sn=null,Qn(),At&&(At.remove(),At=null),pt==null||pt.element.style.removeProperty("width"),pt==null||pt.element.style.removeProperty("maxWidth")}),oe&&wt.push(()=>{de!==null&&(cancelAnimationFrame(de),de=null),Y==null||Y.destroy(),Y=null,ue==null||ue.destroy(),ue=null,ke=null});let Cn=null,mr=()=>{Cn&&(Cn(),Cn=null),n.colorScheme==="auto"&&(Cn=fa(()=>{jr(e,n)}))};mr(),wt.push(()=>{Cn&&(Cn(),Cn=null)});let Bn=cd(Je),wn=null,O,Dn=!1,kn=Kc(),gr=0,cn=Rs(),dn=0,ce=null,Sn=!1,er=!1,Qo=4,mo=24,es=80,Ur=new Map,rt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},go=(ui=(pi=n.voiceRecognition)==null?void 0:pi.autoResume)!=null?ui:!1,Ln=l=>{o.emit("voice:state",{active:rt.active,source:l,timestamp:Date.now()})},pn=()=>{f(l=>({...l,voiceState:{active:rt.active,timestamp:Date.now(),manuallyDeactivated:rt.manuallyDeactivated}}))},ts=()=>{var A,L;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Ba(i.voiceState),m=!!l.active,y=Number((L=l.timestamp)!=null?L:0);rt.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<Hu&&setTimeout(()=>{var H,D;rt.active||(rt.manuallyDeactivated=!1,((D=(H=n.voiceRecognition)==null?void 0:H.provider)==null?void 0:D.type)==="runtype"?O.toggleVoice().then(()=>{rt.active=O.isVoiceActive(),Ln("restore"),O.isVoiceActive()&&yr()}):Pr("restore"))},1e3)},ns=()=>O?wd(O.getMessages()).filter(l=>!l.__skipPersist):[];function fo(l){if(!(a!=null&&a.save))return;let y={messages:l?wd(l):O?ns():[],metadata:i};try{let A=a.save(y);A instanceof Promise&&A.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let tr=null,rs=()=>P.querySelector("#persona-scroll-container")||U,kr=()=>{tr!==null&&(cancelAnimationFrame(tr),tr=null),Sn=!1},ho=()=>{ce!==null&&(cancelAnimationFrame(ce),ce=null),er=!1,kr()},nr=()=>{if(!Ft()||ye){ft.parentNode&&ft.remove(),ft.style.display="none";return}ft.parentNode!==F&&F.appendChild(ft),nt();let l=qo(U)>0;ft.style.display=cn.isFollowing()||!l?"none":""},yo=()=>{cn.pause()&&(ho(),nr())},fr=()=>{cn.resume(),nr()},hr=(l=!1)=>{cn.isFollowing()&&(!l&&!Dn||(ce!==null&&(cancelAnimationFrame(ce),ce=null),er=!0,ce=requestAnimationFrame(()=>{ce=null,er=!1,cn.isFollowing()&&os(rs(),l?220:140)})))},os=(l,m=500)=>{let y=l.scrollTop,A=qo(l),L=A-y;if(Math.abs(L)<1){dn=l.scrollTop;return}if(Math.abs(L)>=es){kr(),Sn=!0,l.scrollTop=A,dn=l.scrollTop,Sn=!1;return}kr();let H=performance.now();Sn=!0;let D=_=>1-Math.pow(1-_,3),V=_=>{if(!cn.isFollowing()){kr();return}let be=qo(l);be!==A&&(A=be,L=A-y);let xe=_-H,Ae=Math.min(xe/m,1),Ee=D(Ae),De=y+L*Ee;l.scrollTop=De,dn=l.scrollTop,Ae<1?tr=requestAnimationFrame(V):(l.scrollTop=A,dn=l.scrollTop,tr=null,Sn=!1)};tr=requestAnimationFrame(V)},ss=l=>{let m=new Map;l.forEach(y=>{let A=Ur.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Ur.clear(),m.forEach((y,A)=>{Ur.set(A,y)})},Lr=(l,m,y)=>{var Ae,Ee,De,Ke,ut,Qe;let A=document.createElement("div"),H=(()=>{var $e;let z=s.find(je=>je.renderLoadingIndicator);if(z!=null&&z.renderLoadingIndicator)return z.renderLoadingIndicator;if(($e=n.loadingIndicator)!=null&&$e.render)return n.loadingIndicator.render})(),D=(z,$e)=>$e==null?!1:typeof $e=="string"?(z.textContent=$e,!0):(z.appendChild($e),!0),V=new Set;if(m.forEach(z=>{var Jt,en;V.add(z.id);let $e=Gc(z,gr),je=Yc(kn,z.id,$e);if(je){A.appendChild(je.cloneNode(!0));return}let ve=null,Ue=s.find(Re=>!!(z.variant==="reasoning"&&Re.renderReasoning||z.variant==="tool"&&Re.renderToolCall||z.variant==="approval"&&Re.renderApproval||!z.variant&&Re.renderMessage)),St=(Jt=n.layout)==null?void 0:Jt.messages;if(Ue)if(z.variant==="reasoning"&&z.reasoning&&Ue.renderReasoning){if(!re)return;ve=Ue.renderReasoning({message:z,defaultRenderer:()=>va(z,n),config:n})}else if(z.variant==="tool"&&z.toolCall&&Ue.renderToolCall){if(!Te)return;ve=Ue.renderToolCall({message:z,defaultRenderer:()=>Ca(z,n),config:n})}else if(z.variant==="approval"&&z.approval&&Ue.renderApproval){if(n.approval===!1)return;ve=Ue.renderApproval({message:z,defaultRenderer:()=>wa(z,n),config:n})}else Ue.renderMessage&&(ve=Ue.renderMessage({message:z,defaultRenderer:()=>{let Re=Yo(z,y,St,n.messageActions,Me,{loadingIndicatorRenderer:H,widgetConfig:n});return z.role!=="user"&&Ea(Re,z,n,O),Re},config:n}));if(!ve&&z.role==="assistant"&&!z.variant&&n.enableComponentStreaming!==!1&&Pa(z)){let un=Wa(z);if(un){let tn=Ia(un,{config:n,message:z,transform:y});if(tn)if(n.wrapComponentDirectiveInBubble!==!1){let dt=document.createElement("div");if(dt.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(" "),dt.id=`bubble-${z.id}`,dt.setAttribute("data-message-id",z.id),z.content&&z.content.trim()){let yt=document.createElement("div");yt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",yt.innerHTML=y({text:z.content,message:z,streaming:!!z.streaming,raw:z.rawContent}),dt.appendChild(yt)}dt.appendChild(tn),ve=dt}else{let dt=document.createElement("div");if(dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",dt.id=`bubble-${z.id}`,dt.setAttribute("data-message-id",z.id),dt.setAttribute("data-persona-component-directive","true"),z.content&&z.content.trim()){let yt=document.createElement("div");yt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",yt.innerHTML=y({text:z.content,message:z,streaming:!!z.streaming,raw:z.rawContent}),dt.appendChild(yt)}dt.appendChild(tn),ve=dt}}}if(!ve)if(z.variant==="reasoning"&&z.reasoning){if(!re)return;ve=va(z,n)}else if(z.variant==="tool"&&z.toolCall){if(!Te)return;ve=Ca(z,n)}else if(z.variant==="approval"&&z.approval){if(n.approval===!1)return;ve=wa(z,n)}else{let Re=(en=n.layout)==null?void 0:en.messages;Re!=null&&Re.renderUserMessage&&z.role==="user"?ve=Re.renderUserMessage({message:z,config:n,streaming:!!z.streaming}):Re!=null&&Re.renderAssistantMessage&&z.role==="assistant"?ve=Re.renderAssistantMessage({message:z,config:n,streaming:!!z.streaming}):ve=Yo(z,y,Re,n.messageActions,Me,{loadingIndicatorRenderer:H,widgetConfig:n}),z.role!=="user"&&ve&&Ea(ve,z,n,O)}let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id=`wrapper-${z.id}`,Ct.setAttribute("data-wrapper-id",z.id),z.role==="user"&&Ct.classList.add("persona-justify-end"),(ve==null?void 0:ve.getAttribute("data-persona-component-directive"))==="true"&&Ct.classList.add("persona-w-full"),Ct.appendChild(ve),Xc(kn,z.id,$e,Ct),A.appendChild(Ct)}),(Ee=(Ae=n.features)==null?void 0:Ae.toolCallDisplay)!=null&&Ee.grouped){let z=[],$e=[];m.forEach(je=>{if(je.variant==="tool"&&je.toolCall&&Te){$e.push(je);return}$e.length>1&&z.push($e),$e=[]}),$e.length>1&&z.push($e),z.forEach((je,ve)=>{var tn,$n;let Ue=je.map(dt=>Array.from(A.children).find(yt=>yt instanceof HTMLElement&&yt.getAttribute("data-wrapper-id")===dt.id)).filter(dt=>!!dt);if(Ue.length<2)return;let St=document.createElement("div");St.className="persona-flex",St.id=`wrapper-tool-group-${ve}-${je[0].id}`,St.setAttribute("data-wrapper-id",`tool-group-${ve}-${je[0].id}`);let Ct=document.createElement("div");Ct.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ct.setAttribute("data-persona-tool-group","true");let Jt=document.createElement("div");Jt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let en=`Called ${je.length} tools`,Re=($n=(tn=n.toolCall)==null?void 0:tn.renderGroupedSummary)==null?void 0:$n.call(tn,{messages:je,toolCalls:je.map(dt=>dt.toolCall).filter(dt=>!!dt),defaultSummary:en,config:n});D(Jt,Re)||(Jt.textContent=en);let un=document.createElement("div");un.className="persona-tool-group-stack persona-flex persona-flex-col",Ct.append(Jt,un),St.appendChild(Ct),Ue[0].before(St),Ue.forEach((dt,yt)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),yt<Ue.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(dt),un.appendChild(mn)})})}Zc(kn,V);let _=m.some(z=>z.role==="assistant"&&z.streaming),be=m[m.length-1],xe=(be==null?void 0:be.role)==="assistant"&&!be.streaming&&be.variant!=="approval";if(Dn&&m.some(z=>z.role==="user")&&!_&&!xe){let z={config:n,streaming:!0,location:"standalone",defaultRenderer:so},$e=s.find(ve=>ve.renderLoadingIndicator),je=null;if($e!=null&&$e.renderLoadingIndicator&&(je=$e.renderLoadingIndicator(z)),je===null&&((De=n.loadingIndicator)!=null&&De.render)&&(je=n.loadingIndicator.render(z)),je===null&&(je=so()),je){let ve=document.createElement("div"),Ue=((Ke=n.loadingIndicator)==null?void 0:Ke.showBubble)!==!1;ve.className=Ue?["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(" "),ve.setAttribute("data-typing-indicator","true"),ve.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ve.appendChild(je);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-typing-indicator",St.setAttribute("data-wrapper-id","typing-indicator"),St.appendChild(ve),A.appendChild(St)}}if(!Dn&&m.length>0){let z=m[m.length-1],$e={config:n,lastMessage:z,messageCount:m.length},je=s.find(Ue=>Ue.renderIdleIndicator),ve=null;if(je!=null&&je.renderIdleIndicator&&(ve=je.renderIdleIndicator($e)),ve===null&&((ut=n.loadingIndicator)!=null&&ut.renderIdle)&&(ve=n.loadingIndicator.renderIdle($e)),ve){let Ue=document.createElement("div"),St=((Qe=n.loadingIndicator)==null?void 0:Qe.showBubble)!==!1;Ue.className=St?["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(" "),Ue.setAttribute("data-idle-indicator","true"),Ue.appendChild(ve);let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id="wrapper-idle-indicator",Ct.setAttribute("data-wrapper-id","idle-indicator"),Ct.appendChild(Ue),A.appendChild(Ct)}}Jc(l,A)},Ir=()=>{var _,be,xe,Ae,Ee;if(!w)return;let l=Yt(n),m=(_=e.ownerDocument.defaultView)!=null?_:window,y=(xe=(be=n.launcher)==null?void 0:be.mobileBreakpoint)!=null?xe:640,A=(Ee=(Ae=n.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Ee:!0,L=m.innerWidth<=y,H=A&&L&&w,D=jn(n).reveal;E?(P.style.removeProperty("display"),P.style.display=l?"flex":"",P.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-95","persona-opacity-0"),q.classList.add("persona-scale-100","persona-opacity-100"),Bt?Bt.element.style.display="none":Dt&&(Dt.style.display="none")):(l?l&&(D==="overlay"||D==="push")&&!H?(P.style.removeProperty("display"),P.style.display="flex",P.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(P.style.setProperty("display","none","important"),P.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(P.style.display="",P.classList.add("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100"),q.classList.add("persona-scale-95","persona-opacity-0")),Bt?Bt.element.style.display=l?"none":"":Dt&&(Dt.style.display=l?"none":""))},Ht=(l,m="user")=>{var H,D;if(!w||E===l)return;let y=E;E=l,Ir();let A=(()=>{var De,Ke,ut,Qe,z,$e,je;let V=(Ke=(De=n.launcher)==null?void 0:De.sidebarMode)!=null?Ke:!1,_=(ut=e.ownerDocument.defaultView)!=null?ut:window,be=(z=(Qe=n.launcher)==null?void 0:Qe.mobileFullscreen)!=null?z:!0,xe=(je=($e=n.launcher)==null?void 0:$e.mobileBreakpoint)!=null?je:640,Ae=_.innerWidth<=xe,Ee=Yt(n)&&be&&Ae;return V||be&&Ae&&w||Ee})();if(E&&A){if(!Ot){let V=e.getRootNode(),_=V instanceof ShadowRoot?V.host:e.closest(".persona-host");_&&(Ot=ha(_,(D=(H=n.launcher)==null?void 0:H.zIndex)!=null?D:hn))}$t||($t=ya(e.ownerDocument))}else E||(Ot==null||Ot(),Ot=null,$t==null||$t(),$t=null);E&&(br(),hr(!0));let L={open:E,source:m,timestamp:Date.now()};E&&!y?o.emit("widget:opened",L):!E&&y&&o.emit("widget:closed",L),o.emit("widget:state",{open:E,launcherEnabled:w,voiceActive:rt.active,streaming:O.isStreaming()})},Vr=l=>{le.disabled=l,I&&(I.disabled=l),Bn.buttons.forEach(m=>{m.disabled=l}),X.dataset.personaComposerStreaming=l?"true":"false",X.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Jr=()=>{rt.active||ee&&ee.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Jr(),200)});let bo=()=>{var y,A,L,H,D,V,_,be,xe,Ae,Ee;Xt.textContent=(A=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}",Xe.textContent=(H=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",ee.placeholder=(V=(D=n.copy)==null?void 0:D.inputPlaceholder)!=null?V:"How can I help...";let l=U.querySelector("[data-persona-intro-card]");if(l){let De=((_=n.copy)==null?void 0:_.showWelcomeCard)!==!1;l.style.display=De?"":"none",De?(U.classList.remove("persona-gap-3"),U.classList.add("persona-gap-6")):(U.classList.remove("persona-gap-6"),U.classList.add("persona-gap-3"))}(xe=(be=n.sendButton)==null?void 0:be.useIcon)!=null&&xe||(le.textContent=(Ee=(Ae=n.copy)==null?void 0:Ae.sendButtonLabel)!=null?Ee:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let Gn=null,as=()=>{Gn==null&&(Gn=setInterval(()=>{let l=me.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Gn),Gn=null;return}let m=Date.now();l.forEach(y=>{let A=Number(y.getAttribute("data-tool-elapsed"));A&&(y.textContent=vs(m-A))})},100))};if(O=new $o(n,{onMessagesChanged(l){Lr(me,l,j),as(),O&&(l.some(L=>L.role==="user")?Bn.render([],O,ee,l):Bn.render(n.suggestionChips,O,ee,l,n.suggestionChipsConfig)),hr(!Dn),ss(l);let m=[...l].reverse().find(A=>A.role==="user"),y=rt.lastUserMessageId;m&&m.id!==y&&(rt.lastUserMessageId=m.id,o.emit("user:message",m)),rt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),fo(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};Ie(ze,(L=>{var H,D,V,_;return L==="idle"?(H=m.idleText)!=null?H:rn.idle:L==="connecting"?(D=m.connectingText)!=null?D:rn.connecting:L==="connected"?(V=m.connectedText)!=null?V:rn.connected:L==="error"?(_=m.errorText)!=null?_:rn.error:rn[L]})(l),m,l)},onStreamingChanged(l){Dn=l,Vr(l),O&&Lr(me,O.getMessages(),j),l||hr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":Fn(),ls();break;case"speaking":Fn(),cs();break;default:l==="idle"&&O.isBargeInActive()?(Fn(),yr(),I==null||I.setAttribute("aria-label","End voice session")):(rt.active=!1,Fn(),Ln("system"),pn());break}},onArtifactsState(l){Hn=l,vn()}}),dr.current=O,((gi=(mi=n.voiceRecognition)==null?void 0:mi.provider)==null?void 0:gi.type)==="runtype")try{O.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&O.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ue||n.onSSEEvent)&&O.setSSEEventCallback((l,m)=>{var y;(y=n.onSSEEvent)==null||y.call(n,l,m),ue==null||ue.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=Ba(l.metadata),M.syncFromMetadata()),(m=l.messages)!=null&&m.length&&O.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let xo=l=>{var L;l.preventDefault();let m=ee.value.trim(),y=(L=qe==null?void 0:qe.hasAttachments())!=null?L:!1;if(!m&&!y)return;let A;y&&(A=[],A.push(...qe.getContentParts()),m&&A.push(Es(m))),ee.value="",ee.style.height="auto",O.sendMessage(m,{contentParts:A}),y&&qe.clearAttachments()},vo=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),le.click())},Co=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!qe)return;let m=Du(l.clipboardData);m.length!==0&&(l.preventDefault(),await qe.handleFiles(m))},an=null,An=!1,rr=null,Ze=null,wo=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Pr=(l="user")=>{var H,D,V,_,be,xe,Ae;if(An||O.isStreaming())return;let m=wo();if(!m)return;an=new m;let A=(D=((H=n.voiceRecognition)!=null?H:{}).pauseDuration)!=null?D:2e3;an.continuous=!0,an.interimResults=!0,an.lang="en-US";let L=ee.value;an.onresult=Ee=>{let De="",Ke="";for(let Qe=0;Qe<Ee.results.length;Qe++){let z=Ee.results[Qe],$e=z[0].transcript;z.isFinal?De+=$e+" ":Ke=$e}let ut=L+De+Ke;ee.value=ut,rr&&clearTimeout(rr),(De||Ke)&&(rr=window.setTimeout(()=>{let Qe=ee.value.trim();Qe&&an&&An&&(Nn(),ee.value="",ee.style.height="auto",O.sendMessage(Qe,{viaVoice:!0}))},A))},an.onerror=Ee=>{Ee.error!=="no-speech"&&Nn()},an.onend=()=>{if(An){let Ee=ee.value.trim();Ee&&Ee!==L.trim()&&(ee.value="",ee.style.height="auto",O.sendMessage(Ee,{viaVoice:!0})),Nn()}};try{if(an.start(),An=!0,rt.active=!0,l!=="system"&&(rt.manuallyDeactivated=!1),Ln(l),pn(),I){let Ee=(V=n.voiceRecognition)!=null?V:{};Ze={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(_=Ee.iconName)!=null?_:"mic",iconSize:parseFloat((Ae=(xe=Ee.iconSize)!=null?xe:(be=n.sendButton)==null?void 0:be.size)!=null?Ae:"40")||24};let De=Ee.recordingBackgroundColor,Ke=Ee.recordingIconColor,ut=Ee.recordingBorderColor;if(I.classList.add("persona-voice-recording"),I.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",I.style.color=Ke!=null?Ke:"var(--persona-voice-recording-indicator, #ffffff)",Ke){let Qe=I.querySelector("svg");Qe&&Qe.setAttribute("stroke",Ke)}ut&&(I.style.borderColor=ut),I.setAttribute("aria-label","Stop voice recognition")}}catch{Nn("system")}},Nn=(l="user")=>{if(An){if(An=!1,rr&&(clearTimeout(rr),rr=null),an){try{an.stop()}catch{}an=null}if(rt.active=!1,Ln(l),pn(),I){if(I.classList.remove("persona-voice-recording"),Ze){I.style.backgroundColor=Ze.backgroundColor,I.style.color=Ze.color,I.style.borderColor=Ze.borderColor;let m=I.querySelector("svg");m&&m.setAttribute("stroke",Ze.color||"currentColor"),Ze=null}I.setAttribute("aria-label","Start voice recognition")}}},is=(l,m)=>{var z,$e,je,ve,Ue,St,Ct,Jt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((z=l==null?void 0:l.provider)==null?void 0:z.type)==="runtype";if(!(y||A))return null;let H=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("aria-label","Start voice recognition");let V=($e=l==null?void 0:l.iconName)!=null?$e:"mic",_=(je=m==null?void 0:m.size)!=null?je:"40px",be=(ve=l==null?void 0:l.iconSize)!=null?ve:_,xe=parseFloat(be)||24,Ae=(Ue=l==null?void 0:l.backgroundColor)!=null?Ue:m==null?void 0:m.backgroundColor,Ee=(St=l==null?void 0:l.iconColor)!=null?St:m==null?void 0:m.textColor;D.style.width=be,D.style.height=be,D.style.minWidth=be,D.style.minHeight=be,D.style.fontSize="18px",D.style.lineHeight="1",Ee?D.style.color=Ee:D.style.color="var(--persona-text, #111827)";let Ke=fe(V,xe,Ee||"currentColor",1.5);Ke?D.appendChild(Ke):D.textContent="\u{1F3A4}",Ae?D.style.backgroundColor=Ae:D.style.backgroundColor="",l!=null&&l.borderWidth&&(D.style.borderWidth=l.borderWidth,D.style.borderStyle="solid"),l!=null&&l.borderColor&&(D.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(D.style.paddingLeft=l.paddingX,D.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(D.style.paddingTop=l.paddingY,D.style.paddingBottom=l.paddingY),H.appendChild(D);let ut=(Ct=l==null?void 0:l.tooltipText)!=null?Ct:"Start voice recognition";if(((Jt=l==null?void 0:l.showTooltip)!=null?Jt:!1)&&ut){let en=h("div","persona-send-button-tooltip");en.textContent=ut,H.appendChild(en)}return{micButton:D,micButtonWrapper:H}},Gr=()=>{var m,y,A,L,H;if(!I||Ze)return;let l=(m=n.voiceRecognition)!=null?m:{};Ze={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((H=(L=l.iconSize)!=null?L:(A=n.sendButton)==null?void 0:A.size)!=null?H:"40")||24}},Kr=(l,m)=>{var H,D,V,_,be;if(!I)return;let y=I.querySelector("svg");y&&y.remove();let A=(be=Ze==null?void 0:Ze.iconSize)!=null?be:parseFloat((_=(V=(H=n.voiceRecognition)==null?void 0:H.iconSize)!=null?V:(D=n.sendButton)==null?void 0:D.size)!=null?_:"40")||24,L=fe(l,A,m,1.5);L&&I.appendChild(L)},Wr=()=>{I&&I.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},yr=()=>{var L;if(!I)return;Gr();let l=(L=n.voiceRecognition)!=null?L:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,A=l.recordingBorderColor;if(Wr(),I.classList.add("persona-voice-recording"),I.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",I.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let H=I.querySelector("svg");H&&H.setAttribute("stroke",y)}A&&(I.style.borderColor=A),I.setAttribute("aria-label","Stop voice recognition")},ls=()=>{var V,_,be,xe,Ae,Ee,De,Ke;if(!I)return;Gr();let l=(V=n.voiceRecognition)!=null?V:{},m=O.getVoiceInterruptionMode(),y=(_=l.processingIconName)!=null?_:"loader",A=(xe=(be=l.processingIconColor)!=null?be:Ze==null?void 0:Ze.color)!=null?xe:"",L=(Ee=(Ae=l.processingBackgroundColor)!=null?Ae:Ze==null?void 0:Ze.backgroundColor)!=null?Ee:"",H=(Ke=(De=l.processingBorderColor)!=null?De:Ze==null?void 0:Ze.borderColor)!=null?Ke:"";Wr(),I.classList.add("persona-voice-processing"),I.style.backgroundColor=L,I.style.borderColor=H;let D=A||"currentColor";I.style.color=D,Kr(y,D),I.setAttribute("aria-label","Processing voice input"),m==="none"&&(I.style.cursor="default")},cs=()=>{var be,xe,Ae,Ee,De,Ke,ut,Qe,z,$e,je,ve;if(!I)return;Gr();let l=(be=n.voiceRecognition)!=null?be:{},m=O.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(xe=l.speakingIconName)!=null?xe:y,L=(Ke=l.speakingIconColor)!=null?Ke:m==="barge-in"?(Ee=(Ae=l.recordingIconColor)!=null?Ae:Ze==null?void 0:Ze.color)!=null?Ee:"":(De=Ze==null?void 0:Ze.color)!=null?De:"",H=(z=l.speakingBackgroundColor)!=null?z:m==="barge-in"?(ut=l.recordingBackgroundColor)!=null?ut:"var(--persona-voice-recording-bg, #ef4444)":(Qe=Ze==null?void 0:Ze.backgroundColor)!=null?Qe:"",D=(ve=l.speakingBorderColor)!=null?ve:m==="barge-in"?($e=l.recordingBorderColor)!=null?$e:"":(je=Ze==null?void 0:Ze.borderColor)!=null?je:"";Wr(),I.classList.add("persona-voice-speaking"),I.style.backgroundColor=H,I.style.borderColor=D;let V=L||"currentColor";I.style.color=V,Kr(A,V);let _=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";I.setAttribute("aria-label",_),m==="none"&&(I.style.cursor="default"),m==="barge-in"&&I.classList.add("persona-voice-recording")},Fn=()=>{var l,m,y;I&&(Wr(),Ze&&(I.style.backgroundColor=(l=Ze.backgroundColor)!=null?l:"",I.style.color=(m=Ze.color)!=null?m:"",I.style.borderColor=(y=Ze.borderColor)!=null?y:"",Kr(Ze.iconName,Ze.color||"currentColor"),Ze=null),I.style.cursor="",I.setAttribute("aria-label","Start voice recognition"))},Rr=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=O.getVoiceStatus(),A=O.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{rt.active=!1,rt.manuallyDeactivated=!0,pn(),Ln("user"),Fn()});return}O.toggleVoice().then(()=>{rt.active=O.isVoiceActive(),rt.manuallyDeactivated=!O.isVoiceActive(),pn(),Ln("user"),O.isVoiceActive()?yr():Fn()});return}if(An){let y=ee.value.trim();rt.manuallyDeactivated=!0,pn(),Nn("user"),y&&(ee.value="",ee.style.height="auto",O.sendMessage(y))}else rt.manuallyDeactivated=!1,pn(),Pr("user")};zt=Rr,I&&(I.addEventListener("click",Rr),wt.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Fn()):Nn("system"),I&&I.removeEventListener("click",Rr)}));let ds=o.on("assistant:complete",()=>{go&&(rt.active||rt.manuallyDeactivated||go==="assistant"&&!rt.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!rt.active&&!rt.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?O.toggleVoice().then(()=>{rt.active=O.isVoiceActive(),Ln("auto"),O.isVoiceActive()&&yr()}):Pr("auto"))},600))});wt.push(ds);let ps=o.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});wt.push(ps);let or=()=>{Ht(!E,"user")},Bt=null,Dt=null;if(w){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>Jo(n,or).element,onToggle:or});m&&(Dt=m)}Dt||(Bt=Jo(n,or))}Bt?e.appendChild(Bt.element):Dt&&e.appendChild(Dt),Ir(),Bn.render(n.suggestionChips,O,ee,void 0,n.suggestionChipsConfig),bo(),Vr(O.isStreaming()),hr(!0),ts(),k&&(w?E&&setTimeout(()=>Jr(),200):setTimeout(()=>Jr(),0));let br=()=>{var _,be,xe,Ae,Ee,De,Ke,ut,Qe,z,$e,je,ve,Ue,St,Ct,Jt,en,Re,un,tn,$n;let l=Yt(n),m=(be=(_=n.launcher)==null?void 0:_.sidebarMode)!=null?be:!1,y=l||m||((Ae=(xe=n.launcher)==null?void 0:xe.fullHeight)!=null?Ae:!1),A=(Ee=e.ownerDocument.defaultView)!=null?Ee:window,L=(Ke=(De=n.launcher)==null?void 0:De.mobileFullscreen)!=null?Ke:!0,H=(Qe=(ut=n.launcher)==null?void 0:ut.mobileBreakpoint)!=null?Qe:640,D=A.innerWidth<=H,V=L&&D&&w;try{if(V){Jn(),jr(e,n);return}if(B&&(B=!1,Jn(),jr(e,n)),!w&&!l){q.style.height="",q.style.width="";return}if(!m&&!l){let dt=($e=(z=n==null?void 0:n.launcher)==null?void 0:z.width)!=null?$e:n==null?void 0:n.launcherWidth,yt=dt!=null?dt:Pn;q.style.width=yt,q.style.maxWidth=yt}if(Vn(),!y){let dt=A.innerHeight,yt=64,mn=(ve=(je=n.launcher)==null?void 0:je.heightOffset)!=null?ve:0,ar=Math.max(200,dt-yt),et=Math.min(640,ar),Et=Math.max(200,et-mn);q.style.height=`${Et}px`}}finally{if(nt(),Ir(),E&&w){let yt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((Ct=(St=n.launcher)==null?void 0:St.mobileBreakpoint)!=null?Ct:640),mn=(en=(Jt=n.launcher)==null?void 0:Jt.sidebarMode)!=null?en:!1,ar=(un=(Re=n.launcher)==null?void 0:Re.mobileFullscreen)!=null?un:!0,et=Yt(n)&&ar&&yt,Et=mn||ar&&yt&&w||et;if(Et&&!$t){let Br=e.getRootNode(),Dr=Br instanceof ShadowRoot?Br.host:e.closest(".persona-host");Dr&&!Ot&&(Ot=ha(Dr,($n=(tn=n.launcher)==null?void 0:tn.zIndex)!=null?$n:hn)),$t=ya(e.ownerDocument)}else Et||(Ot==null||Ot(),Ot=null,$t==null||$t(),$t=null)}}};br();let So=(fi=e.ownerDocument.defaultView)!=null?fi:window;if(So.addEventListener("resize",br),wt.push(()=>So.removeEventListener("resize",br)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{nt()});l.observe(X),wt.push(()=>l.disconnect())}dn=U.scrollTop;let Ao=()=>{let l=U.scrollTop,{action:m,nextLastScrollTop:y}=Hs({following:cn.isFollowing(),currentScrollTop:l,lastScrollTop:dn,nearBottom:Uo(U,mo),userScrollThreshold:Qo,isAutoScrolling:Sn||er,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(dn=y,m==="resume"){fr();return}m==="pause"&&yo()};U.addEventListener("scroll",Ao,{passive:!0}),wt.push(()=>U.removeEventListener("scroll",Ao));let Eo=l=>{let m=Bs({following:cn.isFollowing(),deltaY:l.deltaY,nearBottom:Uo(U,mo),resumeWhenNearBottom:!0});m==="pause"?yo():m==="resume"&&fr()};U.addEventListener("wheel",Eo,{passive:!0}),wt.push(()=>U.removeEventListener("wheel",Eo)),ft.addEventListener("click",()=>{U.scrollTop=U.scrollHeight,dn=U.scrollTop,fr(),hr(!0)}),wt.push(()=>ft.remove()),wt.push(()=>{ho()});let To=()=>{ge&&(wn&&(ge.removeEventListener("click",wn),wn=null),w?(ge.style.display="",wn=()=>{Ht(!1,"user")},ge.addEventListener("click",wn)):ge.style.display="none")};To(),(()=>{let{clearChatButton:l}=ie;l&&l.addEventListener("click",()=>{O.clearMessages(),kn.clear(),fr();try{localStorage.removeItem(po),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${po}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==po)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},M.syncFromMetadata(),ue==null||ue.clear(),Y==null||Y.update()})})(),mt&&mt.addEventListener("submit",xo),ee==null||ee.addEventListener("keydown",vo),ee==null||ee.addEventListener("paste",Co);let Mo="persona-attachment-drop-active",xr=0,Yr=()=>{xr=0,F.classList.remove(Mo)},sr=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&qe!==null},ko=l=>{!qs(l.dataTransfer)||!sr()||(xr++,xr===1&&F.classList.add(Mo))},Hr=l=>{!qs(l.dataTransfer)||!sr()||(xr--,xr<=0&&Yr())},_e=l=>{!qs(l.dataTransfer)||!sr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},b=l=>{var y;if(!qs(l.dataTransfer)||!sr())return;l.preventDefault(),l.stopPropagation(),Yr();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&qe.handleFiles(m)},R=!0;F.addEventListener("dragenter",ko,R),F.addEventListener("dragleave",Hr,R),e.addEventListener("dragover",_e,R),e.addEventListener("drop",b,R);let C=e.ownerDocument,se=l=>{sr()&&l.preventDefault()},We=l=>{sr()&&l.preventDefault()};C.addEventListener("dragover",se),C.addEventListener("drop",We),wt.push(()=>{mt&&mt.removeEventListener("submit",xo),ee==null||ee.removeEventListener("keydown",vo),ee==null||ee.removeEventListener("paste",Co)}),wt.push(()=>{F.removeEventListener("dragenter",ko,R),F.removeEventListener("dragleave",Hr,R),e.removeEventListener("dragover",_e,R),e.removeEventListener("drop",b,R),C.removeEventListener("dragover",se),C.removeEventListener("drop",We),Yr()}),wt.push(()=>{O.cancel()}),Bt?wt.push(()=>{Bt==null||Bt.destroy()}):Dt&&wt.push(()=>{Dt==null||Dt.remove()});let N={update(l){var wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Fi,Oi,$i,_i,ji,zi,qi,Ui,Vi,Ji,Gi,Ki,Yi,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,zl,ql,Ul,Vl,Jl,Gl,Kl,Yl,Xl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc;let m=n.toolCall,y=n.messageActions,A=(wi=n.layout)==null?void 0:wi.messages,L=n.colorScheme,H=n.loadingIndicator,D=n.iterationDisplay,V=(Si=n.features)==null?void 0:Si.showReasoning,_=(Ai=n.features)==null?void 0:Ai.showToolCalls,be=(Ei=n.features)==null?void 0:Ei.toolCallDisplay,xe=(Ti=n.features)==null?void 0:Ti.reasoningDisplay;n={...n,...l},Jn(),jr(e,n),Os(e,n),$s(e,n),vn(),n.colorScheme!==L&&mr();let Ae=_s.getForInstance(n.plugins);s.length=0,s.push(...Ae),w=(ki=(Mi=n.launcher)==null?void 0:Mi.enabled)!=null?ki:!0,S=(Ii=(Li=n.launcher)==null?void 0:Li.autoExpand)!=null?Ii:!1,re=(Wi=(Pi=n.features)==null?void 0:Pi.showReasoning)!=null?Wi:!0,Te=(Hi=(Ri=n.features)==null?void 0:Ri.showToolCalls)!=null?Hi:!0,Ce=(Di=(Bi=n.features)==null?void 0:Bi.scrollToBottom)!=null?Di:{},vt(),nr();let Ee=oe;if(oe=(Fi=(Ni=n.features)==null?void 0:Ni.showEventStreamToggle)!=null?Fi:!1,oe&&!Ee){if(ue||(ke=new Zo(he),ue=new Xo(Be,ke),ke.open().then(()=>ue==null?void 0:ue.restore()).catch(()=>{}),O.setSSEEventCallback((J,gt)=>{var Mt;(Mt=n.onSSEEvent)==null||Mt.call(n,J,gt),ue.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(gt)})})),!it&&W){let J=($i=(Oi=n.features)==null?void 0:Oi.eventStream)==null?void 0:$i.classNames,gt="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"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");it=h("button",gt),it.style.width="28px",it.style.height="28px",it.style.color=yn.actionIconColor,it.type="button",it.setAttribute("aria-label","Event Stream"),it.title="Event Stream";let Mt=fe("activity","18px","currentColor",1.5);Mt&&it.appendChild(Mt);let tt=ie.clearChatButtonWrapper,bt=ie.closeButtonWrapper,Gt=tt||bt;Gt&&Gt.parentNode===W?W.insertBefore(it,Gt):W.appendChild(it),it.addEventListener("click",()=>{ye?Rn():Xn()})}}else!oe&&Ee&&(Rn(),it&&(it.remove(),it=null),ue==null||ue.clear(),ke==null||ke.destroy(),ue=null,ke=null);if(((_i=n.launcher)==null?void 0:_i.enabled)===!1&&Bt&&(Bt.destroy(),Bt=null),((ji=n.launcher)==null?void 0:ji.enabled)===!1&&Dt&&(Dt.remove(),Dt=null),((zi=n.launcher)==null?void 0:zi.enabled)!==!1&&!Bt&&!Dt){let J=s.find(gt=>gt.renderLauncher);if(J!=null&&J.renderLauncher){let gt=J.renderLauncher({config:n,defaultRenderer:()=>Jo(n,or).element,onToggle:or});gt&&(Dt=gt,e.appendChild(Dt))}Dt||(Bt=Jo(n,or),e.appendChild(Bt.element))}Bt&&Bt.update(n),Wt&&((qi=n.launcher)==null?void 0:qi.title)!==void 0&&(Wt.textContent=n.launcher.title),Rt&&((Ui=n.launcher)==null?void 0:Ui.subtitle)!==void 0&&(Rt.textContent=n.launcher.subtitle);let De=(Vi=n.layout)==null?void 0:Vi.header;if((De==null?void 0:De.layout)!==T&&W){let J=De?Go(n,De,{showClose:w,onClose:()=>Ht(!1,"user")}):Sr({config:n,showClose:w,onClose:()=>Ht(!1,"user")});W.replaceWith(J.header),W=J.header,Ge=J.iconHolder,Wt=J.headerTitle,Rt=J.headerSubtitle,ge=J.closeButton,T=De==null?void 0:De.layout}else if(De&&(Ge&&(Ge.style.display=De.showIcon===!1?"none":""),Wt&&(Wt.style.display=De.showTitle===!1?"none":""),Rt&&(Rt.style.display=De.showSubtitle===!1?"none":""),ge&&(ge.style.display=De.showCloseButton===!1?"none":""),ie.clearChatButtonWrapper)){let J=De.showClearChat;if(J!==void 0){ie.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:gt}=ie;gt&&!gt.classList.contains("persona-absolute")&&(J?gt.classList.remove("persona-ml-auto"):gt.classList.add("persona-ml-auto"))}}let ut=((Ji=n.layout)==null?void 0:Ji.showHeader)!==!1;W&&(W.style.display=ut?"":"none");let Qe=((Gi=n.layout)==null?void 0:Gi.showFooter)!==!1;X&&(X.style.display=Qe?"":"none"),nt(),nr(),w!==v?w?Ht(S,"auto"):(E=!0,Ir()):S!==$&&Ht(S,"auto"),$=S,v=w,br(),To();let je=JSON.stringify(l.toolCall)!==JSON.stringify(m),ve=JSON.stringify(n.messageActions)!==JSON.stringify(y),Ue=JSON.stringify((Ki=n.layout)==null?void 0:Ki.messages)!==JSON.stringify(A),St=((Yi=n.loadingIndicator)==null?void 0:Yi.render)!==(H==null?void 0:H.render)||((Xi=n.loadingIndicator)==null?void 0:Xi.renderIdle)!==(H==null?void 0:H.renderIdle)||((Zi=n.loadingIndicator)==null?void 0:Zi.showBubble)!==(H==null?void 0:H.showBubble),Ct=n.iterationDisplay!==D,Jt=((el=(Qi=n.features)==null?void 0:Qi.showReasoning)!=null?el:!0)!==(V!=null?V:!0)||((nl=(tl=n.features)==null?void 0:tl.showToolCalls)!=null?nl:!0)!==(_!=null?_:!0)||JSON.stringify((rl=n.features)==null?void 0:rl.toolCallDisplay)!==JSON.stringify(be)||JSON.stringify((ol=n.features)==null?void 0:ol.reasoningDisplay)!==JSON.stringify(xe);(je||ve||Ue||St||Ct||Jt)&&O&&(gr++,Lr(me,O.getMessages(),j));let Re=(sl=n.launcher)!=null?sl:{},un=(al=Re.headerIconHidden)!=null?al:!1,tn=(ll=(il=n.layout)==null?void 0:il.header)==null?void 0:ll.showIcon,$n=un||tn===!1,dt=Re.headerIconName,yt=(cl=Re.headerIconSize)!=null?cl:"48px";if(Ge){let J=F.querySelector(".persona-border-b-persona-divider"),gt=J==null?void 0:J.querySelector(".persona-flex-col");if($n)Ge.style.display="none",J&>&&!J.contains(gt)&&J.insertBefore(gt,J.firstChild);else{if(Ge.style.display="",Ge.style.height=yt,Ge.style.width=yt,J&>&&(J.contains(Ge)?Ge.nextSibling!==gt&&(Ge.remove(),J.insertBefore(Ge,gt)):J.insertBefore(Ge,gt)),dt){let tt=parseFloat(yt)||24,bt=fe(dt,tt*.6,"#ffffff",2);bt?Ge.replaceChildren(bt):Ge.textContent=(dl=Re.agentIconText)!=null?dl:"\u{1F4AC}"}else if(Re.iconUrl){let tt=Ge.querySelector("img");if(tt)tt.src=Re.iconUrl,tt.style.height=yt,tt.style.width=yt;else{let bt=document.createElement("img");bt.src=Re.iconUrl,bt.alt="",bt.className="persona-rounded-xl persona-object-cover",bt.style.height=yt,bt.style.width=yt,Ge.replaceChildren(bt)}}else{let tt=Ge.querySelector("svg"),bt=Ge.querySelector("img");(tt||bt)&&Ge.replaceChildren(),Ge.textContent=(pl=Re.agentIconText)!=null?pl:"\u{1F4AC}"}let Mt=Ge.querySelector("img");Mt&&(Mt.style.height=yt,Mt.style.width=yt)}}let mn=(ml=(ul=n.layout)==null?void 0:ul.header)==null?void 0:ml.showTitle,ar=(fl=(gl=n.layout)==null?void 0:gl.header)==null?void 0:fl.showSubtitle;if(Wt&&(Wt.style.display=mn===!1?"none":""),Rt&&(Rt.style.display=ar===!1?"none":""),ge){((yl=(hl=n.layout)==null?void 0:hl.header)==null?void 0:yl.showCloseButton)===!1?ge.style.display="none":ge.style.display="";let gt=(bl=Re.closeButtonSize)!=null?bl:"32px",Mt=(xl=Re.closeButtonPlacement)!=null?xl:"inline";ge.style.height=gt,ge.style.width=gt;let{closeButtonWrapper:tt}=ie,bt=Mt==="top-right",Gt=tt==null?void 0:tt.classList.contains("persona-absolute");if(tt&&bt!==Gt)if(tt.remove(),bt)tt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",F.style.position="relative",F.appendChild(tt);else{let lt=(Cl=(vl=Re.clearChat)==null?void 0:vl.placement)!=null?Cl:"inline",Kt=(Sl=(wl=Re.clearChat)==null?void 0:wl.enabled)!=null?Sl:!0;tt.className=Kt&<==="inline"?"":"persona-ml-auto";let fn=F.querySelector(".persona-border-b-persona-divider");fn&&fn.appendChild(tt)}if(ge.style.color=Re.closeButtonColor||yn.actionIconColor,Re.closeButtonBackgroundColor?(ge.style.backgroundColor=Re.closeButtonBackgroundColor,ge.classList.remove("hover:persona-bg-gray-100")):(ge.style.backgroundColor="",ge.classList.add("hover:persona-bg-gray-100")),Re.closeButtonBorderWidth||Re.closeButtonBorderColor){let lt=Re.closeButtonBorderWidth||"0px",Kt=Re.closeButtonBorderColor||"transparent";ge.style.border=`${lt} solid ${Kt}`,ge.classList.remove("persona-border-none")}else ge.style.border="",ge.classList.add("persona-border-none");Re.closeButtonBorderRadius?(ge.style.borderRadius=Re.closeButtonBorderRadius,ge.classList.remove("persona-rounded-full")):(ge.style.borderRadius="",ge.classList.add("persona-rounded-full")),Re.closeButtonPaddingX?(ge.style.paddingLeft=Re.closeButtonPaddingX,ge.style.paddingRight=Re.closeButtonPaddingX):(ge.style.paddingLeft="",ge.style.paddingRight=""),Re.closeButtonPaddingY?(ge.style.paddingTop=Re.closeButtonPaddingY,ge.style.paddingBottom=Re.closeButtonPaddingY):(ge.style.paddingTop="",ge.style.paddingBottom="");let nn=(Al=Re.closeButtonIconName)!=null?Al:"x",_n=(El=Re.closeButtonIconText)!=null?El:"\xD7";ge.innerHTML="";let ln=fe(nn,"28px","currentColor",1);ln?ge.appendChild(ln):ge.textContent=_n;let _t=(Tl=Re.closeButtonTooltipText)!=null?Tl:"Close chat",En=(Ml=Re.closeButtonShowTooltip)!=null?Ml:!0;if(ge.setAttribute("aria-label",_t),tt&&(tt._cleanupTooltip&&(tt._cleanupTooltip(),delete tt._cleanupTooltip),En&&_t)){let lt=null,Kt=()=>{if(lt||!ge)return;let Fr=ge.ownerDocument,Wo=Fr.body;if(!Wo)return;lt=Kn(Fr,"div","persona-clear-chat-tooltip"),lt.textContent=_t;let Ro=Kn(Fr,"div");Ro.className="persona-clear-chat-tooltip-arrow",lt.appendChild(Ro);let Or=ge.getBoundingClientRect();lt.style.position="fixed",lt.style.zIndex=String(Cr),lt.style.left=`${Or.left+Or.width/2}px`,lt.style.top=`${Or.top-8}px`,lt.style.transform="translate(-50%, -100%)",Wo.appendChild(lt)},fn=()=>{lt&<.parentNode&&(lt.parentNode.removeChild(lt),lt=null)};tt.addEventListener("mouseenter",Kt),tt.addEventListener("mouseleave",fn),ge.addEventListener("focus",Kt),ge.addEventListener("blur",fn),tt._cleanupTooltip=()=>{fn(),tt&&(tt.removeEventListener("mouseenter",Kt),tt.removeEventListener("mouseleave",fn)),ge&&(ge.removeEventListener("focus",Kt),ge.removeEventListener("blur",fn))}}}let{clearChatButton:et,clearChatButtonWrapper:Et}=ie;if(et){let J=(kl=Re.clearChat)!=null?kl:{},gt=(Ll=J.enabled)!=null?Ll:!0,Mt=(Pl=(Il=n.layout)==null?void 0:Il.header)==null?void 0:Pl.showClearChat,tt=Mt!==void 0?Mt:gt,bt=(Wl=J.placement)!=null?Wl:"inline";if(Et){Et.style.display=tt?"":"none";let{closeButtonWrapper:Gt}=ie;Gt&&!Gt.classList.contains("persona-absolute")&&(tt?Gt.classList.remove("persona-ml-auto"):Gt.classList.add("persona-ml-auto"));let nn=bt==="top-right",_n=Et.classList.contains("persona-absolute");if(nn!==_n&&tt){if(Et.remove(),nn)Et.className="persona-absolute persona-top-4 persona-z-50",Et.style.right="48px",F.style.position="relative",F.appendChild(Et);else{Et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Et.style.right="";let _t=F.querySelector(".persona-border-b-persona-divider"),En=ie.closeButtonWrapper;_t&&En&&En.parentElement===_t?_t.insertBefore(Et,En):_t&&_t.appendChild(Et)}let ln=ie.closeButtonWrapper;ln&&!ln.classList.contains("persona-absolute")&&(nn?ln.classList.add("persona-ml-auto"):ln.classList.remove("persona-ml-auto"))}}if(tt){let Gt=(Rl=J.size)!=null?Rl:"32px";et.style.height=Gt,et.style.width=Gt;let nn=(Hl=J.iconName)!=null?Hl:"refresh-cw",_n=(Bl=J.iconColor)!=null?Bl:"";et.style.color=_n||yn.actionIconColor,et.innerHTML="";let ln=fe(nn,"20px","currentColor",2);if(ln&&et.appendChild(ln),J.backgroundColor?(et.style.backgroundColor=J.backgroundColor,et.classList.remove("hover:persona-bg-gray-100")):(et.style.backgroundColor="",et.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let lt=J.borderWidth||"0px",Kt=J.borderColor||"transparent";et.style.border=`${lt} solid ${Kt}`,et.classList.remove("persona-border-none")}else et.style.border="",et.classList.add("persona-border-none");J.borderRadius?(et.style.borderRadius=J.borderRadius,et.classList.remove("persona-rounded-full")):(et.style.borderRadius="",et.classList.add("persona-rounded-full")),J.paddingX?(et.style.paddingLeft=J.paddingX,et.style.paddingRight=J.paddingX):(et.style.paddingLeft="",et.style.paddingRight=""),J.paddingY?(et.style.paddingTop=J.paddingY,et.style.paddingBottom=J.paddingY):(et.style.paddingTop="",et.style.paddingBottom="");let _t=(Dl=J.tooltipText)!=null?Dl:"Clear chat",En=(Nl=J.showTooltip)!=null?Nl:!0;if(et.setAttribute("aria-label",_t),Et&&(Et._cleanupTooltip&&(Et._cleanupTooltip(),delete Et._cleanupTooltip),En&&_t)){let lt=null,Kt=()=>{if(lt||!et)return;let Fr=et.ownerDocument,Wo=Fr.body;if(!Wo)return;lt=Kn(Fr,"div","persona-clear-chat-tooltip"),lt.textContent=_t;let Ro=Kn(Fr,"div");Ro.className="persona-clear-chat-tooltip-arrow",lt.appendChild(Ro);let Or=et.getBoundingClientRect();lt.style.position="fixed",lt.style.zIndex=String(Cr),lt.style.left=`${Or.left+Or.width/2}px`,lt.style.top=`${Or.top-8}px`,lt.style.transform="translate(-50%, -100%)",Wo.appendChild(lt)},fn=()=>{lt&<.parentNode&&(lt.parentNode.removeChild(lt),lt=null)};Et.addEventListener("mouseenter",Kt),Et.addEventListener("mouseleave",fn),et.addEventListener("focus",Kt),et.addEventListener("blur",fn),Et._cleanupTooltip=()=>{fn(),Et&&(Et.removeEventListener("mouseenter",Kt),Et.removeEventListener("mouseleave",fn)),et&&(et.removeEventListener("focus",Kt),et.removeEventListener("blur",fn))}}}}let Br=n.actionParsers&&n.actionParsers.length?n.actionParsers:[js],Dr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[co.message,co.messageAndClick];M=zs({parsers:Br,handlers:Dr,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),j=Sd(n,M,G),O.updateConfig(n),Lr(me,O.getMessages(),j),Bn.render(n.suggestionChips,O,ee,void 0,n.suggestionChipsConfig),bo(),Vr(O.isStreaming());let us=((Fl=n.voiceRecognition)==null?void 0:Fl.enabled)===!0,ms=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gs=(($l=(Ol=n.voiceRecognition)==null?void 0:Ol.provider)==null?void 0:$l.type)==="runtype";if(us&&(ms||gs))if(!I||!te){let J=is(n.voiceRecognition,n.sendButton);J&&(I=J.micButton,te=J.micButtonWrapper,Ve.insertBefore(te,Pt),I.addEventListener("click",Rr),I.disabled=O.isStreaming())}else{let J=(_l=n.voiceRecognition)!=null?_l:{},gt=(jl=n.sendButton)!=null?jl:{},Mt=(zl=J.iconName)!=null?zl:"mic",tt=(ql=gt.size)!=null?ql:"40px",bt=(Ul=J.iconSize)!=null?Ul:tt,Gt=parseFloat(bt)||24;I.style.width=bt,I.style.height=bt,I.style.minWidth=bt,I.style.minHeight=bt;let nn=(Jl=(Vl=J.iconColor)!=null?Vl:gt.textColor)!=null?Jl:"currentColor";I.innerHTML="";let _n=fe(Mt,Gt,nn,2);_n?I.appendChild(_n):I.textContent="\u{1F3A4}";let ln=(Gl=J.backgroundColor)!=null?Gl:gt.backgroundColor;ln?I.style.backgroundColor=ln:I.style.backgroundColor="",nn?I.style.color=nn:I.style.color="var(--persona-text, #111827)",J.borderWidth?(I.style.borderWidth=J.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),J.borderColor?I.style.borderColor=J.borderColor:I.style.borderColor="",J.paddingX?(I.style.paddingLeft=J.paddingX,I.style.paddingRight=J.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),J.paddingY?(I.style.paddingTop=J.paddingY,I.style.paddingBottom=J.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let _t=te==null?void 0:te.querySelector(".persona-send-button-tooltip"),En=(Kl=J.tooltipText)!=null?Kl:"Start voice recognition";if(((Yl=J.showTooltip)!=null?Yl:!1)&&En)if(_t)_t.textContent=En,_t.style.display="";else{let Kt=document.createElement("div");Kt.className="persona-send-button-tooltip",Kt.textContent=En,te==null||te.insertBefore(Kt,I)}else _t&&(_t.style.display="none");te.style.display="",I.disabled=O.isStreaming()}else I&&te&&(te.style.display="none",((Zl=(Xl=n.voiceRecognition)==null?void 0:Xl.provider)==null?void 0:Zl.type)==="runtype"?O.isVoiceActive()&&O.toggleVoice():An&&Nn());if(((Ql=n.attachments)==null?void 0:Ql.enabled)===!0)if(!Ye||!Z){let J=(ec=n.attachments)!=null?ec:{},Mt=(nc=((tc=n.sendButton)!=null?tc:{}).size)!=null?nc:"40px";ne||(ne=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ne.style.display="none",mt.insertBefore(ne,ee)),Pe||(Pe=document.createElement("input"),Pe.type="file",Pe.accept=((rc=J.allowedTypes)!=null?rc:ir).join(","),Pe.multiple=((oc=J.maxFiles)!=null?oc:4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),mt.insertBefore(Pe,ee)),Ye=h("div","persona-send-button-wrapper"),Z=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Z.type="button",Z.setAttribute("aria-label",(sc=J.buttonTooltipText)!=null?sc:"Attach file");let tt=(ac=J.buttonIconName)!=null?ac:"paperclip",bt=Mt,Gt=parseFloat(bt)||40,nn=Math.round(Gt*.6);Z.style.width=bt,Z.style.height=bt,Z.style.minWidth=bt,Z.style.minHeight=bt,Z.style.fontSize="18px",Z.style.lineHeight="1",Z.style.backgroundColor="transparent",Z.style.color="var(--persona-primary, #111827)",Z.style.border="none",Z.style.borderRadius="6px",Z.style.transition="background-color 0.15s ease",Z.addEventListener("mouseenter",()=>{Z.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Z.addEventListener("mouseleave",()=>{Z.style.backgroundColor="transparent"});let _n=fe(tt,nn,"currentColor",1.5);_n?Z.appendChild(_n):Z.textContent="\u{1F4CE}",Z.addEventListener("click",En=>{En.preventDefault(),Pe==null||Pe.click()}),Ye.appendChild(Z);let ln=(ic=J.buttonTooltipText)!=null?ic:"Attach file",_t=h("div","persona-send-button-tooltip");_t.textContent=ln,Ye.appendChild(_t),Fe.append(Ye),!qe&&Pe&&ne&&(qe=ro.fromConfig(J),qe.setPreviewsContainer(ne),Pe.addEventListener("change",async()=>{qe&&(Pe!=null&&Pe.files)&&(await qe.handleFileSelect(Pe.files),Pe.value="")})),F.querySelector(".persona-attachment-drop-overlay")||F.appendChild(Ad(J.dropOverlay))}else{Ye.style.display="";let J=(lc=n.attachments)!=null?lc:{};Pe&&(Pe.accept=((cc=J.allowedTypes)!=null?cc:ir).join(","),Pe.multiple=((dc=J.maxFiles)!=null?dc:4)>1),qe&&qe.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else Ye&&(Ye.style.display="none"),qe&&qe.clearAttachments(),(pc=F.querySelector(".persona-attachment-drop-overlay"))==null||pc.remove();let Ut=(uc=n.sendButton)!=null?uc:{},fs=(mc=Ut.useIcon)!=null?mc:!1,Lo=(gc=Ut.iconText)!=null?gc:"\u2191",gn=Ut.iconName,In=(fc=Ut.tooltipText)!=null?fc:"Send message",Xr=(hc=Ut.showTooltip)!=null?hc:!1,Io=(yc=Ut.size)!=null?yc:"40px",hs=Ut.backgroundColor,Nr=Ut.textColor;if(fs){if(le.style.width=Io,le.style.height=Io,le.style.minWidth=Io,le.style.minHeight=Io,le.style.fontSize="18px",le.style.lineHeight="1",le.innerHTML="",Nr?le.style.color=Nr:le.style.color="var(--persona-button-primary-fg, #ffffff)",gn){let J=parseFloat(Io)||24,gt=(Nr==null?void 0:Nr.trim())||"currentColor",Mt=fe(gn,J,gt,2);Mt?le.appendChild(Mt):le.textContent=Lo}else le.textContent=Lo;le.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",hs?(le.style.backgroundColor=hs,le.classList.remove("persona-bg-persona-primary")):(le.style.backgroundColor="",le.classList.add("persona-bg-persona-primary"))}else le.textContent=(xc=(bc=n.copy)==null?void 0:bc.sendButtonLabel)!=null?xc:"Send",le.style.width="",le.style.height="",le.style.minWidth="",le.style.minHeight="",le.style.fontSize="",le.style.lineHeight="",le.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",hs?(le.style.backgroundColor=hs,le.classList.remove("persona-bg-persona-accent")):le.classList.add("persona-bg-persona-accent"),Nr?le.style.color=Nr:le.classList.add("persona-text-white");Ut.borderWidth?(le.style.borderWidth=Ut.borderWidth,le.style.borderStyle="solid"):(le.style.borderWidth="",le.style.borderStyle=""),Ut.borderColor?le.style.borderColor=Ut.borderColor:le.style.borderColor="",Ut.paddingX?(le.style.paddingLeft=Ut.paddingX,le.style.paddingRight=Ut.paddingX):(le.style.paddingLeft="",le.style.paddingRight=""),Ut.paddingY?(le.style.paddingTop=Ut.paddingY,le.style.paddingBottom=Ut.paddingY):(le.style.paddingTop="",le.style.paddingBottom="");let Po=Pt==null?void 0:Pt.querySelector(".persona-send-button-tooltip");if(Xr&&In)if(Po)Po.textContent=In,Po.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=In,Pt==null||Pt.insertBefore(J,le)}else Po&&(Po.style.display="none");let ys=(vc=n.layout)==null?void 0:vc.contentMaxWidth;ys?(me.style.maxWidth=ys,me.style.marginLeft="auto",me.style.marginRight="auto",me.style.width="100%",mt&&(mt.style.maxWidth=ys,mt.style.marginLeft="auto",mt.style.marginRight="auto"),Je&&(Je.style.maxWidth=ys,Je.style.marginLeft="auto",Je.style.marginRight="auto")):(me.style.maxWidth="",me.style.marginLeft="",me.style.marginRight="",me.style.width="",mt&&(mt.style.maxWidth="",mt.style.marginLeft="",mt.style.marginRight=""),Je&&(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight=""));let vr=(Cc=n.statusIndicator)!=null?Cc:{},sp=(wc=vr.visible)!=null?wc:!0;if(ze.style.display=sp?"":"none",O){let J=O.getStatus();Ie(ze,(Mt=>{var tt,bt,Gt,nn;return Mt==="idle"?(tt=vr.idleText)!=null?tt:rn.idle:Mt==="connecting"?(bt=vr.connectingText)!=null?bt:rn.connecting:Mt==="connected"?(Gt=vr.connectedText)!=null?Gt:rn.connected:Mt==="error"?(nn=vr.errorText)!=null?nn:rn.error:rn[Mt]})(J),vr,J)}ze.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ap=vr.align==="left"?"persona-text-left":vr.align==="center"?"persona-text-center":"persona-text-right";ze.classList.add(ap)},open(){w&&Ht(!0,"api")},close(){w&&Ht(!1,"api")},toggle(){w&&Ht(!E,"api")},clearChat(){on=!1,O.clearMessages(),kn.clear(),fr();try{localStorage.removeItem(po),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${po}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==po)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},M.syncFromMetadata(),ue==null||ue.clear(),Y==null||Y.update()},setMessage(l){return!ee||O.isStreaming()?!1:(!E&&w&&Ht(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let m=(l==null?void 0:l.trim())||ee.value.trim();return m?(!E&&w&&Ht(!0,"system"),ee.value="",ee.style.height="auto",O.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return O.isStreaming()?!1:((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(O.isVoiceActive()||(!E&&w&&Ht(!0,"system"),rt.manuallyDeactivated=!1,pn(),O.toggleVoice().then(()=>{rt.active=O.isVoiceActive(),Ln("user"),O.isVoiceActive()&&yr()})),!0):An?!0:wo()?(!E&&w&&Ht(!0,"system"),rt.manuallyDeactivated=!1,pn(),Pr("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{rt.active=!1,rt.manuallyDeactivated=!0,pn(),Ln("user"),Fn()}),!0):!1:An?(rt.manuallyDeactivated=!0,pn(),Nn("user"),!0):!1},injectMessage(l){return!E&&w&&Ht(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!E&&w&&Ht(!0,"system");let m=O.injectAssistantMessage(l);return K&&(K=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),m},injectUserMessage(l){return!E&&w&&Ht(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!E&&w&&Ht(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!E&&w&&Ht(!0,"system"),O.injectMessageBatch(l)},injectTestMessage(l){!E&&w&&Ht(!0,"system"),O.injectTestEvent(l)},async connectStream(l,m){return O.connectStream(l,m)},__pushEventStreamEvent(l){ue&&ue.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!oe||!ue||Xn()},hideEventStream(){ye&&Rn()},isEventStreamVisible(){return ye},showArtifacts(){Wn(n)&&(on=!1,vn(),pt==null||pt.setMobileOpen(!0))},hideArtifacts(){Wn(n)&&(on=!0,vn())},upsertArtifact(l){return Wn(n)?(on=!1,O.upsertArtifact(l)):null},selectArtifact(l){Wn(n)&&O.selectArtifact(l)},clearArtifacts(){Wn(n)&&O.clearArtifacts()},focusInput(){return w&&!E||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,m){let A=O.getMessages().find(L=>{var H;return L.variant==="approval"&&((H=L.approval)==null?void 0:H.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return O.resolveApproval(A.approval,m)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return w&&E},isVoiceActive(){return rt.active},getState(){return{open:w&&E,launcherEnabled:w,voiceActive:rt.active,streaming:O.isStreaming()}},showCSATFeedback(l){!E&&w&&Ht(!0,"system");let m=me.querySelector(".persona-feedback-container");m&&m.remove();let y=Ra({onSubmit:async(A,L)=>{var H;O.isClientTokenMode()&&await O.submitCSATFeedback(A,L),(H=l==null?void 0:l.onSubmit)==null||H.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});me.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&w&&Ht(!0,"system");let m=me.querySelector(".persona-feedback-container");m&&m.remove();let y=Ha({onSubmit:async(A,L)=>{var H;O.isClientTokenMode()&&await O.submitNPSFeedback(A,L),(H=l==null?void 0:l.onSubmit)==null||H.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});me.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return O.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return O.submitNPSFeedback(l,m)},destroy(){Gn!=null&&(clearInterval(Gn),Gn=null),wt.forEach(l=>l()),P.remove(),Bt==null||Bt.destroy(),Dt==null||Dt.remove(),wn&&ge.removeEventListener("click",wn)}};if((((hi=t==null?void 0:t.debugTools)!=null?hi:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:N,getMessages:N.getMessages,getStatus:N.getStatus,getMetadata:N.getPersistentMetadata,updateMetadata:N.updatePersistentMetadata,clearHistory:()=>N.clearChat(),setVoiceActive:y=>y?N.startVoiceRecognition():N.stopVoiceRecognition()};window.AgentWidgetBrowser=m,wt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=V=>{let _=V.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&N.focusInput()};if(window.addEventListener("persona:focusInput",m),wt.push(()=>{window.removeEventListener("persona:focusInput",m)}),oe){let V=be=>{let xe=be.detail;(!(xe!=null&&xe.instanceId)||xe.instanceId===l)&&N.showEventStream()},_=be=>{let xe=be.detail;(!(xe!=null&&xe.instanceId)||xe.instanceId===l)&&N.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",_),wt.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",_)})}let y=V=>{let _=V.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&N.showArtifacts()},A=V=>{let _=V.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&N.hideArtifacts()},L=V=>{let _=V.detail;_!=null&&_.instanceId&&_.instanceId!==l||_!=null&&_.artifact&&N.upsertArtifact(_.artifact)},H=V=>{let _=V.detail;_!=null&&_.instanceId&&_.instanceId!==l||typeof(_==null?void 0:_.id)=="string"&&N.selectArtifact(_.id)},D=V=>{let _=V.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&N.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",D),wt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",D)})}let Oe=Nu(n.persistState);if(Oe&&w){let l=Fu(Oe.storage),m=`${Oe.keyPrefix}widget-open`,y=`${Oe.keyPrefix}widget-voice`,A=`${Oe.keyPrefix}widget-voice-mode`;if(l){let L=((yi=Oe.persist)==null?void 0:yi.openState)&&l.getItem(m)==="true",H=((bi=Oe.persist)==null?void 0:bi.voiceState)&&l.getItem(y)==="true",D=((xi=Oe.persist)==null?void 0:xi.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{N.open(),setTimeout(()=>{var V;if(H||D)N.startVoiceRecognition();else if((V=Oe.persist)!=null&&V.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(vi=Oe.persist)!=null&&vi.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(Ci=Oe.persist)!=null&&Ci.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(A,V.viaVoice?"true":"false")})),Oe.clearOnChatClear){let V=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(A)},_=()=>V();window.addEventListener("persona:clear-chat",_),wt.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return c&&w&&setTimeout(()=>{N.open()},0),N};var Ou=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},Ed=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.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"},$a=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=""},Td=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",$a(e)},Na=e=>{e.style.transition=""},Fa=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=""},Oa=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Us=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},$u=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},_u=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},Md=(e,r,t,n,s,o,a)=>{var x,M,w,S,k,$;let i=jn(o),u=i.reveal==="push";$u(e,r,t,n,u),_u(e,r,t,n,i.side,u),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 c=e.ownerDocument.defaultView,p=(M=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?M:!0,d=(S=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=d:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Fa(r),Na(n),Td(n),Oa(t),Us(s,n),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",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(($=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?$:hn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.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"),Td(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Fa(r),Na(n),Oa(t),Us(s,n);let v=i.animate?"transform 180ms ease":"none",T=i.side==="right"?"translateX(100%)":"translateX(-100%)",B=a?"translateX(0)":T;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=v,n.style.transform=B,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.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",Na(n),$a(n),Us(s,n);let v=Ou(i.width,e.clientWidth),T=Math.max(0,e.clientWidth),B=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${v}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${v}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${T+v}px`,r.style.transition=B,r.style.transform=E,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${T}px`,t.style.maxWidth=`${T}px`,t.style.minWidth=`${T}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Fa(r),$a(n),Oa(t),Us(s,n);let v=i.reveal==="emerge";v?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let T=a?i.width:"0px",B=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${T}`,n.style.width=T,n.style.maxWidth=T,n.style.minWidth=T,n.style.minHeight="0",n.style.position="relative",n.style.overflow=v||E?"hidden":"visible",n.style.transition=B,v&&(n.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")}},ju=(e,r)=>{let t=e.ownerDocument.createElement("div");return Ed(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Ed(t,n)},destroy(){t.remove()}}},zu=(e,r)=>{var k,$,v,T;let{ownerDocument:t}=e,n=e.parentElement;if(!n)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"),u=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),d=($=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)==null||$?(T=(v=r==null?void 0:r.launcher)==null?void 0:v.autoExpand)!=null?T:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),u.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),jn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Md(a,i,u,c,p,r,d)}),f.observe(a))},M=()=>{Md(a,i,u,c,p,r,d),x()},w=a.ownerDocument.defaultView,S=()=>{M()};return w==null||w.addEventListener("resize",S),jn(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(B){let E=B.launcherEnabled?B.open:!0;d!==E&&(d=E,M())},updateConfig(B){var E,K;r=B,((K=(E=r==null?void 0:r.launcher)==null?void 0:E.enabled)!=null?K:!0)===!1&&(d=!0),M()},destroy(){w==null||w.removeEventListener("resize",S),g(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Vs=(e,r)=>Yt(r)?zu(e,r):ju(e,r);var _a={},qu=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 r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},Uu=()=>{try{if(typeof _a!="undefined"&&_a.url)return new URL("../widget.css",_a.url).href}catch{}return null},kd=(e,r)=>{let t=Uu(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.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=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},Ld=e=>{var w;let r=qu(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Vs(r,s),a,i=[],u=(S,k)=>{var B,E;let v=!((E=(B=k==null?void 0:k.launcher)==null?void 0:B.enabled)!=null?E:!0)||Yt(k),T=n.createElement("div");if(T.setAttribute("data-persona-root","true"),v&&(T.style.height="100%",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1",T.style.minHeight="0"),t){let K=S.attachShadow({mode:"open"});K.appendChild(T),kd(K,n)}else S.appendChild(T),kd(S,n);return r.id&&T.setAttribute("data-persona-instance",r.id),T},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let S=u(o.host,s);a=Da(S,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};d(),(w=e.onReady)==null||w.call(e);let g=S=>{f(),o.destroy(),o=Vs(r,S),s=S,d()},x={update(S){var T,B,E,K,Q,G;let k={...s,...S,launcher:{...(T=s==null?void 0:s.launcher)!=null?T:{},...(B=S==null?void 0:S.launcher)!=null?B:{},dock:{...(K=(E=s==null?void 0:s.launcher)==null?void 0:E.dock)!=null?K:{},...(G=(Q=S==null?void 0:S.launcher)==null?void 0:Q.dock)!=null?G:{}}}},$=Yt(s),v=Yt(k);if($!==v){g(k);return}s=k,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},M=new Proxy(x,{get(S,k,$){if(k==="host")return o.host;if(k in S)return Reflect.get(S,k,$);let v=a[k];return typeof v=="function"?v.bind(a):v}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=M),M};var Hd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Vu=new Set(["button","a","input","select","textarea","details","summary"]),Ju=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ja=/\b(product|card|item|listing|result)\b/i,qa=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Gu=3e3,Ku=100;function Bd(e){let r=typeof e.className=="string"?e.className:"";if(ja.test(r)||e.id&&ja.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&ja.test(n.value))return!0}return!1}function Dd(e){var r;return qa.test(((r=e.textContent)!=null?r:"").trim())}function Nd(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Yu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Id(e){let r=e.match(qa);return r?r[0]:null}function Pd(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.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 Xu(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var Zu="commerce-card",Qu="result-card";function Wd(e){return!Bd(e)||!Dd(e)||!Nd(e)&&!Yu(e)?0:5200}function Rd(e){var n;return!Bd(e)||Dd(e)||!Nd(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Fd=[{id:Zu,scoreElement(e){return Wd(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||qa.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,p;if(Wd(e)===0)return null;let{title:t,href:n}=Pd(e),s=(p=(c=Id(((u=e.textContent)!=null?u:"").trim()))!=null?c:Id(r.text))!=null?p:"",o=Xu(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
100
|
+
`)}},{id:Qu,scoreElement(e){return Rd(e)},formatSummary(e,r){if(Rd(e)===0)return null;let{title:t,href:n}=Pd(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
|
|
101
|
+
`)}}];function em(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function tm(e){var p,d,f,g,x,M,w,S,k,$,v,T,B;let r=(p=e.options)!=null?p:{},t=(f=(d=r.maxElements)!=null?d:e.maxElements)!=null?f:80,n=(x=(g=r.excludeSelector)!=null?g:e.excludeSelector)!=null?x:".persona-host",s=(w=(M=r.maxTextLength)!=null?M:e.maxTextLength)!=null?w:200,o=(k=(S=r.visibleOnly)!=null?S:e.visibleOnly)!=null?k:!0,a=($=r.root)!=null?$:e.root,i=(v=r.mode)!=null?v:"structured",u=(T=r.maxCandidates)!=null?T:Math.max(500,t*10),c=(B=e.rules)!=null?B:Fd;return i==="simple"&&e.rules&&e.rules.length>0?(em(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:u,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function za(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var nm=["data-testid","data-product","data-action","data-id","data-name","data-type"];function rm(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||Vu.has(r)||t&&Ju.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Od(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function om(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let u=e.getAttribute("role");u&&(r.role=u);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(r[p.name]=p.value)}return r}function $d(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${za(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of nm){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${za(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=`${r}.${t.map(a=>za(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 > ${r}`)).indexOf(e);if(i>=0){let u=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function sm(e){return e==="static"?Ku:Gu}function _d(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:$d(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:rm(e),attributes:om(e)}}function am(e,r,t,n){let s=sm(r.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,r,n);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function im(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function lm(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(Hd.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Od(c)){i=a.nextNode();continue}let d=_d(c,e.maxTextLength),f=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(w=>w==="role");if(!f&&!g){i=a.nextNode();continue}if(n.has(d.selector)){i=a.nextNode();continue}n.add(d.selector);let{score:x,formattingRule:M}=am(c,d,e.rules,t);s.push({el:c,domIndex:o,enriched:d,score:x,formattingRule:M}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let d=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return d!==f?d-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let u=[];for(let c of s){if(u.length>=e.maxElements)break;im(u,c)||u.push(c)}return u.sort((c,p)=>{let d=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return d!==f?d-f:d===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),u.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,t);g&&(p=g)}let d={...c.enriched};return p&&(d.formattedSummary=p),d})}function cm(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let u=o,c=u.tagName.toLowerCase();if(Hd.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Od(u)){o=s.nextNode();continue}let p=_d(u,e.maxTextLength),d=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!d&&!f){o=s.nextNode();continue}n.has(p.selector)||(n.add(p.selector),t.push(p))}o=s.nextNode()}let a=[],i=[];for(let u of t)u.interactivity!=="static"?a.push(u):i.push(u);return[...a,...i].slice(0,e.maxElements)}function dm(e={}){var n;let r=tm(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?cm(r,t):lm(r,t):[]}var Js=100;function pm(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"structured",n=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
|
|
102
102
|
${a.map(i=>`- ${i.split(`
|
|
103
103
|
`).join(`
|
|
104
104
|
`)}`).join(`
|
|
105
|
-
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
105
|
+
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Js)}" (clickable)`);n.push(`Interactive elements:
|
|
106
106
|
${a.join(`
|
|
107
|
-
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,
|
|
107
|
+
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Js)}" (navigable)`);n.push(`Navigation links:
|
|
108
108
|
${a.join(`
|
|
109
|
-
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,
|
|
109
|
+
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Js)}" (input)`);n.push(`Form inputs:
|
|
110
110
|
${a.join(`
|
|
111
|
-
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
111
|
+
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Js)}"`);n.push(`Content:
|
|
112
112
|
${a.join(`
|
|
113
113
|
`)}`)}return n.join(`
|
|
114
114
|
|
|
115
|
-
`)}var
|
|
115
|
+
`)}var jd={name:"@runtypelabs/persona",version:"3.16.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"},"./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:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --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,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{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:{"@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",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 uo=jd.version;function lr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function mm(e){if(e)return{getHeaders:lr(e.getHeaders),onFeedback:lr(e.onFeedback),onCopy:lr(e.onCopy),requestMiddleware:lr(e.requestMiddleware),actionHandlers:lr(e.actionHandlers),actionParsers:lr(e.actionParsers),postprocessMessage:lr(e.postprocessMessage),contextProviders:lr(e.contextProviders),streamParser:lr(e.streamParser)}}var zd=`({ text, message }: any) => {
|
|
116
116
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
117
117
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
118
118
|
let cleanJson = jsonSource
|
|
@@ -125,7 +125,7 @@ ${a.join(`
|
|
|
125
125
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
126
126
|
} catch (e) { return null; }
|
|
127
127
|
return null;
|
|
128
|
-
}`,
|
|
128
|
+
}`,qd=`function(ctx) {
|
|
129
129
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
130
130
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
131
131
|
var cleanJson = jsonSource
|
|
@@ -138,7 +138,7 @@ ${a.join(`
|
|
|
138
138
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
139
139
|
} catch (e) { return null; }
|
|
140
140
|
return null;
|
|
141
|
-
}`,
|
|
141
|
+
}`,Ud=`(action: any, context: any) => {
|
|
142
142
|
if (action.type !== 'nav_then_click') return;
|
|
143
143
|
const payload = action.payload || action.raw || {};
|
|
144
144
|
const url = payload?.page;
|
|
@@ -155,7 +155,7 @@ ${a.join(`
|
|
|
155
155
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
156
156
|
window.location.href = targetUrl;
|
|
157
157
|
return { handled: true, displayText: text };
|
|
158
|
-
}`,
|
|
158
|
+
}`,Vd=`function(action, context) {
|
|
159
159
|
if (action.type !== 'nav_then_click') return;
|
|
160
160
|
var payload = action.payload || action.raw || {};
|
|
161
161
|
var url = payload.page;
|
|
@@ -172,26 +172,26 @@ ${a.join(`
|
|
|
172
172
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
173
173
|
window.location.href = targetUrl;
|
|
174
174
|
return { handled: true, displayText: text };
|
|
175
|
-
}`,
|
|
175
|
+
}`,gm=`(parsed: any) => {
|
|
176
176
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
177
177
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
178
178
|
if (parsed.action === 'message') return parsed.text || '';
|
|
179
179
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
180
180
|
return parsed.text || null;
|
|
181
|
-
}`,
|
|
181
|
+
}`,fm=`function(parsed) {
|
|
182
182
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
183
183
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
184
184
|
if (parsed.action === 'message') return parsed.text || '';
|
|
185
185
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
186
186
|
return parsed.text || null;
|
|
187
|
-
}`;function
|
|
188
|
-
`)}function
|
|
189
|
-
`)}function xm(e,r){let t=r==null?void 0:r.hooks,n=["// 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&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vr(n,"theme",e.theme," "),e.launcher&&vr(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...Ds(e," ")),n.push(...Ns(e," ",t)),n.push(...Fs(e," ")),n.push(...Os(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${mm}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${jd}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${jd}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${qd}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${qd}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
|
|
190
|
-
`)}function
|
|
191
|
-
`)}function
|
|
187
|
+
}`;function hm(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function Gs(e){var r,t;return(t=(r=e.parserType)!=null?r:hm(e.streamParser))!=null?t:"plain"}function Ks(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,s])=>{typeof s=="string"&&t.push(`${r} ${n}: "${s}",`)}),t.push(`${r}},`)),t}function Ys(e,r,t){let n=[],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)&&(n.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?n.push(`${r} ${a}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${a}: ${i},`))}),t!=null&&t.onFeedback&&n.push(`${r} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&n.push(`${r} onCopy: ${t.onCopy},`),n.push(`${r}},`)),n}function Xs(e,r){let t=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(n||s)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`)}),t.push(`${r} },`)),s&&t.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${r}},`))}return t}function Zs(e,r){let t=[];if(e.layout){let n=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");(n||s)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),s&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${r} avatar: {`),Object.entries(a).forEach(([i,u])=>{typeof u=="string"?t.push(`${r} ${i}: "${u}",`):typeof u=="boolean"&&t.push(`${r} ${i}: ${u},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([u])=>u!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?t.push(`${r} ${u}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${u}: ${c},`))}),t.push(`${r} },`)):typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function Ua(e,r){let t=[];return e&&(e.getHeaders&&t.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${r}streamParser: ${e.streamParser},`)),t}function Jd(e,r,t){Object.entries(r).forEach(([n,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${n}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${n}: {`),Jd(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Er(e,r,t,n){t&&(e.push(`${n}${r}: {`),Jd(e,t,`${n} `),e.push(`${n}},`))}function ym(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:mm(t.hooks)}:void 0;return r==="esm"?bm(n,s):r==="script-installer"?Cm(n,s):r==="script-advanced"?Sm(n,s):r==="react-component"?xm(n,s):r==="react-advanced"?vm(n,s):wm(n,s)}function bm(e,r){let t=r==null?void 0:r.hooks,n=Gs(e),s=n!=="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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Er(o,"theme",e.theme," "),e.launcher&&Er(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(...Ks(e," ")),o.push(...Ys(e," ",t)),o.push(...Xs(e," ")),o.push(...Zs(e," ")),o.push(...Ua(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(`
|
|
188
|
+
`)}function xm(e,r){let t=r==null?void 0:r.hooks,n=Gs(e),s=n!=="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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Er(o,"theme",e.theme," "),e.launcher&&Er(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(...Ks(e," ")),o.push(...Ys(e," ",t)),o.push(...Xs(e," ")),o.push(...Zs(e," ")),o.push(...Ua(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(`
|
|
189
|
+
`)}function vm(e,r){let t=r==null?void 0:r.hooks,n=["// 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&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Er(n,"theme",e.theme," "),e.launcher&&Er(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...Ks(e," ")),n.push(...Ys(e," ",t)),n.push(...Xs(e," ")),n.push(...Zs(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${gm}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${zd}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${zd}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${Ud}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${Ud}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
|
|
190
|
+
`)}function Gd(e){var s;let r=Gs(e),t=r!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),t&&(n.parserType=r),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.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&&(n.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&&(n.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&&(n.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,u])=>{i!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,u])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof u=="object"&&u!==null)a.avatar=u;else if(i==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[p]=d)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Cm(e,r){let t=Gd(e),n=r!=null&&r.windowKey?{config:t,windowKey:r.windowKey}:t,s=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${uo}/dist/install.global.js" data-config='${s}'></script>`}function wm(e,r){let t=r==null?void 0:r.hooks,n=Gs(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${uo}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${uo}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...r!=null&&r.windowKey?[` windowKey: '${r.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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Er(o,"theme",e.theme," "),e.launcher&&Er(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(...Ks(e," ")),o.push(...Ys(e," ",t)),o.push(...Xs(e," ")),o.push(...Zs(e," ")),o.push(...Ua(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(`
|
|
191
|
+
`)}function Sm(e,r){let t=r==null?void 0:r.hooks,n=Gd(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
|
|
192
192
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
193
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
194
|
-
`)}var
|
|
193
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${uo}/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(${fm});`),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(` ${qd}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${qd}`),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(` ${Vd}`),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(` ${Vd}`),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,",...r!=null&&r.windowKey?[` windowKey: '${r.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(`
|
|
194
|
+
`)}var Kd={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Yd=.1,Xd=.15,Zd=1.5,Va=24,Qd=40,Am=`
|
|
195
195
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
196
196
|
.persona-dc-root {
|
|
197
197
|
display: flex;
|
|
@@ -342,7 +342,7 @@ ${a.join(`
|
|
|
342
342
|
.persona-dc-stage {
|
|
343
343
|
height: 550px;
|
|
344
344
|
min-height: 400px;
|
|
345
|
-
padding: ${
|
|
345
|
+
padding: ${Va}px;
|
|
346
346
|
overflow: auto;
|
|
347
347
|
background: #f0f1f3;
|
|
348
348
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -432,5 +432,5 @@ ${a.join(`
|
|
|
432
432
|
min-height: 300px;
|
|
433
433
|
}
|
|
434
434
|
}
|
|
435
|
-
`;function Am(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Sm,document.head.appendChild(e)}function Em(e,r){let t=e.clientWidth-Wa*2-Zd,n=e.clientHeight-Wa*2-Zd;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Tm(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Mm(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Am();let p=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,g=null,x=1,T=!1,C=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),M=h("div","persona-dc-toolbar-lead"),H=h("div","persona-dc-toolbar-trail"),w=Pt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Be(-1)}),L=h("div");L.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 E=h("span","persona-dc-title-text"),K=h("span","persona-dc-title-chevron"),Q=ye("chevron-down",12,"currentColor",2);Q&&K.appendChild(Q),W.append(E,K);let X=h("div","persona-dc-dropdown");X.setAttribute("role","listbox"),X.style.display="none";let O=!1;function oe(){X.innerHTML="";for(let N=0;N<t.length;N++){let J=t[N],ce=h("button","persona-dc-dropdown-item");ce.type="button",ce.setAttribute("role","option"),ce.setAttribute("aria-current",N===p?"true":"false");let fe=h("span");if(fe.textContent=J.title,ce.appendChild(fe),J.description){let te=h("span","persona-dc-dropdown-desc");te.textContent=J.description,ce.appendChild(te)}ce.addEventListener("click",()=>{ae(),st(N)}),X.appendChild(ce)}}function Ee(){O=!O,X.style.display=O?"":"none",W.setAttribute("aria-expanded",O?"true":"false"),O&&oe()}function ae(){O&&(O=!1,X.style.display="none",W.setAttribute("aria-expanded","false"))}W.addEventListener("click",N=>{N.stopPropagation(),Ee()});let we=()=>ae();document.addEventListener("click",we),L.append(W,X);let $e=Pt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Be(1)}),he=h("span","persona-dc-counter");M.append(w,L,$e,he);let We=null;i&&(We=Es({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:N=>{d=N,V.dataset.device=d,g=null,z()}}),H.appendChild(We.element));let Re=null;if(a){let N=h("div","persona-dc-zoom-controls"),J=Pt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let te=g!=null?g:x;g=Math.max(Kd,te-Yd),z()}});Re=h("span","persona-dc-zoom-level"),Re.title="Reset to 100%",Re.style.cursor="pointer",Re.addEventListener("click",()=>{g=1,z()});let ce=Pt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let te=g!=null?g:x;g=Math.min(Xd,te+Yd),z()}}),fe=Pt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,z()}});N.append(J,Re,ce,fe),H.appendChild(N)}if(u){let N=h("div","persona-dc-separator");H.appendChild(N);let J=Es({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ce=>{f=ce,V.dataset.colorScheme=f,He()}});H.appendChild(J.element)}let ie=h("div","persona-dc-separator");H.appendChild(ie);let Z=Pt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});H.appendChild(Z),S.append(M,H);let me=h("div","persona-dc-stage"),V=h("div","persona-dc-iframe-wrapper");V.dataset.device=d,V.dataset.colorScheme=f;let re=h("iframe","persona-dc-iframe");re.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),re.setAttribute("loading","lazy"),re.title=t[p].title,V.appendChild(re),me.appendChild(V),C.append(S,me),e.appendChild(C);function He(){var N;try{let J=(N=re.contentDocument)==null?void 0:N.body;if(!J)return;f==="dark"?J.classList.add("theme-dark"):J.classList.remove("theme-dark")}catch{}}re.addEventListener("load",()=>He());function ge(){let N=t[p];E.textContent=N.title,he.textContent=`${p+1} / ${t.length}`,re.title=N.title}function Be(N){let J=((p+N)%t.length+t.length)%t.length;st(J)}function st(N){N<0||N>=t.length||(p=N,re.src=t[p].url,ge(),c==null||c(p,t[p]))}function z(){var ce;if(T)return;let N=(ce=Gd[d])!=null?ce:Gd.desktop;x=Em(me,N);let J=Math.max(Kd,Math.min(Xd,g!=null?g:x));Tm(V,re,N,J,d),Re&&(Re.textContent=`${Math.round(J*100)}%`)}let U=new ResizeObserver(()=>z());U.observe(me),ge(),re.src=t[p].url,requestAnimationFrame(()=>z());function se(){T||(T=!0,U.disconnect(),document.removeEventListener("click",we),C.remove())}return{element:C,goTo:st,next:()=>Be(1),prev:()=>Be(-1),getIndex:()=>p,setDevice(N){d=N,V.dataset.device=N,We==null||We.setSelected(N),g=null,z()},setColorScheme(N){f=N,V.dataset.colorScheme=N},setZoom(N){g=N,z()},destroy:se}}function km(){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 Lm(){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 Im(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:Yn(e.colors.primary,.95),100:Yn(e.colors.primary,.9),200:Yn(e.colors.primary,.8),300:Yn(e.colors.primary,.7),400:Yn(e.colors.primary,.6),500:e.colors.primary,600:Yn(e.colors.primary,.8),700:Yn(e.colors.primary,.7),800:Yn(e.colors.primary,.6),900:Yn(e.colors.primary,.5),950:Yn(e.colors.primary,.45)}}),{...r,palette:t}}}}function Pm(){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 Wm(){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 Yn(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Rm(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Hm={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"}}},Qd={components:{panel:{borderRadius:"0",shadow:"none"}}},ep={id:"shop",label:"Shopping Assistant",config:{theme:Hm,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:In},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?"]}},tp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Qd}},np={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Qd}},rp={shop:ep,minimal:tp,fullscreen:np};function Bm(e){return rp[e]}var By=kd;export{Gr as AgentWidgetClient,ko as AgentWidgetSession,Xr as AttachmentManager,_c as DEFAULT_COMPONENTS,Xs as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,In as DEFAULT_FLOATING_LAUNCHER_WIDTH,Oc as DEFAULT_PALETTE,$c as DEFAULT_SEMANTIC,Lt as DEFAULT_WIDGET_CONFIG,rp as PRESETS,np as PRESET_FULLSCREEN,tp as PRESET_MINIMAL,ep as PRESET_SHOP,Np as THEME_ZONES,so as VERSION,km as accessibilityPlugin,Lm as animationsPlugin,Dr as applyThemeVariables,Zr as attachHeaderToContainer,Im as brandPlugin,No as buildComposer,Zc as buildDefaultHeader,br as buildHeader,Do as buildHeaderWithLayout,Qc as buildMinimalHeader,cm as collectEnrichedPageContext,xr as componentRegistry,Is as createActionManager,wa as createAgentExperience,Ks as createBestAvailableVoiceProvider,Zp as createBubbleWithLayout,xa as createCSATFeedback,oa as createComboButton,Pu as createComponentMiddleware,fa as createComponentStreamParser,Tc as createDefaultSanitizer,Mm as createDemoCarousel,cp as createDirectivePostprocessor,Nr as createDropdownMenu,yp as createFlexibleJsonStreamParser,Pt as createIconButton,Tp as createImagePart,Vs as createJsonStreamParser,As as createLabelButton,ga as createLocalStorageAdapter,ss as createMarkdownProcessor,Vr as createMarkdownProcessorFromConfig,sd as createMessageActions,va as createNPSFeedback,qs as createPlainTextParser,Rm as createPlugin,Us as createRegexJsonParser,Fo as createStandardBubble,us as createTextPart,Po as createTheme,ta as createThemeObserver,Es as createToggleGroup,Qr as createTypingIndicator,Kr as createVoiceProvider,Rs as createWidgetHostLayout,Js as createXmlParser,By as default,ro as defaultActionHandlers,Ls as defaultJsonActionParser,Nd as defaultParseRules,bs as detectColorScheme,dp as directivePostprocessor,wo as escapeHtml,ba as extractComponentDirectiveFromMessage,Mp as fileToImagePart,dm as formatEnrichedContext,Yr as generateAssistantMessageId,hm as generateCodeSnippet,Cp as generateMessageId,Od as generateStableSelector,To as generateUserMessageId,xs as getActiveTheme,Uc as getColorScheme,Sp as getDisplayText,ed as getHeaderLayout,Ep as getImageParts,Bm as getPreset,ya as hasComponentDirective,Ap as hasImages,sa as headerLayouts,Wm as highContrastPlugin,kd as initAgentWidget,Iu as isComponentDirectiveType,Kt as isDockedMountMode,hs as isVoiceSupported,Sc as markdownPostprocessor,Zs as mergeWithDefaults,wp as normalizeContent,ks as pluginRegistry,Pm as reducedMotionPlugin,ha as renderComponentDirective,od as renderLoadingIndicatorWithFallback,_n as resolveDockConfig,So as resolveSanitizer,Qs as resolveTokens,ea as themeToCssVariables,kp as validateImageFile,jc as validateTheme};
|
|
435
|
+
`;function Em(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Am,document.head.appendChild(e)}function Tm(e,r){let t=e.clientWidth-Va*2-Qd,n=e.clientHeight-Va*2-Qd;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Mm(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function km(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Em();let p=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,g=null,x=1,M=!1,w=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),$=h("div","persona-dc-toolbar-trail"),v=Nt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Le(-1)}),T=h("div");T.style.position="relative";let B=h("button","persona-dc-title-btn");B.type="button",B.setAttribute("aria-expanded","false"),B.setAttribute("aria-haspopup","listbox");let E=h("span","persona-dc-title-text"),K=h("span","persona-dc-title-chevron"),Q=fe("chevron-down",12,"currentColor",2);Q&&K.appendChild(Q),B.append(E,K);let G=h("div","persona-dc-dropdown");G.setAttribute("role","listbox"),G.style.display="none";let j=!1;function re(){G.innerHTML="";for(let F=0;F<t.length;F++){let U=t[F],me=h("button","persona-dc-dropdown-item");me.type="button",me.setAttribute("role","option"),me.setAttribute("aria-current",F===p?"true":"false");let Je=h("span");if(Je.textContent=U.title,me.appendChild(Je),U.description){let ee=h("span","persona-dc-dropdown-desc");ee.textContent=U.description,me.appendChild(ee)}me.addEventListener("click",()=>{oe(),Ie(F)}),G.appendChild(me)}}function Te(){j=!j,G.style.display=j?"":"none",B.setAttribute("aria-expanded",j?"true":"false"),j&&re()}function oe(){j&&(j=!1,G.style.display="none",B.setAttribute("aria-expanded","false"))}B.addEventListener("click",F=>{F.stopPropagation(),Te()});let Ce=()=>oe();document.addEventListener("click",Ce),T.append(B,G);let Ne=Nt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Le(1)}),he=h("span","persona-dc-counter");k.append(v,T,Ne,he);let ke=null;i&&(ke=Fs({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:F=>{d=F,de.dataset.device=d,g=null,P()}}),$.appendChild(ke.element));let Be=null;if(a){let F=h("div","persona-dc-zoom-controls"),U=Nt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ee=g!=null?g:x;g=Math.max(Xd,ee-Yd),P()}});Be=h("span","persona-dc-zoom-level"),Be.title="Reset to 100%",Be.style.cursor="pointer",Be.addEventListener("click",()=>{g=1,P()});let me=Nt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ee=g!=null?g:x;g=Math.min(Zd,ee+Yd),P()}}),Je=Nt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,P()}});F.append(U,Be,me,Je),$.appendChild(F)}if(u){let F=h("div","persona-dc-separator");$.appendChild(F);let U=Fs({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:me=>{f=me,de.dataset.colorScheme=f,Me()}});$.appendChild(U.element)}let ue=h("div","persona-dc-separator");$.appendChild(ue);let Y=Nt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});$.appendChild(Y),S.append(k,$);let ye=h("div","persona-dc-stage"),de=h("div","persona-dc-iframe-wrapper");de.dataset.device=d,de.dataset.colorScheme=f;let we=h("iframe","persona-dc-iframe");we.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),we.setAttribute("loading","lazy"),we.title=t[p].title,de.appendChild(we),ye.appendChild(de),w.append(S,ye),e.appendChild(w);function Me(){var F;try{let U=(F=we.contentDocument)==null?void 0:F.body;if(!U)return;f==="dark"?U.classList.add("theme-dark"):U.classList.remove("theme-dark")}catch{}}we.addEventListener("load",()=>Me());function ae(){let F=t[p];E.textContent=F.title,he.textContent=`${p+1} / ${t.length}`,we.title=F.title}function Le(F){let U=((p+F)%t.length+t.length)%t.length;Ie(U)}function Ie(F){F<0||F>=t.length||(p=F,we.src=t[p].url,ae(),c==null||c(p,t[p]))}function P(){var me;if(M)return;let F=(me=Kd[d])!=null?me:Kd.desktop;x=Tm(ye,F);let U=Math.max(Xd,Math.min(Zd,g!=null?g:x));Mm(de,we,F,U,d),Be&&(Be.textContent=`${Math.round(U*100)}%`)}let q=new ResizeObserver(()=>P());q.observe(ye),ae(),we.src=t[p].url,requestAnimationFrame(()=>P());function ie(){M||(M=!0,q.disconnect(),document.removeEventListener("click",Ce),w.remove())}return{element:w,goTo:Ie,next:()=>Le(1),prev:()=>Le(-1),getIndex:()=>p,setDevice(F){d=F,de.dataset.device=F,ke==null||ke.setSelected(F),g=null,P()},setColorScheme(F){f=F,de.dataset.colorScheme=F},setZoom(F){g=F,P()},destroy:ie}}function Lm(){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 Im(){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 Pm(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:Yn(e.colors.primary,.95),100:Yn(e.colors.primary,.9),200:Yn(e.colors.primary,.8),300:Yn(e.colors.primary,.7),400:Yn(e.colors.primary,.6),500:e.colors.primary,600:Yn(e.colors.primary,.8),700:Yn(e.colors.primary,.7),800:Yn(e.colors.primary,.6),900:Yn(e.colors.primary,.5),950:Yn(e.colors.primary,.45)}}),{...r,palette:t}}}}function Wm(){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 Rm(){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 Yn(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Hm(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Bm={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"}}},ep={components:{panel:{borderRadius:"0",shadow:"none"}}},tp={id:"shop",label:"Shopping Assistant",config:{theme:Bm,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Pn},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?"]}},np={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:ep}},rp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:ep}},op={shop:tp,minimal:np,fullscreen:rp};function Dm(e){return op[e]}var By=Ld;export{eo as AgentWidgetClient,$o as AgentWidgetSession,ro as AttachmentManager,jc as DEFAULT_COMPONENTS,pa as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Pn as DEFAULT_FLOATING_LAUNCHER_WIDTH,$c as DEFAULT_PALETTE,_c as DEFAULT_SEMANTIC,It as DEFAULT_WIDGET_CONFIG,op as PRESETS,rp as PRESET_FULLSCREEN,np as PRESET_MINIMAL,tp as PRESET_SHOP,Fp as THEME_ZONES,uo as VERSION,Lm as accessibilityPlugin,Im as animationsPlugin,jr as applyThemeVariables,oo as attachHeaderToContainer,Pm as brandPlugin,Ko as buildComposer,Qc as buildDefaultHeader,Sr as buildHeader,Go as buildHeaderWithLayout,ed as buildMinimalHeader,dm as collectEnrichedPageContext,Ar as componentRegistry,zs as createActionManager,Da as createAgentExperience,da as createBestAvailableVoiceProvider,Qp as createBubbleWithLayout,Ra as createCSATFeedback,ba as createComboButton,Wu as createComponentMiddleware,La as createComponentStreamParser,Mc as createDefaultSanitizer,km as createDemoCarousel,dp as createDirectivePostprocessor,zr as createDropdownMenu,bp as createFlexibleJsonStreamParser,Nt as createIconButton,Mp as createImagePart,aa as createJsonStreamParser,Ns as createLabelButton,ka as createLocalStorageAdapter,bs as createMarkdownProcessor,Zr as createMarkdownProcessorFromConfig,ad as createMessageActions,Ha as createNPSFeedback,oa as createPlainTextParser,Hm as createPlugin,sa as createRegexJsonParser,Yo as createStandardBubble,Es as createTextPart,zo as createTheme,fa as createThemeObserver,Fs as createToggleGroup,so as createTypingIndicator,no as createVoiceProvider,Vs as createWidgetHostLayout,ia as createXmlParser,By as default,co as defaultActionHandlers,js as defaultJsonActionParser,Fd as defaultParseRules,Ps as detectColorScheme,pp as directivePostprocessor,Ho as escapeHtml,Wa as extractComponentDirectiveFromMessage,kp as fileToImagePart,pm as formatEnrichedContext,to as generateAssistantMessageId,ym as generateCodeSnippet,wp as generateMessageId,$d as generateStableSelector,Fo as generateUserMessageId,Ws as getActiveTheme,Vc as getColorScheme,Ap as getDisplayText,td as getHeaderLayout,Tp as getImageParts,Dm as getPreset,Pa as hasComponentDirective,Ep as hasImages,xa as headerLayouts,Rm as highContrastPlugin,Ld as initAgentWidget,Pu as isComponentDirectiveType,Yt as isDockedMountMode,Ls as isVoiceSupported,Ac as markdownPostprocessor,ua as mergeWithDefaults,Sp as normalizeContent,_s as pluginRegistry,Wm as reducedMotionPlugin,Ia as renderComponentDirective,sd as renderLoadingIndicatorWithFallback,jn as resolveDockConfig,Bo as resolveSanitizer,ma as resolveTokens,ga as themeToCssVariables,Lp as validateImageFile,zc as validateTheme};
|
|
436
436
|
//# sourceMappingURL=index.js.map
|