@runtypelabs/persona 3.19.0 → 3.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -1
- package/dist/index.cjs +27 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +103 -3
- package/dist/index.d.ts +103 -3
- package/dist/index.global.js +65 -65
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +27 -27
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +80 -11
- package/dist/theme-editor.d.cts +73 -0
- package/dist/theme-editor.d.ts +73 -0
- package/dist/theme-editor.js +80 -11
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/session.test.ts +123 -0
- package/src/session.ts +58 -4
- package/src/types.ts +75 -0
- package/src/ui.ts +18 -0
- package/src/utils/component-middleware.test.ts +134 -0
- package/src/utils/component-middleware.ts +44 -13
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{Marked as
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Oo=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)}},
|
|
1
|
+
import{Marked as Gu}from"marked";var Qu=e=>{if(e)return e},ca=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new Gu({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=Qu(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},No=e=>e?ca({markedOptions:e.options,renderer:e.renderer}):ca(),Xu=ca(),Qd=e=>Xu(e),Fo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Xd=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Gd=e=>`%%FORM_PLACEHOLDER_${e}%%`,Yd=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Gd(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Gd(n.length);return n.push({token:o,type:s}),o}),t},Yu=e=>{let n=No(e);return t=>{let r=[],s=Yd(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Xd(i)}"></div>`;o=o.replace(d,u)}),o}},Zu=e=>{let n=[],t=Yd(e,n),r=Qd(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Xd(o)}"></div>`;r=r.replace(a,d)}),r};import em from"dompurify";var tm={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"]},nm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Zd=()=>{let e=em(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!nm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,tm)},bs=e=>e===!1?null:typeof e=="function"?e:Zd();import{parse as ep,STR as tp,OBJ as np}from"partial-json";var da=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Oo=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)}},rm=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},rp=e=>e.status==="complete"?rm(e):e.status==="pending"?"Waiting":"",om=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 op=e=>e.status==="complete"?om(e):"Using tool...",pa=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},vs=e=>{var t,r,s;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return pa(n)},ua=e=>{var t,r,s;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return pa(n)},ai=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=vs(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},ma=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&xs(r,t.slice(o,a.index),[]),a[1]!==void 0?xs(r,a[1],["bold"]):a[2]!==void 0?xs(r,a[2],["italic"]):a[3]!==void 0&&xs(r,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&xs(r,t.slice(o),[]),r},xs=(e,n,t)=>{let r=n.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:t}),s<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},sm=()=>{let e=null,n=0,t=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Co=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},ii=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},li=()=>{var n;let e=om();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},ci=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=ep(t,tp|np);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?da(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=da(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},sm=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?da(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?da(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=ep(o,tp|np),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},di=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var ga=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var am="https://api.runtype.com/v1/dispatch",fa="https://api.runtype.com",pi=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 im(e){switch(e){case"json":return ci;case"regex-json":return li;case"xml":return di;default:return ii}}var sp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function lm(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=sp(t);if(!sp(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=Co(e);return Co(n)!==null&&a===null?n:e}var $o=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s;this.apiUrl=(t=n.apiUrl)!=null?t:am,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:im(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa}/v1/client/feedback`}async sendFeedback(n){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.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 l=await this.buildPayload(n.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(pi).map(g=>{var v,x,k;return{id:g.id,role:g.role,content:(k=(x=(v=g.contentParts)!=null?v:g.llmContent)!=null?x:g.rawContent)!=null?k:g.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.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 x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}if(f.status===429){let x=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:x}),x}let v=new Error(g.error||"Failed to send message");throw t({type:"error",error:v}),v}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,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var i,d;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,""))||fa}/resume`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(o,{method:"POST",headers:a,body:JSON.stringify({executionId:n,toolOutputs:t,streamResponse:(d=r==null?void 0:r.streamResponse)!=null?d:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(pi).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}}),r={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:n,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&&(r.context=s)}return r}async buildPayload(n){let r={messages:n.slice().filter(pi).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:n,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&&(r.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...r},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return r.current=p,s(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var Pt,qt,vr,dr;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=P=>{let oe=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,Pe=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,qe=P.tools?P.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...P,reasoning:oe,toolCall:Pe,tools:qe}},p=P=>{t({type:"message",message:u(P)})},f=null,g={current:null},v={current:null},x=!1,k=new Map,C=new Map,L=new Map,D=new Map,W={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},M=(P,oe,Pe="")=>`${P}::${oe}::${Pe}`,O=(P,oe)=>`${P}::${oe}::`,j=(P,oe,Pe,qe)=>{let Fe=M(P,oe,Pe),Oe=L.get(Fe);if(Oe)return Oe;let Ze=Pe?`-${Pe}`:"",vt={id:`nested-${P}-${oe}${Ze}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Pe?{partId:Pe}:{},agentMetadata:{executionId:qe,parentToolId:P,parentStepId:oe}};return L.set(Fe,vt),p(vt),vt},$=P=>{if(P==null)return null;try{return String(P)}catch{return null}},H=P=>{var oe,Pe,qe,Fe,Oe;return $((Oe=(Fe=(qe=(Pe=(oe=P.stepId)!=null?oe:P.step_id)!=null?Pe:P.step)!=null?qe:P.parentId)!=null?Fe:P.flowStepId)!=null?Oe:P.flow_step_id)},F=P=>{var oe,Pe,qe,Fe,Oe,Ze,vt;return $((vt=(Ze=(Oe=(Fe=(qe=(Pe=(oe=P.callId)!=null?oe:P.call_id)!=null?Pe:P.requestId)!=null?qe:P.request_id)!=null?Fe:P.toolCallId)!=null?Oe:P.tool_call_id)!=null?Ze:P.stepId)!=null?vt:P.step_id)},K=r,ne=!1,Se=()=>{if(f)return f;let P;return!ne&&K?(P=K,ne=!0):K&&v.current?P=`${K}_${v.current}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},We=(P,oe)=>{W.lastId=oe,P&&W.byStep.set(P,oe)},_e=(P,oe)=>{var Oe;let Pe=(Oe=P.reasoningId)!=null?Oe:P.id,qe=H(P);if(Pe){let Ze=String(Pe);return We(qe,Ze),Ze}if(qe){let Ze=W.byStep.get(qe);if(Ze)return W.lastId=Ze,Ze}if(W.lastId&&!oe)return W.lastId;if(!oe)return null;let Fe=`reason-${l()}`;return We(qe,Fe),Fe},fe=P=>{let oe=k.get(P);if(oe)return oe;let Pe={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:P,status:"streaming",chunks:[]}};return k.set(P,Pe),p(Pe),Pe},pe=(P,oe)=>{E.lastId=oe,P&&E.byCall.set(P,oe)},Te=new Set,Ue=new Map,ee=new Set,xe=new Map,Q=P=>{if(!P)return!1;let oe=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return oe==="emit_artifact_markdown"||oe==="emit_artifact_component"},re=(P,oe)=>{var Oe;let Pe=(Oe=P.toolId)!=null?Oe:P.id,qe=F(P);if(Pe){let Ze=String(Pe);return pe(qe,Ze),Ze}if(qe){let Ze=E.byCall.get(qe);if(Ze)return E.lastId=Ze,Ze}if(E.lastId&&!oe)return E.lastId;if(!oe)return null;let Fe=`tool-${l()}`;return pe(qe,Fe),Fe},Me=P=>{let oe=C.get(P);if(oe)return oe;let Pe={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:P,status:"pending"}};return C.set(P,Pe),p(Pe),Pe},ae=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let oe=Number(P);if(!Number.isNaN(oe)&&Number.isFinite(oe))return oe;let Pe=Date.parse(P);if(!Number.isNaN(Pe))return Pe}return Date.now()},Be=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},Re=new Map,J=new Map,De=new Map,He=new Map,G=null,V=(P,oe,Pe)=>{var vt;let qe=De.get(P);qe||(qe=[],De.set(P,qe));let Fe=0,Oe=qe.length;for(;Fe<Oe;){let Ot=Fe+Oe>>>1;qe[Ot].seq<oe?Fe=Ot+1:Oe=Ot}((vt=qe[Fe])==null?void 0:vt.seq)===oe?qe[Fe]={seq:oe,text:Pe}:qe.splice(Fe,0,{seq:oe,text:Pe});let Ze="";for(let Ot=0;Ot<qe.length;Ot++)Ze+=qe[Ot].text;return Ze},ve=(P,oe)=>{let Pe=Be(oe),qe=J.get(P.id),Fe=lm(qe,Pe);P.rawContent=Fe;let Oe=Re.get(P.id),Ze=se=>{var pt;let we=(pt=P.content)!=null?pt:"";se.trim()!==""&&(we.trim().length===0||se.startsWith(we)||se.trimStart().startsWith(we.trim()))&&(P.content=se)},vt=()=>{var se;if(Oe){let we=(se=Oe.close)==null?void 0:se.call(Oe);we instanceof Promise&&we.catch(()=>{})}Re.delete(P.id),J.delete(P.id),P.streaming=!1,p(P)};if(!Oe){Ze(Pe),vt();return}let Ot=Co(Fe);if(Ot!==null&&Ot.trim()!==""){Ze(Ot),vt();return}let zt=se=>{var Je;let we=typeof se=="string"?se:(Je=se==null?void 0:se.text)!=null?Je:null;if(we!==null&&we.trim()!=="")return we;let pt=Oe.getExtractedText();return pt!==null&&pt.trim()!==""?pt:Pe},R;try{R=Oe.processChunk(Fe)}catch{Ze(Pe),vt();return}if(R instanceof Promise){R.then(se=>{Ze(zt(se)),vt()}).catch(()=>{Ze(Pe),vt()});return}Ze(zt(R)),vt()},ce=[],te=!1,me,Qe=()=>{te||(te=!0,queueMicrotask(()=>{te=!1,me()}))},Ft=new ga((P,oe)=>{ce.push({payloadType:P,payload:oe}),Qe()}),ie=null,Ne=new Map,an=(Pt=this.config.iterationDisplay)!=null?Pt:"separate";for(me=()=>{var P,oe,Pe,qe,Fe,Oe,Ze,vt,Ot,zt,R,se,we,pt,Je,Nt,ln,wt,ht,St,it,Vt,wr,Un,Dr,xt,pr,ur,Cr,Yn,ct,io,mr,lo,En,Mo,Nr,Ar,mt,In,Wn,yn,Et,jn,qn,Rn,Fr,Sr,Or,Hn,kt,bn,zn,$r,Er,_r,gr,Bn,Zn,dt,Jt,Kt,Dn,Ur,Vn,er,Nn,_,de,Fn,tr,fr,ts,nr,rr,or,Tr,co,js,ns,qs,Lo,lt,rs,Jn,Tn,zs,Vs,Po,kr,Js,po,os,Mr,ss,jr,qr,Ks,Gs,si,uo,zr,Qs,as,Vr,Xs,is,Jr,ls,Ys,Lr,Zs,Kr,It,Io,Wo,cs,hr,ea,ds,ps,us,ms,xn,On,Pr,et,gs,mo,sr,ta,Ro,Ho,go,Gr,na,ra,ar;for(let Ir=0;Ir<ce.length;Ir++){let Ve=ce[Ir].payloadType,w=ce[Ir].payload;if(Ve==="reason_start"){let U=(P=_e(w,!0))!=null?P:`reason-${l()}`,A=fe(U);A.reasoning=(oe=A.reasoning)!=null?oe:{id:U,status:"streaming",chunks:[]},A.reasoning.startedAt=(qe=A.reasoning.startedAt)!=null?qe:ae((Pe=w.startedAt)!=null?Pe:w.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",p(A)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let U=(Oe=(Fe=_e(w,!1))!=null?Fe:_e(w,!0))!=null?Oe:`reason-${l()}`,A=fe(U);A.reasoning=(Ze=A.reasoning)!=null?Ze:{id:U,status:"streaming",chunks:[]},A.reasoning.startedAt=(Ot=A.reasoning.startedAt)!=null?Ot:ae((vt=w.startedAt)!=null?vt:w.timestamp);let q=(se=(R=(zt=w.reasoningText)!=null?zt:w.text)!=null?R:w.delta)!=null?se:"";if(q&&w.hidden!==!0){let ke=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(ke!==void 0){let Z=V(U,ke,String(q));A.reasoning.chunks=[Z]}else A.reasoning.chunks.push(String(q))}if(A.reasoning.status=w.done?"complete":"streaming",w.done){A.reasoning.completedAt=ae((we=w.completedAt)!=null?we:w.timestamp);let ke=(pt=A.reasoning.startedAt)!=null?pt:Date.now();A.reasoning.durationMs=Math.max(0,((Je=A.reasoning.completedAt)!=null?Je:Date.now())-ke)}A.streaming=A.reasoning.status!=="complete",p(A)}else if(Ve==="reason_complete"){let U=(ln=(Nt=_e(w,!1))!=null?Nt:_e(w,!0))!=null?ln:`reason-${l()}`,A=k.get(U);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=ae((wt=w.completedAt)!=null?wt:w.timestamp);let ke=(ht=A.reasoning.startedAt)!=null?ht:Date.now();A.reasoning.durationMs=Math.max(0,((St=A.reasoning.completedAt)!=null?St:Date.now())-ke),A.streaming=!1,p(A)}let q=H(w);q&&W.byStep.delete(q)}else if(Ve==="tool_start"){let U=(it=re(w,!0))!=null?it:`tool-${l()}`,A=(Vt=w.toolName)!=null?Vt:w.name;if(Q(A)){Te.add(U);continue}let q=Me(U),ke=(wr=q.toolCall)!=null?wr:{id:U,status:"pending"};ke.name=A!=null?A:ke.name,ke.status="running",w.args!==void 0?ke.args=w.args:w.parameters!==void 0&&(ke.args=w.parameters),ke.startedAt=(Dr=ke.startedAt)!=null?Dr:ae((Un=w.startedAt)!=null?Un:w.timestamp),ke.completedAt=void 0,ke.durationMs=void 0,q.toolCall=ke,q.streaming=!0;let Z=w.agentContext;(Z||w.executionId)&&(q.agentMetadata={executionId:(xt=Z==null?void 0:Z.executionId)!=null?xt:w.executionId,iteration:(pr=Z==null?void 0:Z.iteration)!=null?pr:w.iteration}),p(q)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let U=(Cr=(ur=re(w,!1))!=null?ur:re(w,!0))!=null?Cr:`tool-${l()}`;if(Te.has(U))continue;let A=Me(U),q=(Yn=A.toolCall)!=null?Yn:{id:U,status:"running"};q.startedAt=(io=q.startedAt)!=null?io:ae((ct=w.startedAt)!=null?ct:w.timestamp);let ke=(En=(lo=(mr=w.text)!=null?mr:w.delta)!=null?lo:w.message)!=null?En:"";ke&&(q.chunks=(Mo=q.chunks)!=null?Mo:[],q.chunks.push(String(ke))),q.status="running",A.toolCall=q,A.streaming=!0;let Z=w.agentContext;(Z||w.executionId)&&(A.agentMetadata=(mt=A.agentMetadata)!=null?mt:{executionId:(Nr=Z==null?void 0:Z.executionId)!=null?Nr:w.executionId,iteration:(Ar=Z==null?void 0:Z.iteration)!=null?Ar:w.iteration}),p(A)}else if(Ve==="tool_complete"){let U=(Wn=(In=re(w,!1))!=null?In:re(w,!0))!=null?Wn:`tool-${l()}`;if(Te.has(U)){Te.delete(U);continue}let A=Me(U),q=(yn=A.toolCall)!=null?yn:{id:U,status:"running"};q.status="complete",w.result!==void 0&&(q.result=w.result),typeof w.duration=="number"&&(q.duration=w.duration),q.completedAt=ae((Et=w.completedAt)!=null?Et:w.timestamp);let ke=(jn=w.duration)!=null?jn:w.executionTime;if(typeof ke=="number")q.durationMs=ke;else{let Ke=(qn=q.startedAt)!=null?qn:Date.now();q.durationMs=Math.max(0,((Rn=q.completedAt)!=null?Rn:Date.now())-Ke)}A.toolCall=q,A.streaming=!1;let Z=w.agentContext;(Z||w.executionId)&&(A.agentMetadata=(Or=A.agentMetadata)!=null?Or:{executionId:(Fr=Z==null?void 0:Z.executionId)!=null?Fr:w.executionId,iteration:(Sr=Z==null?void 0:Z.iteration)!=null?Sr:w.iteration}),p(A);let Xe=F(w);Xe&&E.byCall.delete(Xe)}else if(Ve==="step_await"&&w.awaitReason==="local_tool_required"&&w.toolName){let U=(Hn=w.toolId)!=null?Hn:`local-${l()}`,A=Me(U),q=(kt=A.toolCall)!=null?kt:{id:U,status:"pending"};q.name=w.toolName,q.args=w.parameters,q.status="complete",q.chunks=(bn=q.chunks)!=null?bn:[],q.startedAt=($r=q.startedAt)!=null?$r:ae((zn=w.startedAt)!=null?zn:w.timestamp),q.completedAt=(Er=q.completedAt)!=null?Er:q.startedAt,A.toolCall=q,A.streaming=!1,A.agentMetadata={...A.agentMetadata,executionId:(gr=w.executionId)!=null?gr:(_r=A.agentMetadata)==null?void 0:_r.executionId,awaitingLocalTool:!0},p(A)}else if(Ve==="text_start"){if((Bn=w.toolContext)!=null&&Bn.toolId)continue;let U=w.partId;if(U!==void 0&&v.current!==null&&U!==v.current){let A=f;A&&(A.streaming=!1,p(A),G=A,f=null,x=!0)}U!==void 0&&(v.current=U)}else if(Ve==="text_end"){if((Zn=w.toolContext)!=null&&Zn.toolId)continue;let U=f;U&&(U.streaming=!1,p(U),G=U,f=null,x=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let U=w.stepType,A=w.executionType;if(U==="tool"||A==="context")continue;let q=w.toolContext;if(q!=null&&q.toolId){let Ke=String((Jt=(dt=w.id)!=null?dt:q.stepId)!=null?Jt:`step-${l()}`),Mt=w.partId!==void 0&&w.partId!==null?String(w.partId):"",gt=`${q.toolId}::${Ke}`,Lt=D.get(gt);if(Mt!==""&&Lt!==void 0&&Lt!==""&&Lt!==Mt){let yt=L.get(M(q.toolId,Ke,Lt));yt&&yt.streaming!==!1&&(yt.streaming=!1,p(yt))}Mt!==""&&D.set(gt,Mt);let Ht=j(q.toolId,Ke,Mt,q.executionId),Gt=(Vn=(Ur=(Dn=(Kt=w.text)!=null?Kt:w.delta)!=null?Dn:w.content)!=null?Ur:w.chunk)!=null?Vn:"";Gt&&(Ht.content+=String(Gt),Ht.streaming=!0,p(Ht)),w.isComplete&&(Ht.streaming=!1,p(Ht));continue}let ke=w.partId;if(ke!==void 0&&v.current!==null&&ke!==v.current){let Ke=f;Ke&&(Ke.streaming=!1,p(Ke),G=Ke,f=null,x=!0)}ke!==void 0&&(v.current=ke);let Z=ke!==void 0&&(er=He.get(ke))!=null?er:Se();ke!==void 0&&(Z.partId||(Z.partId=ke),He.set(ke,Z));let Xe=(Fn=(de=(_=(Nn=w.text)!=null?Nn:w.delta)!=null?_:w.content)!=null?de:w.chunk)!=null?Fn:"";if(Xe){let Ke=typeof w.seq=="number"?w.seq:void 0,Mt=ke!=null?ke:Z.id,gt=Ke!==void 0?V(Mt,Ke,String(Xe)):((tr=J.get(Z.id))!=null?tr:"")+Xe;Z.rawContent=gt,Re.has(Z.id)||Re.set(Z.id,this.createStreamParser());let Lt=Re.get(Z.id),Ht=gt.trim().startsWith("{")||gt.trim().startsWith("[");if(Ht&&J.set(Z.id,gt),Lt.__isPlainTextParser===!0){Z.content=Ke!==void 0?gt:Z.content+Xe,J.delete(Z.id),Re.delete(Z.id),Z.rawContent=void 0,p(Z);continue}let yt=Lt.processChunk(gt);if(yt instanceof Promise)yt.then(ft=>{var un;let tn=typeof ft=="string"?ft:(un=ft==null?void 0:ft.text)!=null?un:null;if(tn!==null&&tn.trim()!=="")Z.content=tn,p(Z);else if(!Ht&&!gt.trim().startsWith("<")){let cn=f,Qt=cn&&cn.id===Z.id?cn:Z;Qt.id===Z.id&&(Qt.content=Ke!==void 0?gt:Qt.content+Xe,J.delete(Qt.id),Re.delete(Qt.id),Qt.rawContent=void 0,p(Qt))}}).catch(()=>{Z.content=Ke!==void 0?gt:Z.content+Xe,J.delete(Z.id),Re.delete(Z.id),Z.rawContent=void 0,p(Z)});else{let ft=typeof yt=="string"?yt:(fr=yt==null?void 0:yt.text)!=null?fr:null;ft!==null&&ft.trim()!==""?(Z.content=ft,p(Z)):!Ht&&!gt.trim().startsWith("<")&&(Z.content=Ke!==void 0?gt:Z.content+Xe,J.delete(Z.id),Re.delete(Z.id),Z.rawContent=void 0,p(Z))}}if(w.isComplete){let Ke=(nr=(ts=w.result)==null?void 0:ts.response)!=null?nr:Z.content;if(Ke){let Mt=J.get(Z.id),gt=Mt!=null?Mt:Be(Ke);Z.rawContent=gt;let Lt=Re.get(Z.id),Ht=null,Gt=!1;if(Lt&&(Ht=Lt.getExtractedText(),Ht===null&&(Ht=Co(gt)),Ht===null)){let yt=Lt.processChunk(gt);yt instanceof Promise?(Gt=!0,yt.then(ft=>{var un;let tn=typeof ft=="string"?ft:(un=ft==null?void 0:ft.text)!=null?un:null;if(tn!==null){let cn=f;cn&&cn.id===Z.id&&(cn.content=tn,cn.streaming=!1,Re.delete(cn.id),J.delete(cn.id),p(cn))}})):Ht=typeof yt=="string"?yt:(rr=yt==null?void 0:yt.text)!=null?rr:null}if(!Gt){Ht!==null&&Ht.trim()!==""?Z.content=Ht:J.has(Z.id)||(Z.content=Be(Ke));let yt=Re.get(Z.id);if(yt){let ft=(or=yt.close)==null?void 0:or.call(yt);ft instanceof Promise&&ft.catch(()=>{}),Re.delete(Z.id)}J.delete(Z.id),Z.streaming=!1,p(Z)}}}}else if(Ve==="step_complete"){let U=w.stepType,A=w.executionType;if(U==="tool"||A==="context")continue;let q=w.toolContext;if(q!=null&&q.toolId){let Ke=String((co=(Tr=w.id)!=null?Tr:q.stepId)!=null?co:"");if(Ke){let Mt=O(q.toolId,Ke);for(let[gt,Lt]of L)gt.startsWith(Mt)&&Lt.streaming!==!1&&(Lt.streaming=!1,p(Lt));D.delete(`${q.toolId}::${Ke}`)}continue}let ke=w.stopReason;if(x){if(f!==null){let gt=f;ke&&(gt.stopReason=ke),Re.delete(gt.id),J.delete(gt.id),gt.streaming!==!1&&(gt.streaming=!1,p(gt))}let Ke=(js=w.result)==null?void 0:js.response,Mt=G;Mt&&(ke&&(Mt.stopReason=ke),Ke!=null?ve(Mt,Ke):(Re.delete(Mt.id),J.delete(Mt.id))),G=null;continue}let Z=(ns=w.result)==null?void 0:ns.response,Xe=Se();if(ke&&(Xe.stopReason=ke),Z!=null){let Ke=Re.get(Xe.id),Mt=!1,gt=!1;if(Ke){let Lt=Ke.getExtractedText(),Ht=J.get(Xe.id),Gt=Ht!=null?Ht:Be(Z);if(Xe.rawContent=Gt,Lt!==null&&Lt.trim()!=="")Xe.content=Lt,Mt=!0;else{let yt=Co(Gt);if(yt!==null)Xe.content=yt,Mt=!0;else{let ft=Ke.processChunk(Gt);if(ft instanceof Promise)gt=!0,ft.then(tn=>{var cn;let un=typeof tn=="string"?tn:(cn=tn==null?void 0:tn.text)!=null?cn:null;if(un!==null&&un.trim()!==""){let Qt=f;Qt&&Qt.id===Xe.id&&(Qt.content=un,Qt.streaming=!1,Re.delete(Qt.id),J.delete(Qt.id),p(Qt))}else{let Qt=Ke.getExtractedText(),sn=f;sn&&sn.id===Xe.id&&(Qt!==null&&Qt.trim()!==""?sn.content=Qt:J.has(sn.id)||(sn.content=Be(Z)),sn.streaming=!1,Re.delete(sn.id),J.delete(sn.id),p(sn))}});else{let tn=typeof ft=="string"?ft:(qs=ft==null?void 0:ft.text)!=null?qs:null;if(tn!==null&&tn.trim()!=="")Xe.content=tn,Mt=!0;else{let un=Ke.getExtractedText();un!==null&&un.trim()!==""&&(Xe.content=un,Mt=!0)}}}}}if(!gt){if(!Xe.rawContent){let Lt=J.get(Xe.id);Xe.rawContent=Lt!=null?Lt:Be(Z)}if(!Mt&&!J.has(Xe.id)&&(Xe.content=Be(Z)),Ke){let Lt=(Lo=Ke.close)==null?void 0:Lo.call(Ke);Lt instanceof Promise&&Lt.catch(()=>{})}Re.delete(Xe.id),J.delete(Xe.id),Xe.streaming=!1,p(Xe)}}else Re.delete(Xe.id),J.delete(Xe.id),Xe.streaming=!1,p(Xe)}else if(Ve==="flow_complete"){let U=(lt=w.result)==null?void 0:lt.response;if(x){if(f!==null){let A=f;Re.delete(A.id),J.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}}else if(U!=null){let A=Se(),q=J.get(A.id),ke=q!=null?q:Be(U);A.rawContent=ke;let Z=Be(U),Xe=Re.get(A.id);if(Xe){let gt=Co(ke);if(gt!==null)Z=gt;else{let Lt=Xe.processChunk(ke);Lt instanceof Promise&&Lt.then(Gt=>{var ft;let yt=typeof Gt=="string"?Gt:(ft=Gt==null?void 0:Gt.text)!=null?ft:null;yt!==null&&(A.content=yt,A.streaming=!1,p(A))});let Ht=Xe.getExtractedText();Ht!==null&&(Z=Ht)}}Re.delete(A.id),J.delete(A.id);let Ke=Z!==A.content,Mt=A.streaming!==!1;Ke&&(A.content=Z),A.streaming=!1,(Ke||Mt)&&p(A)}else if(f!==null){let A=f;Re.delete(A.id),J.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}t({type:"status",status:"idle"})}else if(Ve==="agent_start")ie={executionId:w.executionId,agentId:(rs=w.agentId)!=null?rs:"virtual",agentName:(Jn=w.agentName)!=null?Jn:"",status:"running",currentIteration:0,maxTurns:(Tn=w.maxTurns)!=null?Tn:1,startedAt:ae(w.startedAt)};else if(Ve==="agent_iteration_start"){if(ie&&(ie.currentIteration=w.iteration),an==="separate"&&w.iteration>1){let U=f;U&&(U.streaming=!1,p(U),Ne.set(w.iteration-1,U),f=null)}}else if(Ve!=="agent_turn_start"){if(Ve==="agent_turn_delta"){if(w.contentType==="text"){let U=Se();U.content+=(zs=w.delta)!=null?zs:"",U.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId,agentName:ie==null?void 0:ie.agentName},p(U)}else if(w.contentType==="thinking"){let U=(Vs=w.turnId)!=null?Vs:`agent-think-${w.iteration}`,A=fe(U);A.reasoning=(Po=A.reasoning)!=null?Po:{id:U,status:"streaming",chunks:[]},A.reasoning.chunks.push((kr=w.delta)!=null?kr:""),A.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId},p(A)}else if(w.contentType==="tool_input"){let U=(Js=w.toolCallId)!=null?Js:E.lastId;if(U){let A=C.get(U);A!=null&&A.toolCall&&(A.toolCall.chunks=(po=A.toolCall.chunks)!=null?po:[],A.toolCall.chunks.push((os=w.delta)!=null?os:""),p(A))}}}else if(Ve==="agent_turn_complete"){let U=w.turnId;if(U){let q=k.get(U);if(q!=null&&q.reasoning){q.reasoning.status="complete",q.reasoning.completedAt=ae(w.completedAt);let ke=(Mr=q.reasoning.startedAt)!=null?Mr:Date.now();q.reasoning.durationMs=Math.max(0,((ss=q.reasoning.completedAt)!=null?ss:Date.now())-ke),q.streaming=!1,p(q)}}let A=w.stopReason;if(A&&f!==null){let q=w.turnId;(!q||((jr=f.agentMetadata)==null?void 0:jr.turnId)===q)&&(f.stopReason=A,p(f))}}else if(Ve==="agent_tool_start"){let U=(qr=w.toolCallId)!=null?qr:`agent-tool-${l()}`;pe(F(w),U);let A=Me(U),q=(Ks=A.toolCall)!=null?Ks:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};q.name=(si=(Gs=w.toolName)!=null?Gs:w.name)!=null?si:q.name,q.status="running",w.parameters!==void 0&&(q.args=w.parameters),q.startedAt=ae((uo=w.startedAt)!=null?uo:w.timestamp),A.toolCall=q,A.streaming=!0,A.agentMetadata={executionId:w.executionId,iteration:w.iteration},p(A)}else if(Ve==="agent_tool_delta"){let U=(zr=w.toolCallId)!=null?zr:E.lastId;if(U){let A=(Qs=C.get(U))!=null?Qs:Me(U);A.toolCall&&(A.toolCall.chunks=(as=A.toolCall.chunks)!=null?as:[],A.toolCall.chunks.push((Vr=w.delta)!=null?Vr:""),A.toolCall.status="running",A.streaming=!0,p(A))}}else if(Ve==="agent_tool_complete"){let U=(Xs=w.toolCallId)!=null?Xs:E.lastId;if(U){let A=(is=C.get(U))!=null?is:Me(U);if(A.toolCall){A.toolCall.status="complete",w.result!==void 0&&(A.toolCall.result=w.result),typeof w.executionTime=="number"&&(A.toolCall.durationMs=w.executionTime),A.toolCall.completedAt=ae((Jr=w.completedAt)!=null?Jr:w.timestamp),A.streaming=!1,p(A);let q=F(w);q&&E.byCall.delete(q)}}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let U=`agent-reflection-${w.executionId}-${w.iteration}`,A={id:U,role:"assistant",content:(ls=w.reflection)!=null?ls:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Ys=w.reflection)!=null?Ys:""]},agentMetadata:{executionId:w.executionId,iteration:w.iteration}};p(A)}else if(Ve==="agent_complete"){ie&&(ie.status=w.success?"complete":"error",ie.completedAt=ae(w.completedAt),ie.stopReason=w.stopReason);let U=f;U&&(U.streaming=!1,p(U)),t({type:"status",status:"idle"})}else if(Ve==="agent_error"){let U=typeof w.error=="string"?w.error:(Zs=(Lr=w.error)==null?void 0:Lr.message)!=null?Zs:"Agent execution error";w.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):t({type:"error",error:new Error(U)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let U=(Kr=w.approvalId)!=null?Kr:`approval-${l()}`,A={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(It=ie==null?void 0:ie.agentId)!=null?It:"virtual",executionId:(Wo=(Io=w.executionId)!=null?Io:ie==null?void 0:ie.executionId)!=null?Wo:"",toolName:(cs=w.toolName)!=null?cs:"",toolType:w.toolType,description:(ea=w.description)!=null?ea:`Execute ${(hr=w.toolName)!=null?hr:"tool"}`,parameters:w.parameters}};p(A)}else if(Ve==="step_await"&&w.awaitReason==="approval_required"){let U=(ds=w.approvalId)!=null?ds:`approval-${l()}`,A={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ps=ie==null?void 0:ie.agentId)!=null?ps:"virtual",executionId:(ms=(us=w.executionId)!=null?us:ie==null?void 0:ie.executionId)!=null?ms:"",toolName:(xn=w.toolName)!=null?xn:"",toolType:w.toolType,description:(Pr=w.description)!=null?Pr:`Execute ${(On=w.toolName)!=null?On:"tool"}`,parameters:w.parameters}};p(A)}else if(Ve==="agent_approval_complete"){let U=w.approvalId;if(U){let q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(et=w.decision)!=null?et:"approved",agentId:(gs=ie==null?void 0:ie.agentId)!=null?gs:"virtual",executionId:(sr=(mo=w.executionId)!=null?mo:ie==null?void 0:ie.executionId)!=null?sr:"",toolName:(ta=w.toolName)!=null?ta:"",description:(Ro=w.description)!=null?Ro:"",resolvedAt:Date.now()}};p(q)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let U=w.artifactType,A=String(w.id),q=typeof w.title=="string"?w.title:void 0;if(t({type:"artifact_start",id:A,artifactType:U,title:q,component:typeof w.component=="string"?w.component:void 0}),xe.set(A,{markdown:"",title:q}),!ee.has(A)){ee.add(A);let ke={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:q,artifactType:U,status:"streaming"}})};Ue.set(A,ke),p(ke)}}else if(Ve==="artifact_delta"){let U=String(w.id),A=typeof w.delta=="string"?w.delta:String((Ho=w.delta)!=null?Ho:"");t({type:"artifact_delta",id:U,artDelta:A});let q=xe.get(U);q&&(q.markdown+=A)}else if(Ve==="artifact_update"){let U=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};t({type:"artifact_update",id:String(w.id),props:U,component:typeof w.component=="string"?w.component:void 0})}else if(Ve==="artifact_complete"){let U=String(w.id);t({type:"artifact_complete",id:U});let A=Ue.get(U);if(A){A.streaming=!1;try{let q=JSON.parse((go=A.rawContent)!=null?go:"{}");if(q.props){q.props.status="complete";let ke=xe.get(U);ke!=null&&ke.markdown&&(q.props.markdown=ke.markdown)}A.rawContent=JSON.stringify(q)}catch{}xe.delete(U),p(A),Ue.delete(U)}}}else if(Ve==="transcript_insert"){let U=w.message;if(!U||typeof U!="object")continue;let A=String((Gr=U.id)!=null?Gr:`msg-${l()}`),q=U.role,Z={id:A,role:q==="user"?"user":q==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(p(Z),Z.rawContent)try{let Xe=JSON.parse(Z.rawContent),Ke=(na=Xe==null?void 0:Xe.props)==null?void 0:na.artifactId;typeof Ke=="string"&&ee.add(Ke)}catch{}f=null,g.current=null,Re.delete(A),J.delete(A)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let U=null;if(w.error instanceof Error)U=w.error;else if(Ve==="dispatch_error"){let A=(ra=w.message)!=null?ra:w.error;A!=null&&A!==""&&(U=new Error(String(A)))}else if(Ve==="step_error"||Ve==="flow_error"){let A=w.error;typeof A=="string"&&A!==""?U=new Error(A):A!=null&&typeof A=="object"&&"message"in A&&(U=new Error(String((ar=A.message)!=null?ar:A)))}else Ve==="error"&&w.error!=null&&w.error!==""&&(U=new Error(String(w.error)));if(U){t({type:"error",error:U});let A=f;A&&A.streaming&&(A.streaming=!1,p(A)),t({type:"status",status:"idle"})}}}}}}ce.length=0};;){let{done:P,value:oe}=await s.read();if(P)break;a+=o.decode(oe,{stream:!0});let Pe=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 r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},wo=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},ii=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},li=()=>{var n;let e=sm();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},ci=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=ep(t,tp|np);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?da(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=da(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},am=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?da(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?da(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=ep(o,tp|np),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},di=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var ga=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var im="https://api.runtype.com/v1/dispatch",fa="https://api.runtype.com",pi=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 lm(e){switch(e){case"json":return ci;case"regex-json":return li;case"xml":return di;default:return ii}}var sp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function cm(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=sp(t);if(!sp(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=wo(e);return wo(n)!==null&&a===null?n:e}var $o=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s;this.apiUrl=(t=n.apiUrl)!=null?t:im,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:lm(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa}/v1/client/feedback`}async sendFeedback(n){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.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 l=await this.buildPayload(n.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(pi).map(g=>{var v,x,k;return{id:g.id,role:g.role,content:(k=(x=(v=g.contentParts)!=null?v:g.llmContent)!=null?x:g.rawContent)!=null?k:g.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.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 x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}if(f.status===429){let x=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:x}),x}let v=new Error(g.error||"Failed to send message");throw t({type:"error",error:v}),v}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,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var i,d;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,""))||fa}/resume`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(o,{method:"POST",headers:a,body:JSON.stringify({executionId:n,toolOutputs:t,streamResponse:(d=r==null?void 0:r.streamResponse)!=null?d:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(pi).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}}),r={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:n,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&&(r.context=s)}return r}async buildPayload(n){let r={messages:n.slice().filter(pi).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:n,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&&(r.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...r},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return r.current=p,s(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var It,qt,vr,dr;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=P=>{let oe=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,Pe=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,qe=P.tools?P.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...P,reasoning:oe,toolCall:Pe,tools:qe}},p=P=>{t({type:"message",message:u(P)})},f=null,g={current:null},v={current:null},x=!1,k=new Map,w=new Map,L=new Map,D=new Map,W={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},M=(P,oe,Pe="")=>`${P}::${oe}::${Pe}`,O=(P,oe)=>`${P}::${oe}::`,U=(P,oe,Pe,qe)=>{let Fe=M(P,oe,Pe),Oe=L.get(Fe);if(Oe)return Oe;let Ze=Pe?`-${Pe}`:"",vt={id:`nested-${P}-${oe}${Ze}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Pe?{partId:Pe}:{},agentMetadata:{executionId:qe,parentToolId:P,parentStepId:oe}};return L.set(Fe,vt),p(vt),vt},$=P=>{if(P==null)return null;try{return String(P)}catch{return null}},H=P=>{var oe,Pe,qe,Fe,Oe;return $((Oe=(Fe=(qe=(Pe=(oe=P.stepId)!=null?oe:P.step_id)!=null?Pe:P.step)!=null?qe:P.parentId)!=null?Fe:P.flowStepId)!=null?Oe:P.flow_step_id)},F=P=>{var oe,Pe,qe,Fe,Oe,Ze,vt;return $((vt=(Ze=(Oe=(Fe=(qe=(Pe=(oe=P.callId)!=null?oe:P.call_id)!=null?Pe:P.requestId)!=null?qe:P.request_id)!=null?Fe:P.toolCallId)!=null?Oe:P.tool_call_id)!=null?Ze:P.stepId)!=null?vt:P.step_id)},K=r,ne=!1,Se=()=>{if(f)return f;let P;return!ne&&K?(P=K,ne=!0):K&&v.current?P=`${K}_${v.current}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},We=(P,oe)=>{W.lastId=oe,P&&W.byStep.set(P,oe)},_e=(P,oe)=>{var Oe;let Pe=(Oe=P.reasoningId)!=null?Oe:P.id,qe=H(P);if(Pe){let Ze=String(Pe);return We(qe,Ze),Ze}if(qe){let Ze=W.byStep.get(qe);if(Ze)return W.lastId=Ze,Ze}if(W.lastId&&!oe)return W.lastId;if(!oe)return null;let Fe=`reason-${l()}`;return We(qe,Fe),Fe},fe=P=>{let oe=k.get(P);if(oe)return oe;let Pe={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:P,status:"streaming",chunks:[]}};return k.set(P,Pe),p(Pe),Pe},pe=(P,oe)=>{E.lastId=oe,P&&E.byCall.set(P,oe)},Te=new Set,je=new Map,ee=new Set,xe=new Map,Q=P=>{if(!P)return!1;let oe=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return oe==="emit_artifact_markdown"||oe==="emit_artifact_component"},re=(P,oe)=>{var Oe;let Pe=(Oe=P.toolId)!=null?Oe:P.id,qe=F(P);if(Pe){let Ze=String(Pe);return pe(qe,Ze),Ze}if(qe){let Ze=E.byCall.get(qe);if(Ze)return E.lastId=Ze,Ze}if(E.lastId&&!oe)return E.lastId;if(!oe)return null;let Fe=`tool-${l()}`;return pe(qe,Fe),Fe},Me=P=>{let oe=w.get(P);if(oe)return oe;let Pe={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:P,status:"pending"}};return w.set(P,Pe),p(Pe),Pe},ae=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let oe=Number(P);if(!Number.isNaN(oe)&&Number.isFinite(oe))return oe;let Pe=Date.parse(P);if(!Number.isNaN(Pe))return Pe}return Date.now()},Be=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},Re=new Map,J=new Map,De=new Map,He=new Map,G=null,V=(P,oe,Pe)=>{var vt;let qe=De.get(P);qe||(qe=[],De.set(P,qe));let Fe=0,Oe=qe.length;for(;Fe<Oe;){let Ot=Fe+Oe>>>1;qe[Ot].seq<oe?Fe=Ot+1:Oe=Ot}((vt=qe[Fe])==null?void 0:vt.seq)===oe?qe[Fe]={seq:oe,text:Pe}:qe.splice(Fe,0,{seq:oe,text:Pe});let Ze="";for(let Ot=0;Ot<qe.length;Ot++)Ze+=qe[Ot].text;return Ze},ve=(P,oe)=>{let Pe=Be(oe),qe=J.get(P.id),Fe=cm(qe,Pe);P.rawContent=Fe;let Oe=Re.get(P.id),Ze=se=>{var pt;let Ce=(pt=P.content)!=null?pt:"";se.trim()!==""&&(Ce.trim().length===0||se.startsWith(Ce)||se.trimStart().startsWith(Ce.trim()))&&(P.content=se)},vt=()=>{var se;if(Oe){let Ce=(se=Oe.close)==null?void 0:se.call(Oe);Ce instanceof Promise&&Ce.catch(()=>{})}Re.delete(P.id),J.delete(P.id),P.streaming=!1,p(P)};if(!Oe){Ze(Pe),vt();return}let Ot=wo(Fe);if(Ot!==null&&Ot.trim()!==""){Ze(Ot),vt();return}let zt=se=>{var Je;let Ce=typeof se=="string"?se:(Je=se==null?void 0:se.text)!=null?Je:null;if(Ce!==null&&Ce.trim()!=="")return Ce;let pt=Oe.getExtractedText();return pt!==null&&pt.trim()!==""?pt:Pe},R;try{R=Oe.processChunk(Fe)}catch{Ze(Pe),vt();return}if(R instanceof Promise){R.then(se=>{Ze(zt(se)),vt()}).catch(()=>{Ze(Pe),vt()});return}Ze(zt(R)),vt()},ce=[],te=!1,me,Qe=()=>{te||(te=!0,queueMicrotask(()=>{te=!1,me()}))},Ft=new ga((P,oe)=>{ce.push({payloadType:P,payload:oe}),Qe()}),ie=null,Ne=new Map,an=(It=this.config.iterationDisplay)!=null?It:"separate";for(me=()=>{var P,oe,Pe,qe,Fe,Oe,Ze,vt,Ot,zt,R,se,Ce,pt,Je,Nt,ln,Ct,ht,St,it,Vt,Cr,jn,Dr,xt,pr,ur,wr,Yn,ct,io,mr,lo,En,Mo,Nr,Ar,mt,In,Wn,yn,Et,Un,qn,Rn,Fr,Sr,Or,Hn,kt,bn,zn,$r,Er,_r,gr,Bn,Zn,dt,Jt,Kt,Dn,jr,Vn,er,Nn,_,de,Fn,tr,fr,ts,nr,rr,or,Tr,co,Us,ns,qs,Lo,lt,rs,Jn,Tn,zs,Vs,Po,kr,Js,po,os,Mr,ss,Ur,qr,Ks,Gs,si,uo,zr,Qs,as,Vr,Xs,is,Jr,ls,Ys,Lr,Zs,Kr,Mt,Io,Wo,cs,hr,ea,ds,ps,us,ms,xn,On,Pr,et,gs,mo,sr,ta,Ro,Ho,go,Gr,na,ra,ar;for(let Ir=0;Ir<ce.length;Ir++){let Ve=ce[Ir].payloadType,C=ce[Ir].payload;if(Ve==="reason_start"){let j=(P=_e(C,!0))!=null?P:`reason-${l()}`,A=fe(j);A.reasoning=(oe=A.reasoning)!=null?oe:{id:j,status:"streaming",chunks:[]},A.reasoning.startedAt=(qe=A.reasoning.startedAt)!=null?qe:ae((Pe=C.startedAt)!=null?Pe:C.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",p(A)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let j=(Oe=(Fe=_e(C,!1))!=null?Fe:_e(C,!0))!=null?Oe:`reason-${l()}`,A=fe(j);A.reasoning=(Ze=A.reasoning)!=null?Ze:{id:j,status:"streaming",chunks:[]},A.reasoning.startedAt=(Ot=A.reasoning.startedAt)!=null?Ot:ae((vt=C.startedAt)!=null?vt:C.timestamp);let q=(se=(R=(zt=C.reasoningText)!=null?zt:C.text)!=null?R:C.delta)!=null?se:"";if(q&&C.hidden!==!0){let ke=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(ke!==void 0){let Z=V(j,ke,String(q));A.reasoning.chunks=[Z]}else A.reasoning.chunks.push(String(q))}if(A.reasoning.status=C.done?"complete":"streaming",C.done){A.reasoning.completedAt=ae((Ce=C.completedAt)!=null?Ce:C.timestamp);let ke=(pt=A.reasoning.startedAt)!=null?pt:Date.now();A.reasoning.durationMs=Math.max(0,((Je=A.reasoning.completedAt)!=null?Je:Date.now())-ke)}A.streaming=A.reasoning.status!=="complete",p(A)}else if(Ve==="reason_complete"){let j=(ln=(Nt=_e(C,!1))!=null?Nt:_e(C,!0))!=null?ln:`reason-${l()}`,A=k.get(j);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=ae((Ct=C.completedAt)!=null?Ct:C.timestamp);let ke=(ht=A.reasoning.startedAt)!=null?ht:Date.now();A.reasoning.durationMs=Math.max(0,((St=A.reasoning.completedAt)!=null?St:Date.now())-ke),A.streaming=!1,p(A)}let q=H(C);q&&W.byStep.delete(q)}else if(Ve==="tool_start"){let j=(it=re(C,!0))!=null?it:`tool-${l()}`,A=(Vt=C.toolName)!=null?Vt:C.name;if(Q(A)){Te.add(j);continue}let q=Me(j),ke=(Cr=q.toolCall)!=null?Cr:{id:j,status:"pending"};ke.name=A!=null?A:ke.name,ke.status="running",C.args!==void 0?ke.args=C.args:C.parameters!==void 0&&(ke.args=C.parameters),ke.startedAt=(Dr=ke.startedAt)!=null?Dr:ae((jn=C.startedAt)!=null?jn:C.timestamp),ke.completedAt=void 0,ke.durationMs=void 0,q.toolCall=ke,q.streaming=!0;let Z=C.agentContext;(Z||C.executionId)&&(q.agentMetadata={executionId:(xt=Z==null?void 0:Z.executionId)!=null?xt:C.executionId,iteration:(pr=Z==null?void 0:Z.iteration)!=null?pr:C.iteration}),p(q)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let j=(wr=(ur=re(C,!1))!=null?ur:re(C,!0))!=null?wr:`tool-${l()}`;if(Te.has(j))continue;let A=Me(j),q=(Yn=A.toolCall)!=null?Yn:{id:j,status:"running"};q.startedAt=(io=q.startedAt)!=null?io:ae((ct=C.startedAt)!=null?ct:C.timestamp);let ke=(En=(lo=(mr=C.text)!=null?mr:C.delta)!=null?lo:C.message)!=null?En:"";ke&&(q.chunks=(Mo=q.chunks)!=null?Mo:[],q.chunks.push(String(ke))),q.status="running",A.toolCall=q,A.streaming=!0;let Z=C.agentContext;(Z||C.executionId)&&(A.agentMetadata=(mt=A.agentMetadata)!=null?mt:{executionId:(Nr=Z==null?void 0:Z.executionId)!=null?Nr:C.executionId,iteration:(Ar=Z==null?void 0:Z.iteration)!=null?Ar:C.iteration}),p(A)}else if(Ve==="tool_complete"){let j=(Wn=(In=re(C,!1))!=null?In:re(C,!0))!=null?Wn:`tool-${l()}`;if(Te.has(j)){Te.delete(j);continue}let A=Me(j),q=(yn=A.toolCall)!=null?yn:{id:j,status:"running"};q.status="complete",C.result!==void 0&&(q.result=C.result),typeof C.duration=="number"&&(q.duration=C.duration),q.completedAt=ae((Et=C.completedAt)!=null?Et:C.timestamp);let ke=(Un=C.duration)!=null?Un:C.executionTime;if(typeof ke=="number")q.durationMs=ke;else{let Ke=(qn=q.startedAt)!=null?qn:Date.now();q.durationMs=Math.max(0,((Rn=q.completedAt)!=null?Rn:Date.now())-Ke)}A.toolCall=q,A.streaming=!1;let Z=C.agentContext;(Z||C.executionId)&&(A.agentMetadata=(Or=A.agentMetadata)!=null?Or:{executionId:(Fr=Z==null?void 0:Z.executionId)!=null?Fr:C.executionId,iteration:(Sr=Z==null?void 0:Z.iteration)!=null?Sr:C.iteration}),p(A);let Xe=F(C);Xe&&E.byCall.delete(Xe)}else if(Ve==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let j=(Hn=C.toolId)!=null?Hn:`local-${l()}`,A=Me(j),q=(kt=A.toolCall)!=null?kt:{id:j,status:"pending"};q.name=C.toolName,q.args=C.parameters,q.status="complete",q.chunks=(bn=q.chunks)!=null?bn:[],q.startedAt=($r=q.startedAt)!=null?$r:ae((zn=C.startedAt)!=null?zn:C.timestamp),q.completedAt=(Er=q.completedAt)!=null?Er:q.startedAt,A.toolCall=q,A.streaming=!1,A.agentMetadata={...A.agentMetadata,executionId:(gr=C.executionId)!=null?gr:(_r=A.agentMetadata)==null?void 0:_r.executionId,awaitingLocalTool:!0},p(A)}else if(Ve==="text_start"){if((Bn=C.toolContext)!=null&&Bn.toolId)continue;let j=C.partId;if(j!==void 0&&v.current!==null&&j!==v.current){let A=f;A&&(A.streaming=!1,p(A),G=A,f=null,x=!0)}j!==void 0&&(v.current=j)}else if(Ve==="text_end"){if((Zn=C.toolContext)!=null&&Zn.toolId)continue;let j=f;j&&(j.streaming=!1,p(j),G=j,f=null,x=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let j=C.stepType,A=C.executionType;if(j==="tool"||A==="context")continue;let q=C.toolContext;if(q!=null&&q.toolId){let Ke=String((Jt=(dt=C.id)!=null?dt:q.stepId)!=null?Jt:`step-${l()}`),Lt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",gt=`${q.toolId}::${Ke}`,Pt=D.get(gt);if(Lt!==""&&Pt!==void 0&&Pt!==""&&Pt!==Lt){let yt=L.get(M(q.toolId,Ke,Pt));yt&&yt.streaming!==!1&&(yt.streaming=!1,p(yt))}Lt!==""&&D.set(gt,Lt);let Ht=U(q.toolId,Ke,Lt,q.executionId),Gt=(Vn=(jr=(Dn=(Kt=C.text)!=null?Kt:C.delta)!=null?Dn:C.content)!=null?jr:C.chunk)!=null?Vn:"";Gt&&(Ht.content+=String(Gt),Ht.streaming=!0,p(Ht)),C.isComplete&&(Ht.streaming=!1,p(Ht));continue}let ke=C.partId;if(ke!==void 0&&v.current!==null&&ke!==v.current){let Ke=f;Ke&&(Ke.streaming=!1,p(Ke),G=Ke,f=null,x=!0)}ke!==void 0&&(v.current=ke);let Z=ke!==void 0&&(er=He.get(ke))!=null?er:Se();ke!==void 0&&(Z.partId||(Z.partId=ke),He.set(ke,Z));let Xe=(Fn=(de=(_=(Nn=C.text)!=null?Nn:C.delta)!=null?_:C.content)!=null?de:C.chunk)!=null?Fn:"";if(Xe){let Ke=typeof C.seq=="number"?C.seq:void 0,Lt=ke!=null?ke:Z.id,gt=Ke!==void 0?V(Lt,Ke,String(Xe)):((tr=J.get(Z.id))!=null?tr:"")+Xe;Z.rawContent=gt,Re.has(Z.id)||Re.set(Z.id,this.createStreamParser());let Pt=Re.get(Z.id),Ht=gt.trim().startsWith("{")||gt.trim().startsWith("[");if(Ht&&J.set(Z.id,gt),Pt.__isPlainTextParser===!0){Z.content=Ke!==void 0?gt:Z.content+Xe,J.delete(Z.id),Re.delete(Z.id),Z.rawContent=void 0,p(Z);continue}let yt=Pt.processChunk(gt);if(yt instanceof Promise)yt.then(ft=>{var un;let tn=typeof ft=="string"?ft:(un=ft==null?void 0:ft.text)!=null?un:null;if(tn!==null&&tn.trim()!=="")Z.content=tn,p(Z);else if(!Ht&&!gt.trim().startsWith("<")){let cn=f,Qt=cn&&cn.id===Z.id?cn:Z;Qt.id===Z.id&&(Qt.content=Ke!==void 0?gt:Qt.content+Xe,J.delete(Qt.id),Re.delete(Qt.id),Qt.rawContent=void 0,p(Qt))}}).catch(()=>{Z.content=Ke!==void 0?gt:Z.content+Xe,J.delete(Z.id),Re.delete(Z.id),Z.rawContent=void 0,p(Z)});else{let ft=typeof yt=="string"?yt:(fr=yt==null?void 0:yt.text)!=null?fr:null;ft!==null&&ft.trim()!==""?(Z.content=ft,p(Z)):!Ht&&!gt.trim().startsWith("<")&&(Z.content=Ke!==void 0?gt:Z.content+Xe,J.delete(Z.id),Re.delete(Z.id),Z.rawContent=void 0,p(Z))}}if(C.isComplete){let Ke=(nr=(ts=C.result)==null?void 0:ts.response)!=null?nr:Z.content;if(Ke){let Lt=J.get(Z.id),gt=Lt!=null?Lt:Be(Ke);Z.rawContent=gt;let Pt=Re.get(Z.id),Ht=null,Gt=!1;if(Pt&&(Ht=Pt.getExtractedText(),Ht===null&&(Ht=wo(gt)),Ht===null)){let yt=Pt.processChunk(gt);yt instanceof Promise?(Gt=!0,yt.then(ft=>{var un;let tn=typeof ft=="string"?ft:(un=ft==null?void 0:ft.text)!=null?un:null;if(tn!==null){let cn=f;cn&&cn.id===Z.id&&(cn.content=tn,cn.streaming=!1,Re.delete(cn.id),J.delete(cn.id),p(cn))}})):Ht=typeof yt=="string"?yt:(rr=yt==null?void 0:yt.text)!=null?rr:null}if(!Gt){Ht!==null&&Ht.trim()!==""?Z.content=Ht:J.has(Z.id)||(Z.content=Be(Ke));let yt=Re.get(Z.id);if(yt){let ft=(or=yt.close)==null?void 0:or.call(yt);ft instanceof Promise&&ft.catch(()=>{}),Re.delete(Z.id)}J.delete(Z.id),Z.streaming=!1,p(Z)}}}}else if(Ve==="step_complete"){let j=C.stepType,A=C.executionType;if(j==="tool"||A==="context")continue;let q=C.toolContext;if(q!=null&&q.toolId){let Ke=String((co=(Tr=C.id)!=null?Tr:q.stepId)!=null?co:"");if(Ke){let Lt=O(q.toolId,Ke);for(let[gt,Pt]of L)gt.startsWith(Lt)&&Pt.streaming!==!1&&(Pt.streaming=!1,p(Pt));D.delete(`${q.toolId}::${Ke}`)}continue}let ke=C.stopReason;if(x){if(f!==null){let gt=f;ke&&(gt.stopReason=ke),Re.delete(gt.id),J.delete(gt.id),gt.streaming!==!1&&(gt.streaming=!1,p(gt))}let Ke=(Us=C.result)==null?void 0:Us.response,Lt=G;Lt&&(ke&&(Lt.stopReason=ke),Ke!=null?ve(Lt,Ke):(Re.delete(Lt.id),J.delete(Lt.id))),G=null;continue}let Z=(ns=C.result)==null?void 0:ns.response,Xe=Se();if(ke&&(Xe.stopReason=ke),Z!=null){let Ke=Re.get(Xe.id),Lt=!1,gt=!1;if(Ke){let Pt=Ke.getExtractedText(),Ht=J.get(Xe.id),Gt=Ht!=null?Ht:Be(Z);if(Xe.rawContent=Gt,Pt!==null&&Pt.trim()!=="")Xe.content=Pt,Lt=!0;else{let yt=wo(Gt);if(yt!==null)Xe.content=yt,Lt=!0;else{let ft=Ke.processChunk(Gt);if(ft instanceof Promise)gt=!0,ft.then(tn=>{var cn;let un=typeof tn=="string"?tn:(cn=tn==null?void 0:tn.text)!=null?cn:null;if(un!==null&&un.trim()!==""){let Qt=f;Qt&&Qt.id===Xe.id&&(Qt.content=un,Qt.streaming=!1,Re.delete(Qt.id),J.delete(Qt.id),p(Qt))}else{let Qt=Ke.getExtractedText(),sn=f;sn&&sn.id===Xe.id&&(Qt!==null&&Qt.trim()!==""?sn.content=Qt:J.has(sn.id)||(sn.content=Be(Z)),sn.streaming=!1,Re.delete(sn.id),J.delete(sn.id),p(sn))}});else{let tn=typeof ft=="string"?ft:(qs=ft==null?void 0:ft.text)!=null?qs:null;if(tn!==null&&tn.trim()!=="")Xe.content=tn,Lt=!0;else{let un=Ke.getExtractedText();un!==null&&un.trim()!==""&&(Xe.content=un,Lt=!0)}}}}}if(!gt){if(!Xe.rawContent){let Pt=J.get(Xe.id);Xe.rawContent=Pt!=null?Pt:Be(Z)}if(!Lt&&!J.has(Xe.id)&&(Xe.content=Be(Z)),Ke){let Pt=(Lo=Ke.close)==null?void 0:Lo.call(Ke);Pt instanceof Promise&&Pt.catch(()=>{})}Re.delete(Xe.id),J.delete(Xe.id),Xe.streaming=!1,p(Xe)}}else Re.delete(Xe.id),J.delete(Xe.id),Xe.streaming=!1,p(Xe)}else if(Ve==="flow_complete"){let j=(lt=C.result)==null?void 0:lt.response;if(x){if(f!==null){let A=f;Re.delete(A.id),J.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}}else if(j!=null){let A=Se(),q=J.get(A.id),ke=q!=null?q:Be(j);A.rawContent=ke;let Z=Be(j),Xe=Re.get(A.id);if(Xe){let gt=wo(ke);if(gt!==null)Z=gt;else{let Pt=Xe.processChunk(ke);Pt instanceof Promise&&Pt.then(Gt=>{var ft;let yt=typeof Gt=="string"?Gt:(ft=Gt==null?void 0:Gt.text)!=null?ft:null;yt!==null&&(A.content=yt,A.streaming=!1,p(A))});let Ht=Xe.getExtractedText();Ht!==null&&(Z=Ht)}}Re.delete(A.id),J.delete(A.id);let Ke=Z!==A.content,Lt=A.streaming!==!1;Ke&&(A.content=Z),A.streaming=!1,(Ke||Lt)&&p(A)}else if(f!==null){let A=f;Re.delete(A.id),J.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}t({type:"status",status:"idle"})}else if(Ve==="agent_start")ie={executionId:C.executionId,agentId:(rs=C.agentId)!=null?rs:"virtual",agentName:(Jn=C.agentName)!=null?Jn:"",status:"running",currentIteration:0,maxTurns:(Tn=C.maxTurns)!=null?Tn:1,startedAt:ae(C.startedAt)};else if(Ve==="agent_iteration_start"){if(ie&&(ie.currentIteration=C.iteration),an==="separate"&&C.iteration>1){let j=f;j&&(j.streaming=!1,p(j),Ne.set(C.iteration-1,j),f=null)}}else if(Ve!=="agent_turn_start"){if(Ve==="agent_turn_delta"){if(C.contentType==="text"){let j=Se();j.content+=(zs=C.delta)!=null?zs:"",j.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:ie==null?void 0:ie.agentName},p(j)}else if(C.contentType==="thinking"){let j=(Vs=C.turnId)!=null?Vs:`agent-think-${C.iteration}`,A=fe(j);A.reasoning=(Po=A.reasoning)!=null?Po:{id:j,status:"streaming",chunks:[]},A.reasoning.chunks.push((kr=C.delta)!=null?kr:""),A.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(A)}else if(C.contentType==="tool_input"){let j=(Js=C.toolCallId)!=null?Js:E.lastId;if(j){let A=w.get(j);A!=null&&A.toolCall&&(A.toolCall.chunks=(po=A.toolCall.chunks)!=null?po:[],A.toolCall.chunks.push((os=C.delta)!=null?os:""),p(A))}}}else if(Ve==="agent_turn_complete"){let j=C.turnId;if(j){let q=k.get(j);if(q!=null&&q.reasoning){q.reasoning.status="complete",q.reasoning.completedAt=ae(C.completedAt);let ke=(Mr=q.reasoning.startedAt)!=null?Mr:Date.now();q.reasoning.durationMs=Math.max(0,((ss=q.reasoning.completedAt)!=null?ss:Date.now())-ke),q.streaming=!1,p(q)}}let A=C.stopReason;if(A&&f!==null){let q=C.turnId;(!q||((Ur=f.agentMetadata)==null?void 0:Ur.turnId)===q)&&(f.stopReason=A,p(f))}}else if(Ve==="agent_tool_start"){let j=(qr=C.toolCallId)!=null?qr:`agent-tool-${l()}`;pe(F(C),j);let A=Me(j),q=(Ks=A.toolCall)!=null?Ks:{id:j,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};q.name=(si=(Gs=C.toolName)!=null?Gs:C.name)!=null?si:q.name,q.status="running",C.parameters!==void 0&&(q.args=C.parameters),q.startedAt=ae((uo=C.startedAt)!=null?uo:C.timestamp),A.toolCall=q,A.streaming=!0,A.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(A)}else if(Ve==="agent_tool_delta"){let j=(zr=C.toolCallId)!=null?zr:E.lastId;if(j){let A=(Qs=w.get(j))!=null?Qs:Me(j);A.toolCall&&(A.toolCall.chunks=(as=A.toolCall.chunks)!=null?as:[],A.toolCall.chunks.push((Vr=C.delta)!=null?Vr:""),A.toolCall.status="running",A.streaming=!0,p(A))}}else if(Ve==="agent_tool_complete"){let j=(Xs=C.toolCallId)!=null?Xs:E.lastId;if(j){let A=(is=w.get(j))!=null?is:Me(j);if(A.toolCall){A.toolCall.status="complete",C.result!==void 0&&(A.toolCall.result=C.result),typeof C.executionTime=="number"&&(A.toolCall.durationMs=C.executionTime),A.toolCall.completedAt=ae((Jr=C.completedAt)!=null?Jr:C.timestamp),A.streaming=!1,p(A);let q=F(C);q&&E.byCall.delete(q)}}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let j=`agent-reflection-${C.executionId}-${C.iteration}`,A={id:j,role:"assistant",content:(ls=C.reflection)!=null?ls:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Ys=C.reflection)!=null?Ys:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(A)}else if(Ve==="agent_complete"){ie&&(ie.status=C.success?"complete":"error",ie.completedAt=ae(C.completedAt),ie.stopReason=C.stopReason);let j=f;j&&(j.streaming=!1,p(j)),t({type:"status",status:"idle"})}else if(Ve==="agent_error"){let j=typeof C.error=="string"?C.error:(Zs=(Lr=C.error)==null?void 0:Lr.message)!=null?Zs:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):t({type:"error",error:new Error(j)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let j=(Kr=C.approvalId)!=null?Kr:`approval-${l()}`,A={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Mt=ie==null?void 0:ie.agentId)!=null?Mt:"virtual",executionId:(Wo=(Io=C.executionId)!=null?Io:ie==null?void 0:ie.executionId)!=null?Wo:"",toolName:(cs=C.toolName)!=null?cs:"",toolType:C.toolType,description:(ea=C.description)!=null?ea:`Execute ${(hr=C.toolName)!=null?hr:"tool"}`,parameters:C.parameters}};p(A)}else if(Ve==="step_await"&&C.awaitReason==="approval_required"){let j=(ds=C.approvalId)!=null?ds:`approval-${l()}`,A={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(ps=ie==null?void 0:ie.agentId)!=null?ps:"virtual",executionId:(ms=(us=C.executionId)!=null?us:ie==null?void 0:ie.executionId)!=null?ms:"",toolName:(xn=C.toolName)!=null?xn:"",toolType:C.toolType,description:(Pr=C.description)!=null?Pr:`Execute ${(On=C.toolName)!=null?On:"tool"}`,parameters:C.parameters}};p(A)}else if(Ve==="agent_approval_complete"){let j=C.approvalId;if(j){let q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(et=C.decision)!=null?et:"approved",agentId:(gs=ie==null?void 0:ie.agentId)!=null?gs:"virtual",executionId:(sr=(mo=C.executionId)!=null?mo:ie==null?void 0:ie.executionId)!=null?sr:"",toolName:(ta=C.toolName)!=null?ta:"",description:(Ro=C.description)!=null?Ro:"",resolvedAt:Date.now()}};p(q)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let j=C.artifactType,A=String(C.id),q=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:A,artifactType:j,title:q,component:typeof C.component=="string"?C.component:void 0}),xe.set(A,{markdown:"",title:q}),!ee.has(A)){ee.add(A);let ke={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:q,artifactType:j,status:"streaming"}})};je.set(A,ke),p(ke)}}else if(Ve==="artifact_delta"){let j=String(C.id),A=typeof C.delta=="string"?C.delta:String((Ho=C.delta)!=null?Ho:"");t({type:"artifact_delta",id:j,artDelta:A});let q=xe.get(j);q&&(q.markdown+=A)}else if(Ve==="artifact_update"){let j=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:j,component:typeof C.component=="string"?C.component:void 0})}else if(Ve==="artifact_complete"){let j=String(C.id);t({type:"artifact_complete",id:j});let A=je.get(j);if(A){A.streaming=!1;try{let q=JSON.parse((go=A.rawContent)!=null?go:"{}");if(q.props){q.props.status="complete";let ke=xe.get(j);ke!=null&&ke.markdown&&(q.props.markdown=ke.markdown)}A.rawContent=JSON.stringify(q)}catch{}xe.delete(j),p(A),je.delete(j)}}}else if(Ve==="transcript_insert"){let j=C.message;if(!j||typeof j!="object")continue;let A=String((Gr=j.id)!=null?Gr:`msg-${l()}`),q=j.role,Z={id:A,role:q==="user"?"user":q==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(p(Z),Z.rawContent)try{let Xe=JSON.parse(Z.rawContent),Ke=(na=Xe==null?void 0:Xe.props)==null?void 0:na.artifactId;typeof Ke=="string"&&ee.add(Ke)}catch{}f=null,g.current=null,Re.delete(A),J.delete(A)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let j=null;if(C.error instanceof Error)j=C.error;else if(Ve==="dispatch_error"){let A=(ra=C.message)!=null?ra:C.error;A!=null&&A!==""&&(j=new Error(String(A)))}else if(Ve==="step_error"||Ve==="flow_error"){let A=C.error;typeof A=="string"&&A!==""?j=new Error(A):A!=null&&typeof A=="object"&&"message"in A&&(j=new Error(String((ar=A.message)!=null?ar:A)))}else Ve==="error"&&C.error!=null&&C.error!==""&&(j=new Error(String(C.error)));if(j){t({type:"error",error:j});let A=f;A&&A.streaming&&(A.streaming=!1,p(A)),t({type:"status",status:"idle"})}}}}}}ce.length=0};;){let{done:P,value:oe}=await s.read();if(P)break;a+=o.decode(oe,{stream:!0});let Pe=a.split(`
|
|
5
5
|
|
|
6
6
|
`);a=(qt=Pe.pop())!=null?qt:"";for(let qe of Pe){let Fe=qe.split(`
|
|
7
|
-
`),Oe="message",Ze="";for(let zt of Fe)zt.startsWith("event:")?Oe=zt.replace("event:","").trim():zt.startsWith("data:")&&(Ze+=zt.replace("data:","").trim());if(!Ze)continue;let vt;try{vt=JSON.parse(Ze)}catch(zt){t({type:"error",error:zt instanceof Error?zt:new Error("Failed to parse chat stream payload")});continue}let Ot=Oe!=="message"?Oe:(vr=vt.type)!=null?vr:"message";if((dr=this.onSSEEvent)==null||dr.call(this,Ot,vt),this.parseSSEEvent){g.current=f;let zt=await this.handleCustomSSEEvent(vt,t,g,p,l,v);if(g.current&&g.current!==f&&(f=g.current),zt)continue}Ft.push(Ot,vt),me()}}Ft.flushPending(),me(),Ft.destroy()}};function cm(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function ws(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function _o(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var ha="[Image]";function dm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function pm(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function um(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function mm(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function ya(e){return{type:"text",text:e}}function gm(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function fm(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function hm(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var ap=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ym=["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"],Hr=[...ap,...ym];function bm(e){return ap.includes(e)||e.startsWith("image/")}function ba(e){return bm(e.type)}async function ip(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;ba(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function lp(e,n=Hr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function xm(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function cp(e,n){let t=xm(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var xa=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var va=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Cs=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new va;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" 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 v=!1,x=C=>{v||(v=!0,clearTimeout(k),g(new Error(C)))},k=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(k),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",C=>{if(!C.wasClean&&!v){let L=C.code!==1006?` (code ${C.code})`:"";x("WebSocket connection failed"+L+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new xa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ao=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Uo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Cs(e.runtype);case"browser":if(!Ao.isSupported())throw new Error("Browser speech recognition not supported");return new Ao(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ui(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Uo({type:"runtype",runtype:e.runtype});if(Ao.isSupported())return Uo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function wa(e){try{return ui(e),!0}catch{return!1}}var As=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,d;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=n.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new $o(n);for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return wa((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Uo(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,g,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.text)!=null&&g.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let k=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(C=>C.role==="assistant"))==null?void 0:v.id;k&&this.ttsSpokenMessageIds.add(k)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(u=n.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new $o(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u}=n,f={id:a!=null?a:t==="user"?ws():t==="assistant"?_o():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u}};return this.upsertMessage(f),f}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1}=r,g={id:d!=null?d:s==="user"?ws():s==="assistant"?_o():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...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(n,t){var l,u,p,f,g;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort();let s=ws(),o=_o(),a={id:s,role:"user",content:r||ha,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let k={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(k)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=_o();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let u={id:n,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(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(n,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,l,u;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):p=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let g=await p.json().catch(()=>null);throw new Error((d=g==null?void 0:g.error)!=null?d:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(u=(l=this.callbacks).onError)==null||u.call(l,p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var u,p,f,g,v,x,k,C,L,D,W;let r=this.messages.find(E=>E.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(p=n.agentMetadata)==null?void 0:p.executionId,o=(f=n.toolCall)==null?void 0:f.name;if(!s||!o){(v=(g=this.callbacks).onError)==null||v.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let E=(x=n.toolCall)==null?void 0:x.args,M=Array.isArray(E==null?void 0:E.questions)?E.questions:[];if(M.length===1){let O=typeof((k=M[0])==null?void 0:k.question)=="string"?M[0].question:"";O&&(a={[O]:t})}}this.markAskUserQuestionResolved(n,a);let i=n.toolCall.id,d=(C=n.toolCall)==null?void 0:C.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let E=typeof t=="string"?t:Object.entries(t).map(([M,O])=>`${M}: ${Array.isArray(O)?O.join(", "):O}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let E=a!=null?a:{};l.forEach((M,O)=>{let j=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!j)return;let $=E[j],H=Array.isArray($)?$.join(", "):typeof $=="string"?$:"";this.appendMessage({id:`ask-user-q-${i}-${O}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${O}`,role:"user",content:H||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let E=await this.client.resumeFlow(s,{[o]:t});if(!E.ok){let M=await E.json().catch(()=>null);throw new Error((L=M==null?void 0:M.error)!=null?L:`Resume failed: ${E.status}`)}E.body&&await this.connectStream(E.body)}catch(E){(W=(D=this.callbacks).onError)==null||W.call(D,E instanceof Error?E:new Error(String(E)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var i;if(o!==r)return s;let a={...s,...t};return((i=s.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},br=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import{Activity as vm,ArrowDown as wm,ArrowUp as Cm,ArrowUpRight as Am,Bot as Sm,ChevronDown as Em,ChevronUp as Tm,ChevronRight as km,ChevronLeft as Mm,Check as Lm,Clipboard as Pm,ClipboardCopy as Im,Copy as Wm,File as Rm,FileCode as Hm,FileSpreadsheet as Bm,FileText as Dm,ImagePlus as Nm,Loader as Fm,LoaderCircle as Om,Mic as $m,Paperclip as _m,RefreshCw as Um,Search as jm,Send as qm,ShieldAlert as zm,ShieldCheck as Vm,ShieldX as Jm,Square as Km,ThumbsDown as Gm,ThumbsUp as Qm,Upload as Xm,Volume2 as Ym,X as Zm,User as eg,Mail as tg,Phone as ng,Calendar as rg,Clock as og,Building as sg,MapPin as ag,Lock as ig,Key as lg,CreditCard as cg,AtSign as dg,Hash as pg,Globe as ug,Link as mg,CircleCheck as gg,CircleX as fg,TriangleAlert as hg,Info as yg,Ban as bg,Shield as xg,ArrowLeft as vg,ArrowRight as wg,ExternalLink as Cg,Ellipsis as Ag,EllipsisVertical as Sg,Menu as Eg,House as Tg,Plus as kg,Minus as Mg,Pencil as Lg,Trash as Pg,Trash2 as Ig,Save as Wg,Download as Rg,Share as Hg,Funnel as Bg,Settings as Dg,RotateCw as Ng,Maximize as Fg,Minimize as Og,ShoppingCart as $g,ShoppingBag as _g,Package as Ug,Truck as jg,Tag as qg,Gift as zg,Receipt as Vg,Wallet as Jg,Store as Kg,DollarSign as Gg,Percent as Qg,Play as Xg,Pause as Yg,VolumeX as Zg,Camera as ef,Image as tf,Film as nf,Headphones as rf,MessageCircle as of,MessageSquare as sf,Bell as af,Heart as lf,Star as cf,Eye as df,EyeOff as pf,Bookmark as uf,CalendarDays as mf,History as gf,Timer as ff,Folder as hf,FolderOpen as yf,Files as bf,Sparkles as xf,Zap as vf,Sun as wf,Moon as Cf,Flag as Af,Monitor as Sf,Smartphone as Ef}from"lucide";var Tf={activity:vm,"arrow-down":wm,"arrow-up":Cm,"arrow-up-right":Am,bot:Sm,"chevron-down":Em,"chevron-up":Tm,"chevron-right":km,"chevron-left":Mm,check:Lm,clipboard:Pm,"clipboard-copy":Im,copy:Wm,file:Rm,"file-code":Hm,"file-spreadsheet":Bm,"file-text":Dm,"image-plus":Nm,loader:Fm,"loader-circle":Om,mic:$m,paperclip:_m,"refresh-cw":Um,search:jm,send:qm,"shield-alert":zm,"shield-check":Vm,"shield-x":Jm,square:Km,"thumbs-down":Gm,"thumbs-up":Qm,upload:Xm,"volume-2":Ym,x:Zm,user:eg,mail:tg,phone:ng,calendar:rg,clock:og,building:sg,"map-pin":ag,lock:ig,key:lg,"credit-card":cg,"at-sign":dg,hash:pg,globe:ug,link:mg,"circle-check":gg,"circle-x":fg,"triangle-alert":hg,info:yg,ban:bg,shield:xg,"arrow-left":vg,"arrow-right":wg,"external-link":Cg,ellipsis:Ag,"ellipsis-vertical":Sg,menu:Eg,house:Tg,plus:kg,minus:Mg,pencil:Lg,trash:Pg,"trash-2":Ig,save:Wg,download:Rg,share:Hg,funnel:Bg,settings:Dg,"rotate-cw":Ng,maximize:Fg,minimize:Og,"shopping-cart":$g,"shopping-bag":_g,package:Ug,truck:jg,tag:qg,gift:zg,receipt:Vg,wallet:Jg,store:Kg,"dollar-sign":Gg,percent:Qg,play:Xg,pause:Yg,"volume-x":Zg,camera:ef,image:tf,film:nf,headphones:rf,"message-circle":of,"message-square":sf,bell:af,heart:lf,star:cf,eye:df,"eye-off":pf,bookmark:uf,"calendar-days":mf,history:gf,timer:ff,folder:hf,"folder-open":yf,files:bf,sparkles:xf,zap:vf,sun:wf,moon:Cf,flag:Af,monitor:Sf,smartphone:Ef},ge=(e,n=24,t="currentColor",r=2)=>{let s=Tf[e];return s?kf(s,n,t,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function kf(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),s.appendChild(d)}),s}var Ca={allowedTypes:Hr,maxFileSize:10*1024*1024,maxFiles:4};function Mf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Lf(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var jo=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ca.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ca.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Ca.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Ca.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let u=lp(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,p);continue}try{let p=await ip(l),f=ba(l)?URL.createObjectURL(l):null,g={id:Mf(),file:l,previewUrl:f,contentPart:p};this.attachments.push(g),this.renderPreview(g)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=ba(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Lf(n.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=cp(n.file.type,n.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=ge("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var dp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ss(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];dp(o)&&dp(s)?t[r]=Ss(o,s):t[r]=s}return t}var Gn="min(440px, calc(100vw - 24px))",mi="440px",Dt={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:Gn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function pp(e,n){if(!(!e&&!n))return e?n?Ss(e,n):e:n}function gi(e){var n,t,r,s,o,a,i,d,l,u,p,f,g,v,x,k,C,L,D,W,E;return e?{...Dt,...e,theme:pp(Dt.theme,e.theme),darkTheme:pp(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(n=Dt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var pe,Te,Ue,ee,xe,Q,re,Me;let M=(pe=Dt.features)==null?void 0:pe.artifacts,O=(Te=e.features)==null?void 0:Te.artifacts,j=(Ue=Dt.features)==null?void 0:Ue.scrollToBottom,$=(ee=e.features)==null?void 0:ee.scrollToBottom,H=(xe=Dt.features)==null?void 0:xe.streamAnimation,F=(Q=e.features)==null?void 0:Q.streamAnimation,K=(re=Dt.features)==null?void 0:re.askUserQuestion,ne=(Me=e.features)==null?void 0:Me.askUserQuestion,Se=M===void 0&&O===void 0?void 0:{...M,...O,layout:{...M==null?void 0:M.layout,...O==null?void 0:O.layout}},We=j===void 0&&$===void 0?void 0:{...j,...$},_e=H===void 0&&F===void 0?void 0:{...H,...F},fe=K===void 0&&ne===void 0?void 0:{...K,...ne,styles:{...K==null?void 0:K.styles,...ne==null?void 0:ne.styles}};return{...Dt.features,...e.features,...We!==void 0?{scrollToBottom:We}:{},...Se!==void 0?{artifacts:Se}:{},..._e!==void 0?{streamAnimation:_e}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Dt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(x=(v=Dt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(C=(k=e.layout)==null?void 0:k.messages)==null?void 0:C.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(W=Dt.markdown)==null?void 0:W.options,...(E=e.markdown)==null?void 0:E.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var up={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},mp={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"}},gp={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:Gn,maxWidth:mi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function qo(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?qo(e,r):r}function fi(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=qo(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function fp(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function hp(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=hp(o,s):t[r]=s}return t}function Pf(e,n){return n?hp(e,n):e}function Es(e,n={}){var s,o,a,i,d,l,u,p,f,g,v,x,k;let t={palette:up,semantic:mp,components:gp},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:Pf(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let C=fp(r);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(L=>L.message).join(", ")}`)}if(n.plugins)for(let C of n.plugins)r=C.transform(r);return r}function hi(e){var x,k,C,L,D,W,E,M,O,j,$,H,F,K,ne,Se,We,_e,fe,pe,Te,Ue,ee,xe,Q,re,Me,ae,Be,Re,J,De,He,G,V,ve,ce,te,me,Qe,Ft,ie,Ne,an,Pt,qt,vr,dr,P,oe,Pe,qe,Fe,Oe,Ze,vt,Ot,zt,R,se,we,pt,Je,Nt,ln,wt,ht,St,it,Vt,wr,Un,Dr,xt,pr,ur,Cr,Yn,ct,io,mr,lo,En,Mo,Nr,Ar,mt,In,Wn,yn,Et,jn,qn,Rn,Fr,Sr,Or,Hn,kt,bn,zn,$r,Er,_r,gr,Bn,Zn,dt,Jt,Kt,Dn,Ur,Vn,er,Nn,_;let n=fi(e),t={};for(let[de,Fn]of Object.entries(n)){let tr=de.replace(/\./g,"-");t[`--persona-${tr}`]=Fn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(k=t["--persona-semantic-colors-secondary"])!=null?k: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"]=(L=t["--persona-semantic-colors-surface"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(D=t["--persona-semantic-colors-background"])!=null?D:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(W=t["--persona-semantic-colors-container"])!=null?W:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(E=t["--persona-semantic-colors-text"])!=null?E:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(M=t["--persona-semantic-colors-text-muted"])!=null?M:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(O=t["--persona-semantic-colors-text-inverse"])!=null?O:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(j=t["--persona-semantic-colors-border"])!=null?j:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=($=t["--persona-semantic-colors-divider"])!=null?$:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(H=t["--persona-components-voice-recording-indicator"])!=null?H:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(F=t["--persona-components-voice-recording-background"])!=null?F:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(K=t["--persona-components-voice-processing-icon"])!=null?K:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Se=t["--persona-components-approval-requested-background"])!=null?Se:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(We=t["--persona-components-approval-requested-border"])!=null?We:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(_e=t["--persona-components-approval-requested-text"])!=null?_e:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(fe=t["--persona-components-approval-approve-background"])!=null?fe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(pe=t["--persona-components-approval-deny-background"])!=null?pe:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Te=t["--persona-components-attachment-image-background"])!=null?Te:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Ue=t["--persona-components-attachment-image-border"])!=null?Ue:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ee=t["--persona-semantic-typography-fontFamily"])!=null?ee:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(xe=t["--persona-semantic-typography-fontSize"])!=null?xe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Q=t["--persona-semantic-typography-fontWeight"])!=null?Q:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(re=t["--persona-semantic-typography-lineHeight"])!=null?re: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"]=(Me=t["--persona-palette-radius-sm"])!=null?Me:"0.125rem",t["--persona-radius-md"]=(ae=t["--persona-palette-radius-md"])!=null?ae:"0.375rem",t["--persona-radius-lg"]=(Be=t["--persona-palette-radius-lg"])!=null?Be:"0.5rem",t["--persona-radius-xl"]=(Re=t["--persona-palette-radius-xl"])!=null?Re:"0.75rem",t["--persona-radius-full"]=(J=t["--persona-palette-radius-full"])!=null?J:"9999px",t["--persona-launcher-radius"]=(He=(De=t["--persona-components-launcher-borderRadius"])!=null?De:t["--persona-palette-radius-full"])!=null?He:"9999px",t["--persona-launcher-bg"]=(G=t["--persona-components-launcher-background"])!=null?G:t["--persona-primary"],t["--persona-launcher-fg"]=(V=t["--persona-components-launcher-foreground"])!=null?V:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ve=t["--persona-components-launcher-border"])!=null?ve: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"]=(te=t["--persona-components-button-primary-foreground"])!=null?te:t["--persona-text-inverse"],t["--persona-button-radius"]=(Qe=(me=t["--persona-components-button-primary-borderRadius"])!=null?me:t["--persona-palette-radius-full"])!=null?Qe:"9999px",t["--persona-panel-radius"]=(ie=(Ft=t["--persona-components-panel-borderRadius"])!=null?Ft:t["--persona-radius-xl"])!=null?ie:"0.75rem",t["--persona-panel-border"]=(Ne=t["--persona-components-panel-border"])!=null?Ne:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Pt=(an=t["--persona-components-panel-shadow"])!=null?an:t["--persona-palette-shadows-xl"])!=null?Pt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(vr=(qt=t["--persona-components-input-borderRadius"])!=null?qt:t["--persona-radius-lg"])!=null?vr:"0.5rem",t["--persona-message-user-radius"]=(P=(dr=t["--persona-components-message-user-borderRadius"])!=null?dr:t["--persona-radius-lg"])!=null?P:"0.5rem",t["--persona-message-assistant-radius"]=(Pe=(oe=t["--persona-components-message-assistant-borderRadius"])!=null?oe:t["--persona-radius-lg"])!=null?Pe:"0.5rem",t["--persona-header-bg"]=(qe=t["--persona-components-header-background"])!=null?qe:t["--persona-surface"],t["--persona-header-border"]=(Fe=t["--persona-components-header-border"])!=null?Fe:t["--persona-divider"],t["--persona-header-icon-bg"]=(Oe=t["--persona-components-header-iconBackground"])!=null?Oe:t["--persona-primary"],t["--persona-header-icon-fg"]=(Ze=t["--persona-components-header-iconForeground"])!=null?Ze:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(vt=t["--persona-components-header-titleForeground"])!=null?vt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ot=t["--persona-components-header-subtitleForeground"])!=null?Ot:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(zt=t["--persona-components-header-actionIconForeground"])!=null?zt:t["--persona-muted"];let r=(R=e.components)==null?void 0:R.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(se=e.components)==null?void 0:se.introCard;t["--persona-intro-card-bg"]=(we=t["--persona-components-introCard-background"])!=null?we:t["--persona-surface"],t["--persona-intro-card-radius"]=(pt=t["--persona-components-introCard-borderRadius"])!=null?pt:"1rem",t["--persona-intro-card-padding"]=(Je=t["--persona-components-introCard-padding"])!=null?Je:"1.5rem",t["--persona-intro-card-shadow"]=(ln=(Nt=s==null?void 0:s.shadow)!=null?Nt:t["--persona-components-introCard-shadow"])!=null?ln:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(wt=t["--persona-components-input-background"])!=null?wt:t["--persona-surface"],t["--persona-input-placeholder"]=(ht=t["--persona-components-input-placeholder"])!=null?ht:t["--persona-text-muted"],t["--persona-message-user-bg"]=(St=t["--persona-components-message-user-background"])!=null?St:t["--persona-accent"],t["--persona-message-user-text"]=(it=t["--persona-components-message-user-text"])!=null?it:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Vt=t["--persona-components-message-user-shadow"])!=null?Vt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(wr=t["--persona-components-message-assistant-background"])!=null?wr:t["--persona-surface"],t["--persona-message-assistant-text"]=(Un=t["--persona-components-message-assistant-text"])!=null?Un:t["--persona-text"],t["--persona-message-assistant-border"]=(Dr=t["--persona-components-message-assistant-border"])!=null?Dr:t["--persona-border"],t["--persona-message-assistant-shadow"]=(xt=t["--persona-components-message-assistant-shadow"])!=null?xt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(pr=t["--persona-components-scrollToBottom-background"])!=null?pr:t["--persona-button-primary-bg"])!=null?ur:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Yn=(Cr=t["--persona-components-scrollToBottom-foreground"])!=null?Cr:t["--persona-button-primary-fg"])!=null?Yn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(ct=t["--persona-components-scrollToBottom-border"])!=null?ct:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(io=t["--persona-components-scrollToBottom-size"])!=null?io:"40px",t["--persona-scroll-to-bottom-radius"]=(En=(lo=(mr=t["--persona-components-scrollToBottom-borderRadius"])!=null?mr:t["--persona-button-radius"])!=null?lo:t["--persona-radius-full"])!=null?En:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Nr=(Mo=t["--persona-components-scrollToBottom-shadow"])!=null?Mo:t["--persona-palette-shadows-sm"])!=null?Nr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Ar=t["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(mt=t["--persona-components-scrollToBottom-gap"])!=null?mt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Wn=(In=t["--persona-components-scrollToBottom-fontSize"])!=null?In:t["--persona-palette-typography-fontSize-sm"])!=null?Wn:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(yn=t["--persona-components-scrollToBottom-iconSize"])!=null?yn:"14px",t["--persona-tool-bubble-shadow"]=(Et=t["--persona-components-toolBubble-shadow"])!=null?Et:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(jn=t["--persona-components-reasoningBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(qn=t["--persona-components-composer-shadow"])!=null?qn:"none",t["--persona-md-inline-code-bg"]=(Rn=t["--persona-components-markdown-inlineCode-background"])!=null?Rn:t["--persona-container"],t["--persona-md-inline-code-color"]=(Fr=t["--persona-components-markdown-inlineCode-foreground"])!=null?Fr:t["--persona-text"],t["--persona-md-link-color"]=(Or=(Sr=t["--persona-components-markdown-link-foreground"])!=null?Sr:t["--persona-accent"])!=null?Or:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Hn=t["--persona-components-markdown-codeBlock-background"])!=null?Hn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(kt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?kt:t["--persona-border"],t["--persona-md-code-block-text-color"]=(bn=t["--persona-components-markdown-codeBlock-textColor"])!=null?bn:"inherit",t["--persona-md-table-header-bg"]=(zn=t["--persona-components-markdown-table-headerBackground"])!=null?zn:t["--persona-container"],t["--persona-md-table-border-color"]=($r=t["--persona-components-markdown-table-borderColor"])!=null?$r:t["--persona-border"],t["--persona-md-hr-color"]=(Er=t["--persona-components-markdown-hr-color"])!=null?Er:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(_r=t["--persona-components-markdown-blockquote-borderColor"])!=null?_r:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(gr=t["--persona-components-markdown-blockquote-background"])!=null?gr:"transparent",t["--persona-md-blockquote-text-color"]=(Bn=t["--persona-components-markdown-blockquote-textColor"])!=null?Bn:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Zn=t["--persona-components-collapsibleWidget-container"])!=null?Zn:t["--persona-surface"],t["--cw-surface"]=(dt=t["--persona-components-collapsibleWidget-surface"])!=null?dt:t["--persona-surface"],t["--cw-border"]=(Jt=t["--persona-components-collapsibleWidget-border"])!=null?Jt:t["--persona-border"],t["--persona-message-border"]=(Kt=t["--persona-components-message-border"])!=null?Kt:t["--persona-border"];let u=e.components,p=u==null?void 0:u.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 f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let g=u==null?void 0:u.toggleGroup;g&&(g.gap&&(t["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(t["--persona-toggle-group-radius"]=g.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let de=v.toolbar;de.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=de.iconHoverColor),de.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=de.iconHoverBackground),de.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=de.iconPadding),de.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=de.iconBorderRadius),de.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=de.iconBorder),de.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=de.toggleGroupGap),de.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=de.toggleBorderRadius),de.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=de.copyBackground),de.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=de.copyBorder),de.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=de.copyColor),de.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=de.copyBorderRadius),de.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=de.copyPadding),de.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=de.copyMenuBackground,t["--persona-dropdown-bg"]=(Dn=t["--persona-dropdown-bg"])!=null?Dn:de.copyMenuBackground),de.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=de.copyMenuBorder,t["--persona-dropdown-border"]=(Ur=t["--persona-dropdown-border"])!=null?Ur:de.copyMenuBorder),de.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=de.copyMenuShadow,t["--persona-dropdown-shadow"]=(Vn=t["--persona-dropdown-shadow"])!=null?Vn:de.copyMenuShadow),de.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=de.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(er=t["--persona-dropdown-radius"])!=null?er:de.copyMenuBorderRadius),de.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=de.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Nn=t["--persona-dropdown-item-hover-bg"])!=null?Nn:de.copyMenuItemHoverBackground),de.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=de.iconBackground),de.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=de.toolbarBorder)}if(v!=null&&v.tab){let de=v.tab;de.background&&(t["--persona-artifact-tab-bg"]=de.background),de.activeBackground&&(t["--persona-artifact-tab-active-bg"]=de.activeBackground),de.activeBorder&&(t["--persona-artifact-tab-active-border"]=de.activeBorder),de.borderRadius&&(t["--persona-artifact-tab-radius"]=de.borderRadius),de.textColor&&(t["--persona-artifact-tab-color"]=de.textColor),de.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=de.hoverBackground),de.listBackground&&(t["--persona-artifact-tab-list-bg"]=de.listBackground),de.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=de.listBorderColor),de.listPadding&&(t["--persona-artifact-tab-list-padding"]=de.listPadding)}if(v!=null&&v.pane){let de=v.pane;if(de.toolbarBackground){let Fn=(_=qo(e,de.toolbarBackground))!=null?_:de.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Fn}}return t}var If={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 Wf={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"}}},yp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Aa=()=>{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"},Rf=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Aa()},bp=e=>Rf(e),Hf=e=>Es(e),Bf=e=>{var t;let n=Es(void 0,{validate:!1});return Es({...e,palette:{...n.palette,colors:{...Wf.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Ts=e=>{let n=bp(e),t=yp(e==null?void 0:e.theme),r=yp(e==null?void 0:e.darkTheme);return n==="dark"?Bf(Ss(t!=null?t:{},r!=null?r:{})):Hf(t)},Df=e=>hi(e),So=(e,n)=>{var o;let t=Ts(n),r=Df(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},yi=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Aa())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Aa());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as Nf}from"idiomorph";var Sa=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Nf.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function xp(e,n){var t,r,s,o,a,i,d,l,u,p,f,g,v,x,k,C,L,D,W,E,M,O,j,$,H,F,K,ne,Se,We;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(k=(x=e.toolCall)==null?void 0:x.name)!=null?k:"",(D=(L=(C=e.toolCall)==null?void 0:C.chunks)==null?void 0:L.length)!=null?D:0,(O=(M=(E=(W=e.toolCall)==null?void 0:W.chunks)==null?void 0:E[e.toolCall.chunks.length-1])==null?void 0:M.slice(-32))!=null?O:"",typeof((j=e.toolCall)==null?void 0:j.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(K=(F=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:F.length)!=null?K:0,(Se=(ne=e.contentParts)==null?void 0:ne.length)!=null?Se:0,(We=e.stopReason)!=null?We:"",n].join("\0")}function vp(){return new Map}function wp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Cp(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Ap(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Ea(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function ks(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ms(e,n){return ks(e)-e.scrollTop<=n}function Ta(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:t}:!n&&s&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function ka(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,Xr=hn+1;var Ls={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ff=["pre","code","a","script","style"],Ma=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Ls.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:Ls.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ls.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ls.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ls.buffer}},Ep=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Ps=new Map;for(let e of Ep)Ps.set(e.name,e);var Of=e=>{Ps.set(e.name,e)},$f=e=>{Ep.some(n=>n.name===e)||Ps.delete(e)},_f=()=>Array.from(Ps.keys()),Is=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Ps.get(e))!=null?r:null},La=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
|
|
8
|
-
`);return o<0?"":e.slice(0,o)}return e},Uf=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},
|
|
7
|
+
`),Oe="message",Ze="";for(let zt of Fe)zt.startsWith("event:")?Oe=zt.replace("event:","").trim():zt.startsWith("data:")&&(Ze+=zt.replace("data:","").trim());if(!Ze)continue;let vt;try{vt=JSON.parse(Ze)}catch(zt){t({type:"error",error:zt instanceof Error?zt:new Error("Failed to parse chat stream payload")});continue}let Ot=Oe!=="message"?Oe:(vr=vt.type)!=null?vr:"message";if((dr=this.onSSEEvent)==null||dr.call(this,Ot,vt),this.parseSSEEvent){g.current=f;let zt=await this.handleCustomSSEEvent(vt,t,g,p,l,v);if(g.current&&g.current!==f&&(f=g.current),zt)continue}Ft.push(Ot,vt),me()}}Ft.flushPending(),me(),Ft.destroy()}};function dm(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Cs(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function _o(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var ha="[Image]";function pm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function um(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function mm(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function gm(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function ya(e){return{type:"text",text:e}}function fm(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function hm(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function ym(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var ap=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],bm=["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"],Hr=[...ap,...bm];function xm(e){return ap.includes(e)||e.startsWith("image/")}function ba(e){return xm(e.type)}async function ip(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;ba(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function lp(e,n=Hr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function vm(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function cp(e,n){let t=vm(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var xa=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var va=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var ws=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new va;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" 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 v=!1,x=w=>{v||(v=!0,clearTimeout(k),g(new Error(w)))},k=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(k),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",w=>{if(!w.wasClean&&!v){let L=w.code!==1006?` (code ${w.code})`:"";x("WebSocket connection failed"+L+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new xa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ao=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function jo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ws(e.runtype);case"browser":if(!Ao.isSupported())throw new Error("Browser speech recognition not supported");return new Ao(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ui(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return jo({type:"runtype",runtype:e.runtype});if(Ao.isSupported())return jo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ca(e){try{return ui(e),!0}catch{return!1}}var As=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,d;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=n.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new $o(n);for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Ca((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=jo(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,g,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.text)!=null&&g.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let k=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(w=>w.role==="assistant"))==null?void 0:v.id;k&&this.ttsSpokenMessageIds.add(k)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(u=n.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new $o(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=n,g={id:a!=null?a:t==="user"?Cs():t==="assistant"?_o():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(g),g}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:g}=r,x={id:d!=null?d:s==="user"?Cs():s==="assistant"?_o():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=n,l={text:s,component:t,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(n,t){var l,u,p,f,g;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort();let s=Cs(),o=_o(),a={id:s,role:"user",content:r||ha,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let k={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(k)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=_o();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let u={id:n,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(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(n,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,l,u;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):p=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let g=await p.json().catch(()=>null);throw new Error((d=g==null?void 0:g.error)!=null?d:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(u=(l=this.callbacks).onError)==null||u.call(l,p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var u,p,f,g,v,x,k,w,L,D,W;let r=this.messages.find(E=>E.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(p=n.agentMetadata)==null?void 0:p.executionId,o=(f=n.toolCall)==null?void 0:f.name;if(!s||!o){(v=(g=this.callbacks).onError)==null||v.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let E=(x=n.toolCall)==null?void 0:x.args,M=Array.isArray(E==null?void 0:E.questions)?E.questions:[];if(M.length===1){let O=typeof((k=M[0])==null?void 0:k.question)=="string"?M[0].question:"";O&&(a={[O]:t})}}this.markAskUserQuestionResolved(n,a);let i=n.toolCall.id,d=(w=n.toolCall)==null?void 0:w.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let E=typeof t=="string"?t:Object.entries(t).map(([M,O])=>`${M}: ${Array.isArray(O)?O.join(", "):O}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let E=a!=null?a:{};l.forEach((M,O)=>{let U=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!U)return;let $=E[U],H=Array.isArray($)?$.join(", "):typeof $=="string"?$:"";this.appendMessage({id:`ask-user-q-${i}-${O}`,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${O}`,role:"user",content:H||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let E=await this.client.resumeFlow(s,{[o]:t});if(!E.ok){let M=await E.json().catch(()=>null);throw new Error((L=M==null?void 0:M.error)!=null?L:`Resume failed: ${E.status}`)}E.body&&await this.connectStream(E.body)}catch(E){(W=(D=this.callbacks).onError)==null||W.call(D,E instanceof Error?E:new Error(String(E)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var i;if(o!==r)return s;let a={...s,...t};return((i=s.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},br=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import{Activity as Cm,ArrowDown as wm,ArrowUp as Am,ArrowUpRight as Sm,Bot as Em,ChevronDown as Tm,ChevronUp as km,ChevronRight as Mm,ChevronLeft as Lm,Check as Pm,Clipboard as Im,ClipboardCopy as Wm,Copy as Rm,File as Hm,FileCode as Bm,FileSpreadsheet as Dm,FileText as Nm,ImagePlus as Fm,Loader as Om,LoaderCircle as $m,Mic as _m,Paperclip as jm,RefreshCw as Um,Search as qm,Send as zm,ShieldAlert as Vm,ShieldCheck as Jm,ShieldX as Km,Square as Gm,ThumbsDown as Qm,ThumbsUp as Xm,Upload as Ym,Volume2 as Zm,X as eg,User as tg,Mail as ng,Phone as rg,Calendar as og,Clock as sg,Building as ag,MapPin as ig,Lock as lg,Key as cg,CreditCard as dg,AtSign as pg,Hash as ug,Globe as mg,Link as gg,CircleCheck as fg,CircleX as hg,TriangleAlert as yg,Info as bg,Ban as xg,Shield as vg,ArrowLeft as Cg,ArrowRight as wg,ExternalLink as Ag,Ellipsis as Sg,EllipsisVertical as Eg,Menu as Tg,House as kg,Plus as Mg,Minus as Lg,Pencil as Pg,Trash as Ig,Trash2 as Wg,Save as Rg,Download as Hg,Share as Bg,Funnel as Dg,Settings as Ng,RotateCw as Fg,Maximize as Og,Minimize as $g,ShoppingCart as _g,ShoppingBag as jg,Package as Ug,Truck as qg,Tag as zg,Gift as Vg,Receipt as Jg,Wallet as Kg,Store as Gg,DollarSign as Qg,Percent as Xg,Play as Yg,Pause as Zg,VolumeX as ef,Camera as tf,Image as nf,Film as rf,Headphones as of,MessageCircle as sf,MessageSquare as af,Bell as lf,Heart as cf,Star as df,Eye as pf,EyeOff as uf,Bookmark as mf,CalendarDays as gf,History as ff,Timer as hf,Folder as yf,FolderOpen as bf,Files as xf,Sparkles as vf,Zap as Cf,Sun as wf,Moon as Af,Flag as Sf,Monitor as Ef,Smartphone as Tf}from"lucide";var kf={activity:Cm,"arrow-down":wm,"arrow-up":Am,"arrow-up-right":Sm,bot:Em,"chevron-down":Tm,"chevron-up":km,"chevron-right":Mm,"chevron-left":Lm,check:Pm,clipboard:Im,"clipboard-copy":Wm,copy:Rm,file:Hm,"file-code":Bm,"file-spreadsheet":Dm,"file-text":Nm,"image-plus":Fm,loader:Om,"loader-circle":$m,mic:_m,paperclip:jm,"refresh-cw":Um,search:qm,send:zm,"shield-alert":Vm,"shield-check":Jm,"shield-x":Km,square:Gm,"thumbs-down":Qm,"thumbs-up":Xm,upload:Ym,"volume-2":Zm,x:eg,user:tg,mail:ng,phone:rg,calendar:og,clock:sg,building:ag,"map-pin":ig,lock:lg,key:cg,"credit-card":dg,"at-sign":pg,hash:ug,globe:mg,link:gg,"circle-check":fg,"circle-x":hg,"triangle-alert":yg,info:bg,ban:xg,shield:vg,"arrow-left":Cg,"arrow-right":wg,"external-link":Ag,ellipsis:Sg,"ellipsis-vertical":Eg,menu:Tg,house:kg,plus:Mg,minus:Lg,pencil:Pg,trash:Ig,"trash-2":Wg,save:Rg,download:Hg,share:Bg,funnel:Dg,settings:Ng,"rotate-cw":Fg,maximize:Og,minimize:$g,"shopping-cart":_g,"shopping-bag":jg,package:Ug,truck:qg,tag:zg,gift:Vg,receipt:Jg,wallet:Kg,store:Gg,"dollar-sign":Qg,percent:Xg,play:Yg,pause:Zg,"volume-x":ef,camera:tf,image:nf,film:rf,headphones:of,"message-circle":sf,"message-square":af,bell:lf,heart:cf,star:df,eye:pf,"eye-off":uf,bookmark:mf,"calendar-days":gf,history:ff,timer:hf,folder:yf,"folder-open":bf,files:xf,sparkles:vf,zap:Cf,sun:wf,moon:Af,flag:Sf,monitor:Ef,smartphone:Tf},ge=(e,n=24,t="currentColor",r=2)=>{let s=kf[e];return s?Mf(s,n,t,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Mf(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),s.appendChild(d)}),s}var wa={allowedTypes:Hr,maxFileSize:10*1024*1024,maxFiles:4};function Lf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Pf(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Uo=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:wa.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:wa.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:wa.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:wa.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let u=lp(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,p);continue}try{let p=await ip(l),f=ba(l)?URL.createObjectURL(l):null,g={id:Lf(),file:l,previewUrl:f,contentPart:p};this.attachments.push(g),this.renderPreview(g)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=ba(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Pf(n.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=cp(n.file.type,n.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=ge("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var dp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ss(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];dp(o)&&dp(s)?t[r]=Ss(o,s):t[r]=s}return t}var Gn="min(440px, calc(100vw - 24px))",mi="440px",Dt={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:Gn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function pp(e,n){if(!(!e&&!n))return e?n?Ss(e,n):e:n}function gi(e){var n,t,r,s,o,a,i,d,l,u,p,f,g,v,x,k,w,L,D,W,E;return e?{...Dt,...e,theme:pp(Dt.theme,e.theme),darkTheme:pp(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(n=Dt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var pe,Te,je,ee,xe,Q,re,Me;let M=(pe=Dt.features)==null?void 0:pe.artifacts,O=(Te=e.features)==null?void 0:Te.artifacts,U=(je=Dt.features)==null?void 0:je.scrollToBottom,$=(ee=e.features)==null?void 0:ee.scrollToBottom,H=(xe=Dt.features)==null?void 0:xe.streamAnimation,F=(Q=e.features)==null?void 0:Q.streamAnimation,K=(re=Dt.features)==null?void 0:re.askUserQuestion,ne=(Me=e.features)==null?void 0:Me.askUserQuestion,Se=M===void 0&&O===void 0?void 0:{...M,...O,layout:{...M==null?void 0:M.layout,...O==null?void 0:O.layout}},We=U===void 0&&$===void 0?void 0:{...U,...$},_e=H===void 0&&F===void 0?void 0:{...H,...F},fe=K===void 0&&ne===void 0?void 0:{...K,...ne,styles:{...K==null?void 0:K.styles,...ne==null?void 0:ne.styles}};return{...Dt.features,...e.features,...We!==void 0?{scrollToBottom:We}:{},...Se!==void 0?{artifacts:Se}:{},..._e!==void 0?{streamAnimation:_e}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Dt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(x=(v=Dt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(w=(k=e.layout)==null?void 0:k.messages)==null?void 0:w.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(W=Dt.markdown)==null?void 0:W.options,...(E=e.markdown)==null?void 0:E.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var up={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},mp={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"}},gp={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:Gn,maxWidth:mi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function qo(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?qo(e,r):r}function fi(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=qo(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function fp(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function hp(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=hp(o,s):t[r]=s}return t}function If(e,n){return n?hp(e,n):e}function Es(e,n={}){var s,o,a,i,d,l,u,p,f,g,v,x,k;let t={palette:up,semantic:mp,components:gp},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:If(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let w=fp(r);if(!w.valid)throw new Error(`Theme validation failed: ${w.errors.map(L=>L.message).join(", ")}`)}if(n.plugins)for(let w of n.plugins)r=w.transform(r);return r}function hi(e){var x,k,w,L,D,W,E,M,O,U,$,H,F,K,ne,Se,We,_e,fe,pe,Te,je,ee,xe,Q,re,Me,ae,Be,Re,J,De,He,G,V,ve,ce,te,me,Qe,Ft,ie,Ne,an,It,qt,vr,dr,P,oe,Pe,qe,Fe,Oe,Ze,vt,Ot,zt,R,se,Ce,pt,Je,Nt,ln,Ct,ht,St,it,Vt,Cr,jn,Dr,xt,pr,ur,wr,Yn,ct,io,mr,lo,En,Mo,Nr,Ar,mt,In,Wn,yn,Et,Un,qn,Rn,Fr,Sr,Or,Hn,kt,bn,zn,$r,Er,_r,gr,Bn,Zn,dt,Jt,Kt,Dn,jr,Vn,er,Nn,_;let n=fi(e),t={};for(let[de,Fn]of Object.entries(n)){let tr=de.replace(/\./g,"-");t[`--persona-${tr}`]=Fn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(k=t["--persona-semantic-colors-secondary"])!=null?k: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"]=(L=t["--persona-semantic-colors-surface"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(D=t["--persona-semantic-colors-background"])!=null?D:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(W=t["--persona-semantic-colors-container"])!=null?W:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(E=t["--persona-semantic-colors-text"])!=null?E:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(M=t["--persona-semantic-colors-text-muted"])!=null?M:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(O=t["--persona-semantic-colors-text-inverse"])!=null?O:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(U=t["--persona-semantic-colors-border"])!=null?U:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=($=t["--persona-semantic-colors-divider"])!=null?$:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(H=t["--persona-components-voice-recording-indicator"])!=null?H:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(F=t["--persona-components-voice-recording-background"])!=null?F:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(K=t["--persona-components-voice-processing-icon"])!=null?K:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Se=t["--persona-components-approval-requested-background"])!=null?Se:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(We=t["--persona-components-approval-requested-border"])!=null?We:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(_e=t["--persona-components-approval-requested-text"])!=null?_e:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(fe=t["--persona-components-approval-approve-background"])!=null?fe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(pe=t["--persona-components-approval-deny-background"])!=null?pe:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Te=t["--persona-components-attachment-image-background"])!=null?Te:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(je=t["--persona-components-attachment-image-border"])!=null?je:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ee=t["--persona-semantic-typography-fontFamily"])!=null?ee:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(xe=t["--persona-semantic-typography-fontSize"])!=null?xe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Q=t["--persona-semantic-typography-fontWeight"])!=null?Q:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(re=t["--persona-semantic-typography-lineHeight"])!=null?re: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"]=(Me=t["--persona-palette-radius-sm"])!=null?Me:"0.125rem",t["--persona-radius-md"]=(ae=t["--persona-palette-radius-md"])!=null?ae:"0.375rem",t["--persona-radius-lg"]=(Be=t["--persona-palette-radius-lg"])!=null?Be:"0.5rem",t["--persona-radius-xl"]=(Re=t["--persona-palette-radius-xl"])!=null?Re:"0.75rem",t["--persona-radius-full"]=(J=t["--persona-palette-radius-full"])!=null?J:"9999px",t["--persona-launcher-radius"]=(He=(De=t["--persona-components-launcher-borderRadius"])!=null?De:t["--persona-palette-radius-full"])!=null?He:"9999px",t["--persona-launcher-bg"]=(G=t["--persona-components-launcher-background"])!=null?G:t["--persona-primary"],t["--persona-launcher-fg"]=(V=t["--persona-components-launcher-foreground"])!=null?V:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ve=t["--persona-components-launcher-border"])!=null?ve: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"]=(te=t["--persona-components-button-primary-foreground"])!=null?te:t["--persona-text-inverse"],t["--persona-button-radius"]=(Qe=(me=t["--persona-components-button-primary-borderRadius"])!=null?me:t["--persona-palette-radius-full"])!=null?Qe:"9999px",t["--persona-panel-radius"]=(ie=(Ft=t["--persona-components-panel-borderRadius"])!=null?Ft:t["--persona-radius-xl"])!=null?ie:"0.75rem",t["--persona-panel-border"]=(Ne=t["--persona-components-panel-border"])!=null?Ne:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(It=(an=t["--persona-components-panel-shadow"])!=null?an:t["--persona-palette-shadows-xl"])!=null?It:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(vr=(qt=t["--persona-components-input-borderRadius"])!=null?qt:t["--persona-radius-lg"])!=null?vr:"0.5rem",t["--persona-message-user-radius"]=(P=(dr=t["--persona-components-message-user-borderRadius"])!=null?dr:t["--persona-radius-lg"])!=null?P:"0.5rem",t["--persona-message-assistant-radius"]=(Pe=(oe=t["--persona-components-message-assistant-borderRadius"])!=null?oe:t["--persona-radius-lg"])!=null?Pe:"0.5rem",t["--persona-header-bg"]=(qe=t["--persona-components-header-background"])!=null?qe:t["--persona-surface"],t["--persona-header-border"]=(Fe=t["--persona-components-header-border"])!=null?Fe:t["--persona-divider"],t["--persona-header-icon-bg"]=(Oe=t["--persona-components-header-iconBackground"])!=null?Oe:t["--persona-primary"],t["--persona-header-icon-fg"]=(Ze=t["--persona-components-header-iconForeground"])!=null?Ze:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(vt=t["--persona-components-header-titleForeground"])!=null?vt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ot=t["--persona-components-header-subtitleForeground"])!=null?Ot:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(zt=t["--persona-components-header-actionIconForeground"])!=null?zt:t["--persona-muted"];let r=(R=e.components)==null?void 0:R.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(se=e.components)==null?void 0:se.introCard;t["--persona-intro-card-bg"]=(Ce=t["--persona-components-introCard-background"])!=null?Ce:t["--persona-surface"],t["--persona-intro-card-radius"]=(pt=t["--persona-components-introCard-borderRadius"])!=null?pt:"1rem",t["--persona-intro-card-padding"]=(Je=t["--persona-components-introCard-padding"])!=null?Je:"1.5rem",t["--persona-intro-card-shadow"]=(ln=(Nt=s==null?void 0:s.shadow)!=null?Nt:t["--persona-components-introCard-shadow"])!=null?ln:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ct=t["--persona-components-input-background"])!=null?Ct:t["--persona-surface"],t["--persona-input-placeholder"]=(ht=t["--persona-components-input-placeholder"])!=null?ht:t["--persona-text-muted"],t["--persona-message-user-bg"]=(St=t["--persona-components-message-user-background"])!=null?St:t["--persona-accent"],t["--persona-message-user-text"]=(it=t["--persona-components-message-user-text"])!=null?it:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Vt=t["--persona-components-message-user-shadow"])!=null?Vt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Cr=t["--persona-components-message-assistant-background"])!=null?Cr:t["--persona-surface"],t["--persona-message-assistant-text"]=(jn=t["--persona-components-message-assistant-text"])!=null?jn:t["--persona-text"],t["--persona-message-assistant-border"]=(Dr=t["--persona-components-message-assistant-border"])!=null?Dr:t["--persona-border"],t["--persona-message-assistant-shadow"]=(xt=t["--persona-components-message-assistant-shadow"])!=null?xt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(pr=t["--persona-components-scrollToBottom-background"])!=null?pr:t["--persona-button-primary-bg"])!=null?ur:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Yn=(wr=t["--persona-components-scrollToBottom-foreground"])!=null?wr:t["--persona-button-primary-fg"])!=null?Yn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(ct=t["--persona-components-scrollToBottom-border"])!=null?ct:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(io=t["--persona-components-scrollToBottom-size"])!=null?io:"40px",t["--persona-scroll-to-bottom-radius"]=(En=(lo=(mr=t["--persona-components-scrollToBottom-borderRadius"])!=null?mr:t["--persona-button-radius"])!=null?lo:t["--persona-radius-full"])!=null?En:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Nr=(Mo=t["--persona-components-scrollToBottom-shadow"])!=null?Mo:t["--persona-palette-shadows-sm"])!=null?Nr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Ar=t["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(mt=t["--persona-components-scrollToBottom-gap"])!=null?mt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Wn=(In=t["--persona-components-scrollToBottom-fontSize"])!=null?In:t["--persona-palette-typography-fontSize-sm"])!=null?Wn:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(yn=t["--persona-components-scrollToBottom-iconSize"])!=null?yn:"14px",t["--persona-tool-bubble-shadow"]=(Et=t["--persona-components-toolBubble-shadow"])!=null?Et:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Un=t["--persona-components-reasoningBubble-shadow"])!=null?Un:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(qn=t["--persona-components-composer-shadow"])!=null?qn:"none",t["--persona-md-inline-code-bg"]=(Rn=t["--persona-components-markdown-inlineCode-background"])!=null?Rn:t["--persona-container"],t["--persona-md-inline-code-color"]=(Fr=t["--persona-components-markdown-inlineCode-foreground"])!=null?Fr:t["--persona-text"],t["--persona-md-link-color"]=(Or=(Sr=t["--persona-components-markdown-link-foreground"])!=null?Sr:t["--persona-accent"])!=null?Or:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Hn=t["--persona-components-markdown-codeBlock-background"])!=null?Hn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(kt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?kt:t["--persona-border"],t["--persona-md-code-block-text-color"]=(bn=t["--persona-components-markdown-codeBlock-textColor"])!=null?bn:"inherit",t["--persona-md-table-header-bg"]=(zn=t["--persona-components-markdown-table-headerBackground"])!=null?zn:t["--persona-container"],t["--persona-md-table-border-color"]=($r=t["--persona-components-markdown-table-borderColor"])!=null?$r:t["--persona-border"],t["--persona-md-hr-color"]=(Er=t["--persona-components-markdown-hr-color"])!=null?Er:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(_r=t["--persona-components-markdown-blockquote-borderColor"])!=null?_r:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(gr=t["--persona-components-markdown-blockquote-background"])!=null?gr:"transparent",t["--persona-md-blockquote-text-color"]=(Bn=t["--persona-components-markdown-blockquote-textColor"])!=null?Bn:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Zn=t["--persona-components-collapsibleWidget-container"])!=null?Zn:t["--persona-surface"],t["--cw-surface"]=(dt=t["--persona-components-collapsibleWidget-surface"])!=null?dt:t["--persona-surface"],t["--cw-border"]=(Jt=t["--persona-components-collapsibleWidget-border"])!=null?Jt:t["--persona-border"],t["--persona-message-border"]=(Kt=t["--persona-components-message-border"])!=null?Kt:t["--persona-border"];let u=e.components,p=u==null?void 0:u.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 f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let g=u==null?void 0:u.toggleGroup;g&&(g.gap&&(t["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(t["--persona-toggle-group-radius"]=g.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let de=v.toolbar;de.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=de.iconHoverColor),de.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=de.iconHoverBackground),de.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=de.iconPadding),de.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=de.iconBorderRadius),de.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=de.iconBorder),de.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=de.toggleGroupGap),de.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=de.toggleBorderRadius),de.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=de.copyBackground),de.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=de.copyBorder),de.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=de.copyColor),de.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=de.copyBorderRadius),de.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=de.copyPadding),de.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=de.copyMenuBackground,t["--persona-dropdown-bg"]=(Dn=t["--persona-dropdown-bg"])!=null?Dn:de.copyMenuBackground),de.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=de.copyMenuBorder,t["--persona-dropdown-border"]=(jr=t["--persona-dropdown-border"])!=null?jr:de.copyMenuBorder),de.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=de.copyMenuShadow,t["--persona-dropdown-shadow"]=(Vn=t["--persona-dropdown-shadow"])!=null?Vn:de.copyMenuShadow),de.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=de.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(er=t["--persona-dropdown-radius"])!=null?er:de.copyMenuBorderRadius),de.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=de.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Nn=t["--persona-dropdown-item-hover-bg"])!=null?Nn:de.copyMenuItemHoverBackground),de.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=de.iconBackground),de.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=de.toolbarBorder)}if(v!=null&&v.tab){let de=v.tab;de.background&&(t["--persona-artifact-tab-bg"]=de.background),de.activeBackground&&(t["--persona-artifact-tab-active-bg"]=de.activeBackground),de.activeBorder&&(t["--persona-artifact-tab-active-border"]=de.activeBorder),de.borderRadius&&(t["--persona-artifact-tab-radius"]=de.borderRadius),de.textColor&&(t["--persona-artifact-tab-color"]=de.textColor),de.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=de.hoverBackground),de.listBackground&&(t["--persona-artifact-tab-list-bg"]=de.listBackground),de.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=de.listBorderColor),de.listPadding&&(t["--persona-artifact-tab-list-padding"]=de.listPadding)}if(v!=null&&v.pane){let de=v.pane;if(de.toolbarBackground){let Fn=(_=qo(e,de.toolbarBackground))!=null?_:de.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Fn}}return t}var Wf={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 Rf={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"}}},yp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Aa=()=>{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"},Hf=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Aa()},bp=e=>Hf(e),Bf=e=>Es(e),Df=e=>{var t;let n=Es(void 0,{validate:!1});return Es({...e,palette:{...n.palette,colors:{...Rf.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Ts=e=>{let n=bp(e),t=yp(e==null?void 0:e.theme),r=yp(e==null?void 0:e.darkTheme);return n==="dark"?Df(Ss(t!=null?t:{},r!=null?r:{})):Bf(t)},Nf=e=>hi(e),So=(e,n)=>{var o;let t=Ts(n),r=Nf(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},yi=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Aa())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Aa());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as Ff}from"idiomorph";var Sa=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Ff.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function xp(e,n){var t,r,s,o,a,i,d,l,u,p,f,g,v,x,k,w,L,D,W,E,M,O,U,$,H,F,K,ne,Se,We;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(k=(x=e.toolCall)==null?void 0:x.name)!=null?k:"",(D=(L=(w=e.toolCall)==null?void 0:w.chunks)==null?void 0:L.length)!=null?D:0,(O=(M=(E=(W=e.toolCall)==null?void 0:W.chunks)==null?void 0:E[e.toolCall.chunks.length-1])==null?void 0:M.slice(-32))!=null?O:"",typeof((U=e.toolCall)==null?void 0:U.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(K=(F=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:F.length)!=null?K:0,(Se=(ne=e.contentParts)==null?void 0:ne.length)!=null?Se:0,(We=e.stopReason)!=null?We:"",n].join("\0")}function vp(){return new Map}function Cp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function wp(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Ap(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Ea(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function ks(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ms(e,n){return ks(e)-e.scrollTop<=n}function Ta(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:t}:!n&&s&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function ka(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,Xr=hn+1;var Ls={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Of=["pre","code","a","script","style"],Ma=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Ls.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:Ls.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ls.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ls.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ls.buffer}},Ep=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Ps=new Map;for(let e of Ep)Ps.set(e.name,e);var $f=e=>{Ps.set(e.name,e)},_f=e=>{Ep.some(n=>n.name===e)||Ps.delete(e)},jf=()=>Array.from(Ps.keys()),Is=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Ps.get(e))!=null?r:null},La=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
|
|
8
|
+
`);return o<0?"":e.slice(0,o)}return e},Uf=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},qf=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${t}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=n,s},bi=/\s/,zf=(e,n)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(n.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Vf=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(bi.test(o[i])){let l=i;for(;l<o.length&&bi.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<o.length&&!bi.test(o[u]);)l.appendChild(Uf(r,o[u],n,t.value)),t.value+=1,u+=1;a.appendChild(l),i=u}s.replaceChild(a,e)},Jf=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(qf(r,l,n,t.value)),t.value+=1));s.replaceChild(a,e)},Ws=(e,n,t,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((p=r==null?void 0:r.skipTags)!=null?p:Of).map(g=>g.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)zf(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=n==="char"?Vf:Jf;for(let g of i)u(g,t,l);return s.innerHTML},Pa=(e=document)=>{let n=e.createElement("span");return n.className="persona-stream-caret",n.setAttribute("aria-hidden","true"),n.setAttribute("data-preserve-animation","stream-caret"),n},Rs=(e=document)=>{let n=e.createElement("div");n.className="persona-stream-skeleton",n.setAttribute("data-preserve-animation","stream-skeleton"),n.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",n.appendChild(t),n},Sp=new WeakMap,Kf=(e,n)=>{var o;if(!e.styles)return;let t=Sp.get(n);if(t||(t=new Set,Sp.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let s=(n instanceof ShadowRoot?n.ownerDocument:(o=n.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,n.appendChild(s)},xi=new WeakMap,Gf=(e,n)=>{if(!e.onAttach)return;let t=xi.get(n);if(t||(t=new Map,xi.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},Tp=e=>{let n=xi.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},vi=(e,n)=>{Kf(e,n),Gf(e,n)};function Ci(e,n=hn){let t=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=s}}var Hs=0,Yr=null;function wi(e=document){var t;if(Hs++,Hs===1){let r=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Yr={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,Hs=Math.max(0,Hs-1),Hs===0&&Yr)){let s=e.body,o=(r=e.defaultView)!=null?r: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 Ia={side:"right",width:"420px",animate:!0,reveal:"resize"},on=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},Zr=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="composer-bar"},lr=e=>{var t,r,s,o,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:Ia.side,width:(s=n==null?void 0:n.width)!=null?s:Ia.width,animate:(o=n==null?void 0:n.animate)!=null?o:Ia.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:Ia.reveal}};var cr={"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 Bs=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
9
9
|
<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>
|
|
10
10
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
11
11
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -13,14 +13,14 @@ import{Marked as Ku}from"marked";var Gu=e=>{if(e)return e},ca=e=>{var s,o;let n=
|
|
|
13
13
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
14
14
|
</span>
|
|
15
15
|
<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>
|
|
16
|
-
`,t.addEventListener("click",n);let r=o=>{var D,W,E,M,O,j,$,H,F,K,ne,Se,We,_e;let a=(D=o.launcher)!=null?D:{},i=on(o),d=t.querySelector("[data-role='launcher-title']");if(d){let fe=(W=a.title)!=null?W:"Chat Assistant";d.textContent=fe,d.setAttribute("title",fe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let fe=(E=a.subtitle)!=null?E:"Get answers fast";l.textContent=fe,l.setAttribute("title",fe)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let fe=(M=a.agentIconSize)!=null?M:"40px";if(p.style.height=fe,p.style.width=fe,p.innerHTML="",a.agentIconName){let pe=parseFloat(fe)||24,Te=ge(a.agentIconName,pe*.6,"var(--persona-text-inverse, #ffffff)",2);Te?(p.appendChild(Te),p.style.display=""):(p.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(j=a.agentIconText)!=null?j:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let fe=($=a.agentIconSize)!=null?$:"40px";f.style.height=fe,f.style.width=fe,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 fe=(H=a.callToActionIconSize)!=null?H:"32px";g.style.height=fe,g.style.width=fe,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 pe=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,pe=(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 Te=parseFloat(fe)||24,Ue=Math.max(Te-pe,8),ee=ge(a.callToActionIconName,Ue,"currentColor",2);ee?g.appendChild(ee):g.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else g.textContent=(K=a.callToActionIconText)!=null?K:"\u2197"}let v=a.position&&cr[a.position]?cr[a.position]:cr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="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?k:`${x} ${v}`,i||(t.style.zIndex=String((ne=a.zIndex)!=null?ne:hn));let C="1px solid var(--persona-border, #e5e7eb)",L="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=(Se=a.border)!=null?Se:C,t.style.boxShadow=(We=a.shadow)!=null?We:L,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",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Gf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Wa=(e,n={})=>{var x,k,C,L,D,W;let{showClose:t=!0,wrapperClassName:r=Gf,buttonSize:s,iconSize:o="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(k=s!=null?s:a.closeButtonSize)!=null?k:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(C=a.closeButtonTooltipText)!=null?C:"Close chat",p=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(D=a.closeButtonIconName)!=null?D:"x",g=(W=a.closeButtonIconText)!=null?W:"\xD7";l.style.color=a.closeButtonColor||Sn.actionIconColor;let v=ge(f,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=g,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let E=a.closeButtonBorderWidth||"0px",M=a.closeButtonBorderColor||"transparent";l.style.border=`${E} solid ${M}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let E=null,M=()=>{if(E)return;let j=l.ownerDocument,$=j.body;if(!$)return;E=br(j,"div","persona-clear-chat-tooltip"),E.textContent=u;let H=br(j,"div");H.className="persona-clear-chat-tooltip-arrow",E.appendChild(H);let F=l.getBoundingClientRect();E.style.position="fixed",E.style.zIndex=String(Xr),E.style.left=`${F.left+F.width/2}px`,E.style.top=`${F.top-8}px`,E.style.transform="translate(-50%, -100%)",$.appendChild(E)},O=()=>{E&&E.parentNode&&(E.parentNode.removeChild(E),E=null)};d.addEventListener("mouseenter",M),d.addEventListener("mouseleave",O),l.addEventListener("focus",M),l.addEventListener("blur",O),d._cleanupTooltip=()=>{O(),d.removeEventListener("mouseenter",M),d.removeEventListener("mouseleave",O),l.removeEventListener("focus",M),l.removeEventListener("blur",O)}}return{button:l,wrapper:d}},Qf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ra=(e,n={})=>{var E,M,O,j,$,H,F,K,ne,Se,We,_e,fe;let{wrapperClassName:t=Qf,buttonSize:r,iconSize:s="20px"}=n,a=(M=((E=e==null?void 0:e.launcher)!=null?E:{}).clearChat)!=null?M:{},i=(O=r!=null?r:a.size)!=null?O:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",l=($=a.iconColor)!=null?$:"",u=(H=a.backgroundColor)!=null?H:"",p=(F=a.borderWidth)!=null?F:"",f=(K=a.borderColor)!=null?K:"",g=(ne=a.borderRadius)!=null?ne:"",v=(Se=a.paddingX)!=null?Se:"",x=(We=a.paddingY)!=null?We:"",k=(_e=a.tooltipText)!=null?_e:"Clear chat",C=(fe=a.showTooltip)!=null?fe:!0,L=h("div",t),D=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");D.style.height=i,D.style.width=i,D.type="button",D.setAttribute("aria-label",k),D.style.color=l||Sn.actionIconColor;let W=ge(d,s,"currentColor",1);if(W&&(W.style.display="block",D.appendChild(W)),u&&(D.style.backgroundColor=u,D.classList.remove("hover:persona-bg-gray-100")),p||f){let pe=p||"0px",Te=f||"transparent";D.style.border=`${pe} solid ${Te}`,D.classList.remove("persona-border-none")}if(g&&(D.style.borderRadius=g,D.classList.remove("persona-rounded-full")),v&&(D.style.paddingLeft=v,D.style.paddingRight=v),x&&(D.style.paddingTop=x,D.style.paddingBottom=x),L.appendChild(D),C&&k){let pe=null,Te=()=>{if(pe)return;let ee=D.ownerDocument,xe=ee.body;if(!xe)return;pe=br(ee,"div","persona-clear-chat-tooltip"),pe.textContent=k;let Q=br(ee,"div");Q.className="persona-clear-chat-tooltip-arrow",pe.appendChild(Q);let re=D.getBoundingClientRect();pe.style.position="fixed",pe.style.zIndex=String(Xr),pe.style.left=`${re.left+re.width/2}px`,pe.style.top=`${re.top-8}px`,pe.style.transform="translate(-50%, -100%)",xe.appendChild(pe)},Ue=()=>{pe&&pe.parentNode&&(pe.parentNode.removeChild(pe),pe=null)};L.addEventListener("mouseenter",Te),L.addEventListener("mouseleave",Ue),D.addEventListener("focus",Te),D.addEventListener("blur",Ue),L._cleanupTooltip=()=>{Ue(),L.removeEventListener("mouseenter",Te),L.removeEventListener("mouseleave",Ue),D.removeEventListener("focus",Te),D.removeEventListener("blur",Ue)}}return{button:D,wrapper:L}};var Sn={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))"},eo=e=>{var E,M,O,j,$,H,F,K,ne,Se,We,_e,fe,pe,Te,Ue;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(E=n==null?void 0:n.launcher)!=null?E:{},o=(M=s.headerIconSize)!=null?M:"48px",a=(O=s.closeButtonPlacement)!=null?O:"inline",i=(j=s.headerIconHidden)!=null?j:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(o)||24,xe=ge(d,ee*.6,"currentColor",1);xe?l.replaceChildren(xe):l.textContent=(H=($=n==null?void 0:n.launcher)==null?void 0:$.agentIconText)!=null?H:"\u{1F4AC}"}else if((F=n==null?void 0:n.launcher)!=null&&F.iconUrl){let ee=h("img");ee.src=n.launcher.iconUrl,ee.alt="",ee.className="persona-rounded-xl persona-object-cover",ee.style.height=o,ee.style.width=o,l.replaceChildren(ee)}else l.textContent=(ne=(K=n==null?void 0:n.launcher)==null?void 0:K.agentIconText)!=null?ne:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=Sn.titleColor,p.textContent=(We=(Se=n==null?void 0:n.launcher)==null?void 0:Se.title)!=null?We:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Sn.subtitleColor,f.textContent=(fe=(_e=n==null?void 0:n.launcher)==null?void 0:_e.subtitle)!=null?fe:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let g=(pe=s.clearChat)!=null?pe:{},v=(Te=g.enabled)!=null?Te:!0,x=(Ue=g.placement)!=null?Ue:"inline",k=null,C=null;if(v){let xe=Ra(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=xe.button,C=xe.wrapper,x==="top-right"&&(C.style.right="48px"),x==="inline"&&r.appendChild(C)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:D,wrapper:W}=Wa(n,{showClose:t,wrapperClassName:L});return a!=="top-right"&&r.appendChild(W),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:D,closeButtonWrapper:W,clearChatButton:k,clearChatButtonWrapper:C}},zo=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Eo(e){let{items:n,onSelect:t,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Xr)):(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 n){if(g.dividerBefore){let k=document.createElement("hr");a.appendChild(k)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let k=ge(g.icon,16,"currentColor",1.5);k&&v.appendChild(k)}let x=document.createElement("span");x.textContent=g.label,v.appendChild(x),v.addEventListener("click",k=>{k.stopPropagation(),u(),t(g.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let g=r.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 l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function _t(e){let{icon:n,label:t,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=ge(n,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Ha(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=ge(n,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))u.setAttribute(f,g);return u}function Ba(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=_t({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function l(u){a=u,d()}return{element:o,setSelected:l}}function Ai(e){var g,v;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",n);let u=h("span","persona-combo-btn-label");u.textContent=n,l.appendChild(u);let p=ge(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,k;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(k=d.border)!=null?k:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Eo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let k=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",k?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var kp=e=>{var r;let n=eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function Xf(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=ge(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=Eo({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Mp=e=>{var L,D,W,E,M,O,j,$,H;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(L=n==null?void 0:n.launcher)!=null?L:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,u;if(d)l=Ai({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Sn.titleColor,u=(W=l.querySelector(".persona-combo-btn-label"))!=null?W:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Sn.titleColor,u.textContent=(E=a.title)!=null?E:"Chat Assistant",l.appendChild(u),Xf(l,s==null?void 0:s.trailingActions,(M=s==null?void 0:s.onAction)!=null?M:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let K=s.onTitleClick;l.addEventListener("click",ne=>{ne.target.closest("button")||K()}),l.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),K())})}let F=s==null?void 0:s.titleRowHover;F&&(l.style.borderRadius=(O=F.borderRadius)!=null?O:"10px",l.style.padding=(j=F.padding)!=null?j:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var K,ne;l.style.backgroundColor=(K=F.background)!=null?K:"",l.style.borderColor=(ne=F.border)!=null?ne:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=($=a.closeButtonSize)!=null?$:"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=p,g.style.width=p,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||Sn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=ge(v,"28px","currentColor",1);x?g.appendChild(x):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let k=h("div");k.style.display="none";let C=h("span");return C.style.display="none",{header:i,iconHolder:k,headerTitle:u,headerSubtitle:C,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Si={default:kp,minimal:Mp},Lp=e=>{var n;return(n=Si[e])!=null?n:Si.default},Ds=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),g=h("button");g.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=Lp(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Da=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},Na=e=>{var E,M,O,j,$,H,F,K,ne,Se,We,_e;let n=(E=e==null?void 0:e.sendButton)!=null?E:{},t=(M=n.useIcon)!=null?M:!1,r=(O=n.iconText)!=null?O:"\u2191",s=n.iconName,o=(j=n.stopIconName)!=null?j:"square",a=($=n.tooltipText)!=null?$:"Send message",i=(H=n.stopTooltipText)!=null?H:"Stop generating",d=(K=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?K:"Send",l=(Se=(ne=e==null?void 0:e.copy)==null?void 0:ne.stopButtonLabel)!=null?Se:"Stop",u=(We=n.showTooltip)!=null?We:!1,p=(_e=n.size)!=null?_e:"40px",f=n.backgroundColor,g=n.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",t?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let k=null,C=null;if(t){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",g?x.style.color=g:x.style.color="var(--persona-button-primary-fg, #ffffff)";let fe=parseFloat(p)||24,pe=(g==null?void 0:g.trim())||"currentColor";s?(k=ge(s,fe,pe,2),k?x.appendChild(k):x.textContent=r):x.textContent=r,C=ge(o,fe,pe,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,g?x.style.color=g:x.classList.add("persona-text-white");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let L=null;u&&a&&(L=h("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let D="send";return{button:x,wrapper:v,setMode:fe=>{if(fe===D)return;D=fe;let pe=fe==="stop"?i:a;if(x.setAttribute("aria-label",pe),L&&(L.textContent=pe),t){if(k&&C){let Te=fe==="stop"?C:k,Ue=fe==="stop"?k:C;Ue.parentNode===x?x.replaceChild(Te,Ue):x.appendChild(Te)}}else x.textContent=fe==="stop"?l:d}}},Fa=e=>{var L,D,W,E,M,O,j,$,H,F,K,ne;let n=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((D=n.provider)==null?void 0:D.type)==="runtype";if(!(r||s))return null;let a=(E=(W=e==null?void 0:e.sendButton)==null?void 0:W.size)!=null?E:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(M=n.iconName)!=null?M:"mic",u=(O=n.iconSize)!=null?O:a,p=parseFloat(u)||24,f=($=n.backgroundColor)!=null?$:(j=e==null?void 0:e.sendButton)==null?void 0:j.backgroundColor,g=(F=n.iconColor)!=null?F:(H=e==null?void 0:e.sendButton)==null?void 0:H.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",g?d.style.color=g:d.style.color="var(--persona-text, #111827)";let x=ge(l,p,g||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let k=(K=n.tooltipText)!=null?K:"Start voice recognition";if(((ne=n.showTooltip)!=null?ne:!1)&&k){let Se=h("div","persona-send-button-tooltip");Se.textContent=k,i.appendChild(Se)}return{button:d,wrapper:i}},Oa=e=>{var v,x,k,C,L,D,W,E;let n=(v=e==null?void 0:e.attachments)!=null?v:{};if(n.enabled!==!0)return null;let t=(k=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?k:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((C=n.allowedTypes)!=null?C:Hr).join(","),s.multiple=((L=n.maxFiles)!=null?L:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(D=n.buttonTooltipText)!=null?D:"Attach file");let i=(W=n.buttonIconName)!=null?W:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=ge(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",M=>{M.preventDefault(),s.click()}),o.appendChild(a);let f=(E=n.buttonTooltipText)!=null?E:"Attach file",g=h("div","persona-send-button-tooltip");return g.textContent=f,o.appendChild(g),{button:a,wrapper:o,input:s,previewsContainer:r}},$a=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},_a=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ns=e=>{var v,x,k,C,L,D;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=_a(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Da(n);a();let i=Na(n),d=Fa(n),l=Oa(n),u=$a(n);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),p.append(f,g),s.append(p),s.addEventListener("click",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(l==null?void 0:l.button)&&W.target!==(l==null?void 0:l.wrapper)&&o.focus()}),t.append(r,s,u),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:u,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(C=l==null?void 0:l.wrapper)!=null?C:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:p,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Pp=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let n=h("span","persona-pill-peek__icon"),t=ge("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=ge("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},Ip=e=>{var v,x,k,C,L,D;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=_a();r.style.display="none";let s=$a(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=Da(n);o.style.maxHeight="100px",a();let i=Na(n),d=Fa(n),l=Oa(n);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(l==null?void 0:l.button)&&W.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&u.append(l.input),u.append(p,o,f),l&&t.append(l.previewsContainer),t.append(u,r,s);let g=u;return{footer:t,suggestions:r,composerForm:u,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(C=l==null?void 0:l.wrapper)!=null?C:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Wp=e=>{var u,p,f,g,v,x,k,C,L,D,W,E,M,O,j,$,H;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=on(e);if(Zr(e)){let F=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},K=h("div","persona-widget-wrapper persona-fixed persona-transition");K.setAttribute("data-persona-composer-bar",""),K.dataset.state="collapsed",K.dataset.expandedSize=(v=F.expandedSize)!=null?v:"anchored",K.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:hn);let ne=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",K.appendChild(ne);let Se=h("div","persona-widget-pill-root");return Se.setAttribute("data-persona-composer-bar",""),Se.dataset.state="collapsed",Se.dataset.expandedSize=(C=F.expandedSize)!=null?C:"anchored",Se.style.zIndex=String((D=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?D:hn),{wrapper:K,panel:ne,pillRoot:Se}}if(t){let F=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),K=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild(K),{wrapper:F,panel:K}}if(!n){let F=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),K=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(E=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?E:"100%";return F.style.width=ne,K.style.width="100%",F.appendChild(K),{wrapper:F,panel:K}}let s=(M=e==null?void 0:e.launcher)!=null?M:{},o=s.position&&cr[s.position]?cr[s.position]:cr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((j=(O=e==null?void 0:e.launcher)==null?void 0:O.zIndex)!=null?j:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?H:e==null?void 0:e.launcherWidth,l=d!=null?d:Gn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Yf=(e,n)=>{var W,E,M,O,j,$,H,F,K;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Wa(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(M=(E=(W=e==null?void 0:e.launcher)==null?void 0:W.clearChat)==null?void 0:E.enabled)!=null?M:!0,a=null,i=null;if(o){let ne=Ra(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(j=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeTitle)!=null?j:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(H=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",u.append(p,f);let g=h("div","persona-flex persona-flex-col persona-gap-3"),v=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;v&&(g.style.maxWidth=v,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((K=e==null?void 0:e.copy)==null?void 0:K.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);let k=h("div","persona-composer-overlay persona-pointer-events-none");k.setAttribute("data-persona-composer-overlay",""),k.style.position="absolute",k.style.left="0",k.style.right="0",k.style.bottom="0",k.style.zIndex="20";let C=Ip({config:e}),{root:L,textNode:D}=Pp();return t.append(d,s,l,k),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:g,composerOverlay:k,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode,peekBanner:L,peekTextNode:D}},Rp=(e,n=!0)=>{var k,C,L,D,W,E,M,O,j;if(Zr(e))return Yf(e,n);let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let r=(k=e==null?void 0:e.layout)==null?void 0:k.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=r?Ds(e,r,{showClose:n}):eo({config:e,showClose:n}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(D=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?D:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(E=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?E:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(M=e==null?void 0:e.layout)==null?void 0:M.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=Ns({config:e}),v=((j=e==null?void 0:e.layout)==null?void 0:j.showFooter)!==!1;s?zo(t,o,e):(o.header.style.display="none",zo(t,o,e)),t.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(g.footer.style.display="none"),t.append(g.footer),t.append(x),{container:t,body:a,messagesWrapper:u,composerOverlay:x,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var Zf=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},eh=(e,n)=>{if(!e)return null;let t=Zf(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},th=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},nh=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},rh=320,oh=320,sh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),ah=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${rh}px`,l.style.maxHeight=`${oh}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,l.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{u=!0}),nh(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},Vo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},Bp=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Vo};if(n){let s=n(r);if(s!==null)return s}return Vo()},ih=(e,n)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Hp=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},lh=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Dp=(e,n,t)=>{var g,v,x,k,C,L;let r=(g=n.showCopy)!=null?g:!0,s=(v=n.showUpvote)!=null?v:!0,o=(x=n.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let D=h("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let a=(k=n.visibility)!=null?k:"hover",i=(C=n.align)!=null?C:"right",d=(L=n.layout)!=null?L:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(D,W,E)=>{let M=_t({icon:D,label:W,size:14,className:"persona-message-action-btn"});return M.setAttribute("data-action",E),M};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Fs=(e,n,t,r,s,o)=>{var pe,Te,Ue,ee,xe,Q,re,Me,ae,Be,Re,J,De,He,G,V,ve;let a=t!=null?t:{},i=(pe=a.layout)!=null?pe:"bubble",d=a.avatar,l=a.timestamp,u=(Te=d==null?void 0:d.show)!=null?Te:!1,p=(Ue=l==null?void 0:l.show)!=null?Ue:!1,f=(ee=d==null?void 0:d.position)!=null?ee:"left",g=(xe=l==null?void 0:l.position)!=null?xe:"below",v=lh(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=sh(e),C=(re=(Q=e.content)==null?void 0:Q.trim())!=null?re:"",D=k.length>0&&C===ha,W=Ma((ae=(Me=o==null?void 0:o.widgetConfig)==null?void 0:Me.features)==null?void 0:ae.streamAnimation),E=(J=(Re=(Be=o==null?void 0:o.widgetConfig)==null?void 0:Be.features)==null?void 0:Re.streamAnimation)==null?void 0:J.plugins,M=e.role==="assistant"&&W.type!=="none"?Is(W.type,E):null,O=e.role==="assistant"&&((De=M==null?void 0:M.isAnimating)==null?void 0:De.call(M,e))===!0,j=e.role==="assistant"&&M!==null&&(!!e.streaming||O);j&&(M!=null&&M.bubbleClass)&&x.classList.add(M.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),j&&M&&(M.containerClass&&$.classList.add(M.containerClass),$.style.setProperty("--persona-stream-step",`${W.speed}ms`),$.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let H=j?La((He=e.content)!=null?He:"",W.buffer,M,e,!!e.streaming):(G=e.content)!=null?G:"",F=n({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),K=F;j&&(M==null?void 0:M.wrap)==="char"?K=Ws(F,"char",e.id,{skipTags:M.skipTags}):j&&(M==null?void 0:M.wrap)==="word"&&(K=Ws(F,"word",e.id,{skipTags:M.skipTags}));let ne=null;if(D?(ne=document.createElement("div"),ne.innerHTML=K,ne.style.display="none",$.appendChild(ne)):$.innerHTML=K,j&&(M!=null&&M.useCaret)&&!D&&C){let ce=Pa(),te=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),me=te[te.length-1];if(me!=null&&me.parentNode)me.parentNode.insertBefore(ce,me.nextSibling);else{let Qe=$.lastElementChild;Qe?Qe.appendChild(ce):$.appendChild(ce)}}if(p&&g==="inline"&&e.createdAt){let ce=Hp(e,l);ce.classList.add("persona-ml-2","persona-inline"),$.appendChild(ce)}if(k.length>0){let ce=ah(k,!D&&!!C,()=>{D&&ne&&(ne.style.display="")});ce?x.appendChild(ce):D&&ne&&(ne.style.display="")}if(x.appendChild($),p&&g==="below"&&e.createdAt){let ce=Hp(e,l);ce.classList.add("persona-mt-1"),x.appendChild(ce)}let Se=e.role==="assistant"?eh(e.stopReason,(ve=(V=o==null?void 0:o.widgetConfig)==null?void 0:V.copy)==null?void 0:ve.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ce=!!(H&&H.trim()),te=W.placeholder==="skeleton",me=te&&W.buffer==="line"&&ce;if(ce)me&&x.appendChild(Rs());else if(te)x.appendChild(Rs());else{let Qe=Bp("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Qe&&x.appendChild(Qe)}}if(Se&&e.stopReason&&!e.streaming&&(C||($.style.display="none"),x.appendChild(th(e.stopReason,Se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let ce=Dp(e,r,s);x.appendChild(ce)}if(!u||e.role==="system")return x;let _e=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),fe=ih(d,e.role);return f==="right"||f==="left"&&e.role==="user"?_e.append(x,fe):_e.append(fe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),_e},ch=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Fs(e,n,t,r,s,o)};var Jo=new Set,dh=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),ph=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
|
|
17
|
-
`):""},Np=(e,n)=>{let t=Jo.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Ei=(e,n)=>{var We,_e,fe,pe,Te,
|
|
16
|
+
`,t.addEventListener("click",n);let r=o=>{var D,W,E,M,O,U,$,H,F,K,ne,Se,We,_e;let a=(D=o.launcher)!=null?D:{},i=on(o),d=t.querySelector("[data-role='launcher-title']");if(d){let fe=(W=a.title)!=null?W:"Chat Assistant";d.textContent=fe,d.setAttribute("title",fe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let fe=(E=a.subtitle)!=null?E:"Get answers fast";l.textContent=fe,l.setAttribute("title",fe)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let fe=(M=a.agentIconSize)!=null?M:"40px";if(p.style.height=fe,p.style.width=fe,p.innerHTML="",a.agentIconName){let pe=parseFloat(fe)||24,Te=ge(a.agentIconName,pe*.6,"var(--persona-text-inverse, #ffffff)",2);Te?(p.appendChild(Te),p.style.display=""):(p.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(U=a.agentIconText)!=null?U:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let fe=($=a.agentIconSize)!=null?$:"40px";f.style.height=fe,f.style.width=fe,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 fe=(H=a.callToActionIconSize)!=null?H:"32px";g.style.height=fe,g.style.width=fe,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 pe=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,pe=(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 Te=parseFloat(fe)||24,je=Math.max(Te-pe,8),ee=ge(a.callToActionIconName,je,"currentColor",2);ee?g.appendChild(ee):g.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else g.textContent=(K=a.callToActionIconText)!=null?K:"\u2197"}let v=a.position&&cr[a.position]?cr[a.position]:cr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="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?k:`${x} ${v}`,i||(t.style.zIndex=String((ne=a.zIndex)!=null?ne:hn));let w="1px solid var(--persona-border, #e5e7eb)",L="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=(Se=a.border)!=null?Se:w,t.style.boxShadow=(We=a.shadow)!=null?We:L,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",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Qf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Wa=(e,n={})=>{var x,k,w,L,D,W;let{showClose:t=!0,wrapperClassName:r=Qf,buttonSize:s,iconSize:o="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(k=s!=null?s:a.closeButtonSize)!=null?k:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(w=a.closeButtonTooltipText)!=null?w:"Close chat",p=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(D=a.closeButtonIconName)!=null?D:"x",g=(W=a.closeButtonIconText)!=null?W:"\xD7";l.style.color=a.closeButtonColor||Sn.actionIconColor;let v=ge(f,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=g,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let E=a.closeButtonBorderWidth||"0px",M=a.closeButtonBorderColor||"transparent";l.style.border=`${E} solid ${M}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let E=null,M=()=>{if(E)return;let U=l.ownerDocument,$=U.body;if(!$)return;E=br(U,"div","persona-clear-chat-tooltip"),E.textContent=u;let H=br(U,"div");H.className="persona-clear-chat-tooltip-arrow",E.appendChild(H);let F=l.getBoundingClientRect();E.style.position="fixed",E.style.zIndex=String(Xr),E.style.left=`${F.left+F.width/2}px`,E.style.top=`${F.top-8}px`,E.style.transform="translate(-50%, -100%)",$.appendChild(E)},O=()=>{E&&E.parentNode&&(E.parentNode.removeChild(E),E=null)};d.addEventListener("mouseenter",M),d.addEventListener("mouseleave",O),l.addEventListener("focus",M),l.addEventListener("blur",O),d._cleanupTooltip=()=>{O(),d.removeEventListener("mouseenter",M),d.removeEventListener("mouseleave",O),l.removeEventListener("focus",M),l.removeEventListener("blur",O)}}return{button:l,wrapper:d}},Xf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ra=(e,n={})=>{var E,M,O,U,$,H,F,K,ne,Se,We,_e,fe;let{wrapperClassName:t=Xf,buttonSize:r,iconSize:s="20px"}=n,a=(M=((E=e==null?void 0:e.launcher)!=null?E:{}).clearChat)!=null?M:{},i=(O=r!=null?r:a.size)!=null?O:"32px",d=(U=a.iconName)!=null?U:"refresh-cw",l=($=a.iconColor)!=null?$:"",u=(H=a.backgroundColor)!=null?H:"",p=(F=a.borderWidth)!=null?F:"",f=(K=a.borderColor)!=null?K:"",g=(ne=a.borderRadius)!=null?ne:"",v=(Se=a.paddingX)!=null?Se:"",x=(We=a.paddingY)!=null?We:"",k=(_e=a.tooltipText)!=null?_e:"Clear chat",w=(fe=a.showTooltip)!=null?fe:!0,L=h("div",t),D=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");D.style.height=i,D.style.width=i,D.type="button",D.setAttribute("aria-label",k),D.style.color=l||Sn.actionIconColor;let W=ge(d,s,"currentColor",1);if(W&&(W.style.display="block",D.appendChild(W)),u&&(D.style.backgroundColor=u,D.classList.remove("hover:persona-bg-gray-100")),p||f){let pe=p||"0px",Te=f||"transparent";D.style.border=`${pe} solid ${Te}`,D.classList.remove("persona-border-none")}if(g&&(D.style.borderRadius=g,D.classList.remove("persona-rounded-full")),v&&(D.style.paddingLeft=v,D.style.paddingRight=v),x&&(D.style.paddingTop=x,D.style.paddingBottom=x),L.appendChild(D),w&&k){let pe=null,Te=()=>{if(pe)return;let ee=D.ownerDocument,xe=ee.body;if(!xe)return;pe=br(ee,"div","persona-clear-chat-tooltip"),pe.textContent=k;let Q=br(ee,"div");Q.className="persona-clear-chat-tooltip-arrow",pe.appendChild(Q);let re=D.getBoundingClientRect();pe.style.position="fixed",pe.style.zIndex=String(Xr),pe.style.left=`${re.left+re.width/2}px`,pe.style.top=`${re.top-8}px`,pe.style.transform="translate(-50%, -100%)",xe.appendChild(pe)},je=()=>{pe&&pe.parentNode&&(pe.parentNode.removeChild(pe),pe=null)};L.addEventListener("mouseenter",Te),L.addEventListener("mouseleave",je),D.addEventListener("focus",Te),D.addEventListener("blur",je),L._cleanupTooltip=()=>{je(),L.removeEventListener("mouseenter",Te),L.removeEventListener("mouseleave",je),D.removeEventListener("focus",Te),D.removeEventListener("blur",je)}}return{button:D,wrapper:L}};var Sn={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))"},eo=e=>{var E,M,O,U,$,H,F,K,ne,Se,We,_e,fe,pe,Te,je;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(E=n==null?void 0:n.launcher)!=null?E:{},o=(M=s.headerIconSize)!=null?M:"48px",a=(O=s.closeButtonPlacement)!=null?O:"inline",i=(U=s.headerIconHidden)!=null?U:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(o)||24,xe=ge(d,ee*.6,"currentColor",1);xe?l.replaceChildren(xe):l.textContent=(H=($=n==null?void 0:n.launcher)==null?void 0:$.agentIconText)!=null?H:"\u{1F4AC}"}else if((F=n==null?void 0:n.launcher)!=null&&F.iconUrl){let ee=h("img");ee.src=n.launcher.iconUrl,ee.alt="",ee.className="persona-rounded-xl persona-object-cover",ee.style.height=o,ee.style.width=o,l.replaceChildren(ee)}else l.textContent=(ne=(K=n==null?void 0:n.launcher)==null?void 0:K.agentIconText)!=null?ne:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=Sn.titleColor,p.textContent=(We=(Se=n==null?void 0:n.launcher)==null?void 0:Se.title)!=null?We:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Sn.subtitleColor,f.textContent=(fe=(_e=n==null?void 0:n.launcher)==null?void 0:_e.subtitle)!=null?fe:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let g=(pe=s.clearChat)!=null?pe:{},v=(Te=g.enabled)!=null?Te:!0,x=(je=g.placement)!=null?je:"inline",k=null,w=null;if(v){let xe=Ra(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=xe.button,w=xe.wrapper,x==="top-right"&&(w.style.right="48px"),x==="inline"&&r.appendChild(w)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:D,wrapper:W}=Wa(n,{showClose:t,wrapperClassName:L});return a!=="top-right"&&r.appendChild(W),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:D,closeButtonWrapper:W,clearChatButton:k,clearChatButtonWrapper:w}},zo=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Eo(e){let{items:n,onSelect:t,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Xr)):(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 n){if(g.dividerBefore){let k=document.createElement("hr");a.appendChild(k)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let k=ge(g.icon,16,"currentColor",1.5);k&&v.appendChild(k)}let x=document.createElement("span");x.textContent=g.label,v.appendChild(x),v.addEventListener("click",k=>{k.stopPropagation(),u(),t(g.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let g=r.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 l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function _t(e){let{icon:n,label:t,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=ge(n,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Ha(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=ge(n,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))u.setAttribute(f,g);return u}function Ba(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=_t({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function l(u){a=u,d()}return{element:o,setSelected:l}}function Ai(e){var g,v;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",n);let u=h("span","persona-combo-btn-label");u.textContent=n,l.appendChild(u);let p=ge(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,k;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(k=d.border)!=null?k:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Eo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let k=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",k?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var kp=e=>{var r;let n=eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function Yf(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=ge(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=Eo({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Mp=e=>{var L,D,W,E,M,O,U,$,H;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(L=n==null?void 0:n.launcher)!=null?L:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,u;if(d)l=Ai({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Sn.titleColor,u=(W=l.querySelector(".persona-combo-btn-label"))!=null?W:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Sn.titleColor,u.textContent=(E=a.title)!=null?E:"Chat Assistant",l.appendChild(u),Yf(l,s==null?void 0:s.trailingActions,(M=s==null?void 0:s.onAction)!=null?M:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let K=s.onTitleClick;l.addEventListener("click",ne=>{ne.target.closest("button")||K()}),l.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),K())})}let F=s==null?void 0:s.titleRowHover;F&&(l.style.borderRadius=(O=F.borderRadius)!=null?O:"10px",l.style.padding=(U=F.padding)!=null?U:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var K,ne;l.style.backgroundColor=(K=F.background)!=null?K:"",l.style.borderColor=(ne=F.border)!=null?ne:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=($=a.closeButtonSize)!=null?$:"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=p,g.style.width=p,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||Sn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=ge(v,"28px","currentColor",1);x?g.appendChild(x):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let k=h("div");k.style.display="none";let w=h("span");return w.style.display="none",{header:i,iconHolder:k,headerTitle:u,headerSubtitle:w,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Si={default:kp,minimal:Mp},Lp=e=>{var n;return(n=Si[e])!=null?n:Si.default},Ds=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),g=h("button");g.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=Lp(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Da=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},Na=e=>{var E,M,O,U,$,H,F,K,ne,Se,We,_e;let n=(E=e==null?void 0:e.sendButton)!=null?E:{},t=(M=n.useIcon)!=null?M:!1,r=(O=n.iconText)!=null?O:"\u2191",s=n.iconName,o=(U=n.stopIconName)!=null?U:"square",a=($=n.tooltipText)!=null?$:"Send message",i=(H=n.stopTooltipText)!=null?H:"Stop generating",d=(K=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?K:"Send",l=(Se=(ne=e==null?void 0:e.copy)==null?void 0:ne.stopButtonLabel)!=null?Se:"Stop",u=(We=n.showTooltip)!=null?We:!1,p=(_e=n.size)!=null?_e:"40px",f=n.backgroundColor,g=n.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",t?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let k=null,w=null;if(t){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",g?x.style.color=g:x.style.color="var(--persona-button-primary-fg, #ffffff)";let fe=parseFloat(p)||24,pe=(g==null?void 0:g.trim())||"currentColor";s?(k=ge(s,fe,pe,2),k?x.appendChild(k):x.textContent=r):x.textContent=r,w=ge(o,fe,pe,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,g?x.style.color=g:x.classList.add("persona-text-white");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let L=null;u&&a&&(L=h("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let D="send";return{button:x,wrapper:v,setMode:fe=>{if(fe===D)return;D=fe;let pe=fe==="stop"?i:a;if(x.setAttribute("aria-label",pe),L&&(L.textContent=pe),t){if(k&&w){let Te=fe==="stop"?w:k,je=fe==="stop"?k:w;je.parentNode===x?x.replaceChild(Te,je):x.appendChild(Te)}}else x.textContent=fe==="stop"?l:d}}},Fa=e=>{var L,D,W,E,M,O,U,$,H,F,K,ne;let n=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((D=n.provider)==null?void 0:D.type)==="runtype";if(!(r||s))return null;let a=(E=(W=e==null?void 0:e.sendButton)==null?void 0:W.size)!=null?E:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(M=n.iconName)!=null?M:"mic",u=(O=n.iconSize)!=null?O:a,p=parseFloat(u)||24,f=($=n.backgroundColor)!=null?$:(U=e==null?void 0:e.sendButton)==null?void 0:U.backgroundColor,g=(F=n.iconColor)!=null?F:(H=e==null?void 0:e.sendButton)==null?void 0:H.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",g?d.style.color=g:d.style.color="var(--persona-text, #111827)";let x=ge(l,p,g||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let k=(K=n.tooltipText)!=null?K:"Start voice recognition";if(((ne=n.showTooltip)!=null?ne:!1)&&k){let Se=h("div","persona-send-button-tooltip");Se.textContent=k,i.appendChild(Se)}return{button:d,wrapper:i}},Oa=e=>{var v,x,k,w,L,D,W,E;let n=(v=e==null?void 0:e.attachments)!=null?v:{};if(n.enabled!==!0)return null;let t=(k=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?k:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((w=n.allowedTypes)!=null?w:Hr).join(","),s.multiple=((L=n.maxFiles)!=null?L:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(D=n.buttonTooltipText)!=null?D:"Attach file");let i=(W=n.buttonIconName)!=null?W:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=ge(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",M=>{M.preventDefault(),s.click()}),o.appendChild(a);let f=(E=n.buttonTooltipText)!=null?E:"Attach file",g=h("div","persona-send-button-tooltip");return g.textContent=f,o.appendChild(g),{button:a,wrapper:o,input:s,previewsContainer:r}},$a=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},_a=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ns=e=>{var v,x,k,w,L,D;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=_a(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Da(n);a();let i=Na(n),d=Fa(n),l=Oa(n),u=$a(n);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),p.append(f,g),s.append(p),s.addEventListener("click",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(l==null?void 0:l.button)&&W.target!==(l==null?void 0:l.wrapper)&&o.focus()}),t.append(r,s,u),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:u,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(w=l==null?void 0:l.wrapper)!=null?w:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:p,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Pp=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let n=h("span","persona-pill-peek__icon"),t=ge("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=ge("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},Ip=e=>{var v,x,k,w,L,D;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=_a();r.style.display="none";let s=$a(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=Da(n);o.style.maxHeight="100px",a();let i=Na(n),d=Fa(n),l=Oa(n);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(l==null?void 0:l.button)&&W.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&u.append(l.input),u.append(p,o,f),l&&t.append(l.previewsContainer),t.append(u,r,s);let g=u;return{footer:t,suggestions:r,composerForm:u,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(w=l==null?void 0:l.wrapper)!=null?w:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(D=l==null?void 0:l.previewsContainer)!=null?D:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Wp=e=>{var u,p,f,g,v,x,k,w,L,D,W,E,M,O,U,$,H;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=on(e);if(Zr(e)){let F=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},K=h("div","persona-widget-wrapper persona-fixed persona-transition");K.setAttribute("data-persona-composer-bar",""),K.dataset.state="collapsed",K.dataset.expandedSize=(v=F.expandedSize)!=null?v:"anchored",K.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:hn);let ne=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",K.appendChild(ne);let Se=h("div","persona-widget-pill-root");return Se.setAttribute("data-persona-composer-bar",""),Se.dataset.state="collapsed",Se.dataset.expandedSize=(w=F.expandedSize)!=null?w:"anchored",Se.style.zIndex=String((D=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?D:hn),{wrapper:K,panel:ne,pillRoot:Se}}if(t){let F=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),K=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild(K),{wrapper:F,panel:K}}if(!n){let F=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),K=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(E=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?E:"100%";return F.style.width=ne,K.style.width="100%",F.appendChild(K),{wrapper:F,panel:K}}let s=(M=e==null?void 0:e.launcher)!=null?M:{},o=s.position&&cr[s.position]?cr[s.position]:cr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((U=(O=e==null?void 0:e.launcher)==null?void 0:O.zIndex)!=null?U:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?H:e==null?void 0:e.launcherWidth,l=d!=null?d:Gn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Zf=(e,n)=>{var W,E,M,O,U,$,H,F,K;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Wa(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(M=(E=(W=e==null?void 0:e.launcher)==null?void 0:W.clearChat)==null?void 0:E.enabled)!=null?M:!0,a=null,i=null;if(o){let ne=Ra(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(U=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeTitle)!=null?U:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(H=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",u.append(p,f);let g=h("div","persona-flex persona-flex-col persona-gap-3"),v=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;v&&(g.style.maxWidth=v,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((K=e==null?void 0:e.copy)==null?void 0:K.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);let k=h("div","persona-composer-overlay persona-pointer-events-none");k.setAttribute("data-persona-composer-overlay",""),k.style.position="absolute",k.style.left="0",k.style.right="0",k.style.bottom="0",k.style.zIndex="20";let w=Ip({config:e}),{root:L,textNode:D}=Pp();return t.append(d,s,l,k),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:g,composerOverlay:k,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:w.footer,attachmentButton:w.attachmentButton,attachmentButtonWrapper:w.attachmentButtonWrapper,attachmentInput:w.attachmentInput,attachmentPreviewsContainer:w.attachmentPreviewsContainer,actionsRow:w.actionsRow,leftActions:w.leftActions,rightActions:w.rightActions,setSendButtonMode:w.setSendButtonMode,peekBanner:L,peekTextNode:D}},Rp=(e,n=!0)=>{var k,w,L,D,W,E,M,O,U;if(Zr(e))return Zf(e,n);let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let r=(k=e==null?void 0:e.layout)==null?void 0:k.header,s=((w=e==null?void 0:e.layout)==null?void 0:w.showHeader)!==!1,o=r?Ds(e,r,{showClose:n}):eo({config:e,showClose:n}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(D=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?D:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(E=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?E:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(M=e==null?void 0:e.layout)==null?void 0:M.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=Ns({config:e}),v=((U=e==null?void 0:e.layout)==null?void 0:U.showFooter)!==!1;s?zo(t,o,e):(o.header.style.display="none",zo(t,o,e)),t.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(g.footer.style.display="none"),t.append(g.footer),t.append(x),{container:t,body:a,messagesWrapper:u,composerOverlay:x,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var eh=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},th=(e,n)=>{if(!e)return null;let t=eh(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},nh=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},rh=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},oh=320,sh=320,ah=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),ih=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${oh}px`,l.style.maxHeight=`${sh}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,l.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{u=!0}),rh(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},Vo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},Bp=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Vo};if(n){let s=n(r);if(s!==null)return s}return Vo()},lh=(e,n)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Hp=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},ch=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Dp=(e,n,t)=>{var g,v,x,k,w,L;let r=(g=n.showCopy)!=null?g:!0,s=(v=n.showUpvote)!=null?v:!0,o=(x=n.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let D=h("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let a=(k=n.visibility)!=null?k:"hover",i=(w=n.align)!=null?w:"right",d=(L=n.layout)!=null?L:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(D,W,E)=>{let M=_t({icon:D,label:W,size:14,className:"persona-message-action-btn"});return M.setAttribute("data-action",E),M};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Fs=(e,n,t,r,s,o)=>{var pe,Te,je,ee,xe,Q,re,Me,ae,Be,Re,J,De,He,G,V,ve;let a=t!=null?t:{},i=(pe=a.layout)!=null?pe:"bubble",d=a.avatar,l=a.timestamp,u=(Te=d==null?void 0:d.show)!=null?Te:!1,p=(je=l==null?void 0:l.show)!=null?je:!1,f=(ee=d==null?void 0:d.position)!=null?ee:"left",g=(xe=l==null?void 0:l.position)!=null?xe:"below",v=ch(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=ah(e),w=(re=(Q=e.content)==null?void 0:Q.trim())!=null?re:"",D=k.length>0&&w===ha,W=Ma((ae=(Me=o==null?void 0:o.widgetConfig)==null?void 0:Me.features)==null?void 0:ae.streamAnimation),E=(J=(Re=(Be=o==null?void 0:o.widgetConfig)==null?void 0:Be.features)==null?void 0:Re.streamAnimation)==null?void 0:J.plugins,M=e.role==="assistant"&&W.type!=="none"?Is(W.type,E):null,O=e.role==="assistant"&&((De=M==null?void 0:M.isAnimating)==null?void 0:De.call(M,e))===!0,U=e.role==="assistant"&&M!==null&&(!!e.streaming||O);U&&(M!=null&&M.bubbleClass)&&x.classList.add(M.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),U&&M&&(M.containerClass&&$.classList.add(M.containerClass),$.style.setProperty("--persona-stream-step",`${W.speed}ms`),$.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let H=U?La((He=e.content)!=null?He:"",W.buffer,M,e,!!e.streaming):(G=e.content)!=null?G:"",F=n({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),K=F;U&&(M==null?void 0:M.wrap)==="char"?K=Ws(F,"char",e.id,{skipTags:M.skipTags}):U&&(M==null?void 0:M.wrap)==="word"&&(K=Ws(F,"word",e.id,{skipTags:M.skipTags}));let ne=null;if(D?(ne=document.createElement("div"),ne.innerHTML=K,ne.style.display="none",$.appendChild(ne)):$.innerHTML=K,U&&(M!=null&&M.useCaret)&&!D&&w){let ce=Pa(),te=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),me=te[te.length-1];if(me!=null&&me.parentNode)me.parentNode.insertBefore(ce,me.nextSibling);else{let Qe=$.lastElementChild;Qe?Qe.appendChild(ce):$.appendChild(ce)}}if(p&&g==="inline"&&e.createdAt){let ce=Hp(e,l);ce.classList.add("persona-ml-2","persona-inline"),$.appendChild(ce)}if(k.length>0){let ce=ih(k,!D&&!!w,()=>{D&&ne&&(ne.style.display="")});ce?x.appendChild(ce):D&&ne&&(ne.style.display="")}if(x.appendChild($),p&&g==="below"&&e.createdAt){let ce=Hp(e,l);ce.classList.add("persona-mt-1"),x.appendChild(ce)}let Se=e.role==="assistant"?th(e.stopReason,(ve=(V=o==null?void 0:o.widgetConfig)==null?void 0:V.copy)==null?void 0:ve.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ce=!!(H&&H.trim()),te=W.placeholder==="skeleton",me=te&&W.buffer==="line"&&ce;if(ce)me&&x.appendChild(Rs());else if(te)x.appendChild(Rs());else{let Qe=Bp("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Qe&&x.appendChild(Qe)}}if(Se&&e.stopReason&&!e.streaming&&(w||($.style.display="none"),x.appendChild(nh(e.stopReason,Se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let ce=Dp(e,r,s);x.appendChild(ce)}if(!u||e.role==="system")return x;let _e=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),fe=lh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?_e.append(x,fe):_e.append(fe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),_e},dh=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Fs(e,n,t,r,s,o)};var Jo=new Set,ph=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),uh=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
|
|
17
|
+
`):""},Np=(e,n)=>{let t=Jo.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Ei=(e,n)=>{var We,_e,fe,pe,Te,je,ee,xe,Q,re,Me;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let s=(_e=(We=n==null?void 0:n.features)==null?void 0:We.reasoningDisplay)!=null?_e:{},o=s.expandable!==!1,a=o&&Jo.has(e.id),i=t.status!=="complete",d=uh(e,(fe=s.previewMaxLines)!=null?fe:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(pe=n==null?void 0:n.reasoning)!=null?pe:{},v=String((Te=t.startedAt)!=null?Te:Date.now()),x=()=>{let ae=h("span","");return ae.setAttribute("data-tool-elapsed",v),ae.textContent=ua(t),ae},k=(je=g.renderCollapsedSummary)==null?void 0:je.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:n!=null?n:{},elapsed:ua(t),createElapsedElement:x});typeof k=="string"&&k.trim()?(p.textContent=k,u.appendChild(p)):k instanceof HTMLElement?u.appendChild(k):(p.textContent=f,u.appendChild(p));let w=h("span","persona-text-xs persona-text-persona-primary");w.textContent=rp(t),u.appendChild(w);let L=(ee=s.loadingAnimation)!=null?ee:"none",D=g.activeTextTemplate,W=g.completeTextTemplate,E=i?D:W,M=k instanceof HTMLElement,O=(ae,Be,Re)=>{let J=Re;for(let De of Be){let He=h("span","persona-tool-char");He.style.setProperty("--char-index",String(J)),He.textContent=De===" "?"\xA0":De,ae.appendChild(He),J++}return J},U=(ae,Be)=>{p.textContent="";let Re=ma(ae,""),J=0;for(let De of Re){let He=De.styles.length>0?(()=>{let G=h("span",De.styles.map(V=>`persona-tool-text-${V}`).join(" "));return p.appendChild(G),G})():p;if(De.isDuration&&i)He.appendChild(x());else{let G=De.isDuration?ua(t):De.text;Be?J=O(He,G,J):He.appendChild(document.createTextNode(G))}}};if(!M&&E)if(w.style.display="none",p.style.display="",i&&L!=="none"){let ae=(xe=g.loadingAnimationDuration)!=null?xe:2e3;p.setAttribute("data-preserve-animation","true"),L==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),U(E,!1)):(p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),L==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),U(E,!0))}else U(E,!1);else if(!M&&i&&L!=="none"){p.style.display="";let ae=(Q=g.loadingAnimationDuration)!=null?Q:2e3;if(p.setAttribute("data-preserve-animation","true"),L==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ae}ms`);else{p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),L==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Be=p.textContent||f;p.textContent="",O(p,Be,0)}t.status==="complete"&&(p.style.display="none")}else M||(t.status==="complete"?p.style.display="none":p.style.display="");let $=null;if(o){$=h("div","persona-flex persona-items-center");let Be=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);Be?$.appendChild(Be):$.textContent=a?"Hide":"Show";let Re=h("div","persona-flex persona-items-center persona-ml-auto");Re.append($),l.append(u,Re)}else l.append(u);let H=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","reasoning"),H.style.display="none",H.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let ae=(Me=(re=n==null?void 0:n.reasoning)==null?void 0:re.renderCollapsedPreview)==null?void 0:Me.call(re,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});ph(H,ae)||(H.textContent=d),H.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,H),r;let F=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=a?"":"none";let K=t.chunks.join(""),ne=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=K||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(ne),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),$){$.innerHTML="";let Be=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);Be?$.appendChild(Be):$.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",H.style.display=a?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(l,H,F),r};var Ko=new Set,mh=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),gh=(e,n)=>{var o;let t=e.toolCall;if(!t)return"";let r=((o=t.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
|
|
18
18
|
`);let s=Oo(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
|
|
19
|
-
`):""},gh=(e,n)=>{var u,p,f,g,v;let t=e.toolCall,r=(u=n==null?void 0:n.features)==null?void 0:u.toolCallDisplay,s=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",o=mh(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?op(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(g=n==null?void 0:n.toolCall)!=null?g:{},l=a;return s==="tool-name"?l=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=ai(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ai(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Fp=(e,n,t)=>{var u;let r=Ko.has(e),s=(u=t==null?void 0:t.toolCall)!=null?u:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=ge(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Ti=(e,n)=>{var K,ne,Se,We,_e,fe,pe,Te,Ue;let t=e.toolCall,r=(K=n==null?void 0:n.toolCall)!=null?K:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(Se=(ne=n==null?void 0:n.features)==null?void 0:ne.toolCallDisplay)!=null?Se:{},a=o.expandable!==!1,i=a&&Ko.has(e.id),{summary:d,previewText:l,isActive:u}=gh(e,n),p=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");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let v=String((We=t.startedAt)!=null?We:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",v),ee.textContent=vs(t),ee},k=(fe=r.renderCollapsedSummary)==null?void 0:fe.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(_e=o.collapsedMode)!=null?_e:"tool-call",isActive:u,config:n!=null?n:{},elapsed:vs(t),createElapsedElement:x});typeof k=="string"&&k.trim()?(g.textContent=k,f.appendChild(g)):k instanceof HTMLElement?f.appendChild(k):(g.textContent=d,f.appendChild(g));let C=(pe=o.loadingAnimation)!=null?pe:"none",L=r.activeTextTemplate,D=r.completeTextTemplate,W=u?L:D,E=k instanceof HTMLElement,M=(ee,xe,Q)=>{let re=Q;for(let Me of xe){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(re)),ae.textContent=Me===" "?"\xA0":Me,ee.appendChild(ae),re++}return re},O=(ee,xe)=>{var ae;g.textContent="";let Q=((ae=t.name)==null?void 0:ae.trim())||"tool",re=ma(ee,Q),Me=0;for(let Be of re){let Re=Be.styles.length>0?(()=>{let J=h("span",Be.styles.map(De=>`persona-tool-text-${De}`).join(" "));return g.appendChild(J),J})():g;if(Be.isDuration&&u)Re.appendChild(x());else{let J=Be.isDuration?vs(t):Be.text;xe?Me=M(Re,J,Me):Re.appendChild(document.createTextNode(J))}}};if(!E)if(u&&C!=="none"){let ee=(Te=r.loadingAnimationDuration)!=null?Te:2e3;if(g.setAttribute("data-preserve-animation","true"),C==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),W&&O(W,!1);else if(g.classList.add(`persona-tool-loading-${C}`),g.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),C==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),W)O(W,!0);else{let xe=g.textContent||d;g.textContent="",M(g,xe,0)}}else W&&O(W,!1);let j=null;if(a){j=h("div","persona-flex persona-items-center");let ee=r.toggleTextColor||r.headerTextColor||"currentColor",xe=ge(i?"chevron-up":"chevron-down",16,ee,2);xe?j.appendChild(xe):j.textContent=i?"Hide":"Show";let Q=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(j),p.append(f,Q)}else p.append(f);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&l){let ee=(Ue=r.renderCollapsedPreview)==null?void 0:Ue.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});uh($,ee)||($.textContent=l),$.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,$),s;let H=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),t.name){let ee=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ee.style.color=r.contentTextColor:r.headerTextColor&&(ee.style.color=r.headerTextColor),ee.textContent=t.name,H.appendChild(ee)}if(t.args!==void 0){let ee=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Arguments";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=Oo(t.args),ee.append(xe,Q),H.appendChild(ee)}if(t.chunks&&t.chunks.length){let ee=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Activity";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=t.chunks.join(""),ee.append(xe,Q),H.appendChild(ee)}if(t.status==="complete"&&t.result!==void 0){let ee=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Result";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=Oo(t.result),ee.append(xe,Q),H.appendChild(ee)}if(t.status==="complete"&&typeof t.duration=="number"){let ee=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ee.style.color=r.contentTextColor),ee.textContent=`Duration: ${t.duration}ms`,H.appendChild(ee)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),j){j.innerHTML="";let ee=r.toggleTextColor||r.headerTextColor||"currentColor",xe=ge(i?"chevron-up":"chevron-down",16,ee,2);xe?j.appendChild(xe):j.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(p,$,H),s};import{parse as fh,ARR as hh,OBJ as yh,STR as bh}from"partial-json";var $p="ask_user_question",ki=8,Go="data-persona-ask-sheet-for",xh="Other",vh="Other\u2026",_p="Type your own answer here",Up="Send",wh="Next",Ch="Back",Ah="Submit all",Sh="Skip",Eh=3,Mi="data-ask-current-index",Li="data-ask-question-count",jp="data-ask-answers",Pi="data-ask-grouped",qp="data-ask-layout",Th=e=>e.layout==="pills"?"pills":"rows",kh=e=>e.getAttribute(qp)==="pills"?"pills":"rows",Op=!1,zp=e=>e.replace(/["\\]/g,"\\$&"),to=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===$p,Ua=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},no=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=fh(s,bh|yh|hh);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},Os=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>ki&&!Op&&(Op=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${ki}.`)),n.slice(0,ki)},Mh=e=>{var n;return(n=Os(e)[0])!=null?n:null},Lh=(e,n)=>{var t;return(t=Os(e)[n])!=null?t:null},Vp=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Jp=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},Ph=(e,n,t,r)=>{let o=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(n)),o.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Jp(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Ih=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},Wh=(e,n,t,r)=>{var u,p,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!t){for(let g=0;g<Eh;g++)o.appendChild(Ih(r));return o}if(d.forEach((g,v)=>{o.appendChild(Ph(g,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?xh:vh;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(u=n.freeTextPlaceholder)!=null?u:_p,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:g),x.appendChild(k),v.appendChild(x);let C=Jp(r,a,d.length);C&&v.appendChild(C),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=n.freeTextLabel)!=null?f:g,o.appendChild(v)}}return o},Kp=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:_p,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Up,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Rh=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:Up,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},Hh=(e,n,t)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=t.backLabel)!=null?l:Ch,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:Sh,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===n-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:Ah:(f=t.nextLabel)!=null?f:wh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},To=e=>{let n=e.getAttribute(jp);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Gp=(e,n)=>{e.setAttribute(jp,JSON.stringify(n))},Qn=e=>{var t;let n=Number((t=e.getAttribute(Mi))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},Bh=(e,n)=>{e.setAttribute(Mi,String(Math.max(0,Math.floor(n))))},Qo=e=>{var t;let n=Number((t=e.getAttribute(Li))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},ro=e=>e.getAttribute(Pi)==="true",Dh=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Nh=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},ja=(e,n)=>{let{payload:t}=no(n),r=Os(t),s=To(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Qp=e=>{let n=To(e),t=Qn(e),r=n[t],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=s.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Xp=e=>{if(!ro(e))return;let n=To(e),t=Qn(e),r=n[t],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ii=(e,n,t)=>{let r=Ua(t),s=kh(e),{payload:o,complete:a}=no(n),i=ro(e),d=Qn(e),l=Qo(e),u=i?Lh(o,d):Mh(o),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=Wh(u,r,a,s);x.replaceWith(L)}if(s!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Kp(r,s))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!k?e.appendChild(Rh(r)):(!p||i)&&k&&k.remove(),e.setAttribute("data-multi-select",p?"true":"false");let C=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=Hh(d,l,r);C?C.replaceWith(L):e.appendChild(L)}else C&&C.remove();Qp(e),Xp(e)},Fh=(e,n,t)=>{let r=Ua(n),s=Th(r),o=e.toolCall.id,a=Os(t),i=Math.max(1,a.length),d=i>1,l=Dh(e,a),u=d?Nh(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Go,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(Li,String(i)),p.setAttribute(Mi,String(u)),p.setAttribute(Pi,d?"true":"false"),p.setAttribute(qp,s),Gp(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Vp(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),p.appendChild(f);let k=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),p.appendChild(k),s!=="rows"&&p.appendChild(Kp(r,s)),Ii(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Oh=(e,n,t)=>{let{payload:r}=no(n),s=Math.max(1,Os(r).length);s>Qo(e)&&(e.setAttribute(Li,String(s)),s>1&&!ro(e)&&e.setAttribute(Pi,"true")),Ii(e,n,t)},$h=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=Ua(n);Vp(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=no(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},$s=(e,n,t)=>{if(!t||!to(e)||Ua(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${Go}]`).forEach(l=>{l.getAttribute(Go)!==s&&l.remove()});let a=t.querySelector(`[${Go}="${zp(s)}"]`);if(a){Oh(a,e,n);return}let{payload:i}=no(e),d=Fh(e,n,i);t.appendChild(d)},ko=(e,n)=>{if(!e)return;let t=n?`[${Go}="${zp(n)}"]`:`[${Go}]`;e.querySelectorAll(t).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Wi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),oo=(e,n)=>{let t=To(e),r=Qn(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,Gp(e,t),Qp(e),Xp(e)},qa=(e,n,t,r)=>{let s=Qo(e),o=Math.max(0,Math.min(s-1,r));Bh(e,o),Ii(e,n,t)};var Ri=(e,n)=>{var x,k,C,L,D,W,E,M,O,j,$,H;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(k=r==null?void 0:r.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(C=r==null?void 0:r.titleColor)!=null?C:"currentColor",u=ge(d,20,l,2);u&&i.appendChild(u);let p=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(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(L=r==null?void 0:r.title)!=null?L:"Approval Required",f.appendChild(g),!s){let F=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",t.status),t.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):t.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):t.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),f.appendChild(F)}p.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=t.description,p.appendChild(v),t.parameters){let F=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(F.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(F.style.color=r.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=Oo(t.parameters),p.appendChild(F)}if(s){let F=h("div","persona-flex persona-gap-2 persona-mt-2");F.setAttribute("data-approval-buttons","true");let K=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");K.type="button",K.style.backgroundColor=(D=r==null?void 0:r.approveButtonColor)!=null?D:"var(--persona-approval-approve-bg, #22c55e)",K.style.color=(W=r==null?void 0:r.approveButtonTextColor)!=null?W:"#ffffff",K.setAttribute("data-approval-action","approve");let ne=ge("shield-check",14,(E=r==null?void 0:r.approveButtonTextColor)!=null?E:"#ffffff",2);ne&&(ne.style.marginRight="4px",K.appendChild(ne));let Se=document.createTextNode((M=r==null?void 0:r.approveLabel)!=null?M:"Approve");K.appendChild(Se);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=(O=r==null?void 0:r.denyButtonColor)!=null?O:"transparent",We.style.color=(j=r==null?void 0:r.denyButtonTextColor)!=null?j:"var(--persona-feedback-error, #dc2626)",We.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,We.setAttribute("data-approval-action","deny");let _e=ge("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);_e&&(_e.style.marginRight="4px",We.appendChild(_e));let fe=document.createTextNode((H=r==null?void 0:r.denyLabel)!=null?H:"Deny");We.appendChild(fe),F.append(K,We),p.appendChild(F)}return a.append(i,p),o.appendChild(a),o};var Yp=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let u=document.createDocumentFragment(),p=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'}};r.forEach(g=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=g,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),u.appendChild(v),n.push(v)}),e.appendChild(u)}}};var _s=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Us=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function Xo(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var _h={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)"}},Uh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},jh=["flowName","stepName","reasoningText","text","name","tool","toolName"],qh=100;function zh(e,n){let t={..._h,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Uh}function Vh(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Jh(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function Kh(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Gh(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Qh(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Xh(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Hi(e,n,t,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Xo(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let g=u.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(p()),l;function p(){var K,ne;let g=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),k=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);k&&x.appendChild(k);let C=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(K=r.timestampFormat)!=null?K:"relative";C.textContent=L==="relative"?Vh(e.timestamp,t):Jh(e.timestamp);let D=null;r.showSequenceNumbers!==!1&&(D=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(n+1));let W=zh(e.type,r.badgeColors),E=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");E.style.backgroundColor=W.bg,E.style.color=W.text,E.style.borderColor=W.text+"50",E.textContent=e.type;let M=(ne=r.descriptionFields)!=null?ne:jh,O=Kh(e.payload,M),j=null;O&&(j=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),j.textContent=O);let $=h("div","persona-flex-1 persona-min-w-0"),H=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"),F=ge("clipboard","12px","currentColor",1.5);return F&&H.appendChild(F),H.addEventListener("click",async Se=>{Se.stopPropagation(),await Gh(Qh(e)),H.innerHTML="";let We=ge("check","12px","currentColor",1.5);We&&H.appendChild(We),setTimeout(()=>{H.innerHTML="";let _e=ge("clipboard","12px","currentColor",1.5);_e&&H.appendChild(_e)},1500)}),v.appendChild(x),v.appendChild(C),D&&v.appendChild(D),v.appendChild(E),j&&v.appendChild(j),v.appendChild($),v.appendChild(H),g.appendChild(v),d&&g.appendChild(Xh(e,a,i)),g}}function Zp(e){var g,v,x,k,C;let{buffer:n,getFullHistory:t,onClose:r,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,d=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",l=(x=a==null?void 0:a.label)!=null?x:"",u=(C=(k=s==null?void 0:s.features)==null?void 0:k.eventStream)!=null?C:{},p=o.find(L=>L.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let L=p.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return f();function f(){let L=u.classNames,D=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Xo(D,L==null?void 0:L.panel);let W=[],E="",M="",O=null,j=[],$={},H=0,F=Ea(),K=0,ne=0,Se=!1,We=null,_e=!1,fe=0,pe=new Set,Te=new Map,Ue="",ee="",xe=null,Q,re,Me,ae,Be;function Re(){let R=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),se=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");Xo(se,L==null?void 0:L.headerBar);let we=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");we.textContent="Events",Q=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Q.textContent="0";let pt=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 Je=h("option","");Je.value="",Je.textContent="All events",re.appendChild(Je),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 ln=ge("clipboard-copy","12px","currentColor",1.5);ln&&Me.appendChild(ln);let wt=h("span","persona-text-xs");wt.textContent="Copy All",Me.appendChild(wt),se.appendChild(we),se.appendChild(Q),se.appendChild(pt),se.appendChild(re),se.appendChild(Me);let ht=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Xo(ht,L==null?void 0:L.searchBar);let St=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),it=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");St&&it.appendChild(St),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"),Xo(ae,L==null?void 0:L.searchInput),ae.type="text",ae.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 Vt=ge("x","12px","currentColor",2);return Vt&&Be.appendChild(Vt),ht.appendChild(it),ht.appendChild(ae),ht.appendChild(Be),R.appendChild(se),R.appendChild(ht),R}let J,De=o.find(R=>R.renderEventStreamToolbar);if(De!=null&&De.renderEventStreamToolbar&&s){let R=De.renderEventStreamToolbar({config:s,defaultRenderer:()=>Re(),eventCount:n.getSize(),filteredCount:0,onFilterChange:se=>{E=se,Ne(),qt()},onSearchChange:se=>{M=se,Ne(),qt()}});J=R!=null?R:Re()}else J=Re();let He=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");He.style.display="none";let G=h("div","persona-flex-1 persona-min-h-0 persona-relative"),V=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");V.style.height="100%";let ve=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");Xo(ve,L==null?void 0:L.scrollIndicator),ve.style.display="none",ve.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let ce=ge(d,"14px","currentColor",2);ce&&ve.appendChild(ce);let te=h("span","");te.textContent=l,ve.appendChild(te);let me=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");me.style.display="none",G.appendChild(V),G.appendChild(me),G.appendChild(ve),D.setAttribute("tabindex","0"),D.appendChild(J),D.appendChild(He),D.appendChild(G);function Qe(){let R=n.getAll(),se={};for(let wt of R)se[wt.type]=(se[wt.type]||0)+1;let we=Object.keys(se).sort(),pt=we.length!==j.length||!we.every((wt,ht)=>wt===j[ht]),Je=!pt&&we.some(wt=>se[wt]!==$[wt]),Nt=R.length!==Object.values($).reduce((wt,ht)=>wt+ht,0);if(!pt&&!Je&&!Nt||(j=we,$=se,!re))return;let ln=re.value;if(re.options[0].textContent="All events",pt){for(;re.options.length>1;)re.remove(1);for(let wt of we){let ht=h("option","");ht.value=wt,ht.textContent=`${wt} (${se[wt]||0})`,re.appendChild(ht)}ln&&we.includes(ln)?re.value=ln:ln&&(re.value="",E="")}else for(let wt=1;wt<re.options.length;wt++){let ht=re.options[wt];ht.textContent=`${ht.value} (${se[ht.value]||0})`}}function Ft(){let R=n.getAll();if(E&&(R=R.filter(se=>se.type===E)),M){let se=M.toLowerCase();R=R.filter(we=>we.type.toLowerCase().includes(se)||we.payload.toLowerCase().includes(se))}return R}function ie(){return E!==""||M!==""}function Ne(){H=0,K=0,F.resume(),ve.style.display="none"}function an(R){pe.has(R)?pe.delete(R):pe.add(R),xe=R;let se=V.scrollTop,we=F.isFollowing();_e=!0,F.pause(),qt(),V.scrollTop=se,we&&F.resume(),_e=!1}function Pt(){return Ms(V,50)}function qt(){ne=Date.now(),Se=!1,Qe();let R=n.getEvictedCount();R>0?(He.textContent=`${R.toLocaleString()} older events truncated`,He.style.display=""):He.style.display="none",W=Ft();let se=W.length,we=n.getSize()>0;Q&&(Q.textContent=String(n.getSize())),se===0&&we&&ie()?(me.textContent=M?`No events matching '${M}'`:"No events matching filter",me.style.display="",V.style.display="none"):(me.style.display="none",V.style.display=""),Me&&(Me.title=ie()?`Copy Filtered (${se})`:"Copy All"),i&&!F.isFollowing()&&se>H&&(K+=se-H,te.textContent=l?`${l}${K>0?` (${K})`:""}`:"",ve.style.display=""),H=se;let pt=n.getAll(),Je=pt.length>0?pt[0].timestamp:0,Nt=new Set(W.map(ht=>ht.id));for(let ht of pe)Nt.has(ht)||pe.delete(ht);let ln=E!==Ue||M!==ee,wt=Te.size===0&&W.length>0;if(ln||wt||W.length===0){V.innerHTML="",Te.clear();let ht=document.createDocumentFragment();for(let St=0;St<W.length;St++){let it=Hi(W[St],St,Je,u,pe,an,o,s);Te.set(W[St].id,it),ht.appendChild(it)}V.appendChild(ht),Ue=E,ee=M,xe=null}else{if(xe!==null){let St=Te.get(xe);if(St&&St.parentNode===V){let it=W.findIndex(Vt=>Vt.id===xe);if(it>=0){let Vt=Hi(W[it],it,Je,u,pe,an,o,s);V.insertBefore(Vt,St),St.remove(),Te.set(xe,Vt)}}xe=null}let ht=new Set(W.map(St=>St.id));for(let[St,it]of Te)ht.has(St)||(it.remove(),Te.delete(St));for(let St=0;St<W.length;St++){let it=W[St];if(!Te.has(it.id)){let Vt=Hi(it,St,Je,u,pe,an,o,s);Te.set(it.id,Vt),V.appendChild(Vt)}}}F.isFollowing()&&(V.scrollTop=V.scrollHeight)}function vr(){if(Date.now()-ne>=qh){We!==null&&(cancelAnimationFrame(We),We=null),qt();return}Se||(Se=!0,We=requestAnimationFrame(()=>{We=null,qt()}))}let dr=(R,se)=>{if(!Me)return;Me.innerHTML="";let we=ge(R,"12px","currentColor",1.5);we&&Me.appendChild(we);let pt=h("span","persona-text-xs");pt.textContent="Copy All",Me.appendChild(pt),setTimeout(()=>{Me.innerHTML="";let Je=ge("clipboard-copy","12px","currentColor",1.5);Je&&Me.appendChild(Je);let Nt=h("span","persona-text-xs");Nt.textContent="Copy All",Me.appendChild(Nt),Me.disabled=!1},se)},P=async()=>{if(Me){Me.disabled=!0;try{let R;ie()?R=W:t?(R=await t(),R.length===0&&(R=n.getAll())):R=n.getAll();let se=R.map(we=>{try{return JSON.parse(we.payload)}catch{return we.payload}});await navigator.clipboard.writeText(JSON.stringify(se,null,2)),dr("check",1500)}catch{dr("x",1500)}}},oe=()=>{re&&(E=re.value,Ne(),qt())},Pe=()=>{!ae||!Be||(Be.style.display=ae.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{M=ae.value,Ne(),qt()},150))},qe=()=>{!ae||!Be||(ae.value="",M="",Be.style.display="none",O&&clearTimeout(O),Ne(),qt())},Fe=()=>{if(_e)return;let R=V.scrollTop,{action:se,nextLastScrollTop:we}=Ta({following:F.isFollowing(),currentScrollTop:R,lastScrollTop:fe,nearBottom:Pt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});fe=we,se==="resume"?(F.resume(),K=0,ve.style.display="none"):se==="pause"&&(F.pause(),i&&(te.textContent=l,ve.style.display=""))},Oe=R=>{let se=ka({following:F.isFollowing(),deltaY:R.deltaY,nearBottom:Pt(),resumeWhenNearBottom:!0});se==="pause"?(F.pause(),i&&(te.textContent=l,ve.style.display="")):se==="resume"&&(F.resume(),K=0,ve.style.display="none")},Ze=()=>{i&&(V.scrollTop=V.scrollHeight,F.resume(),K=0,ve.style.display="none")},vt=R=>{let se=R.target;if(!se||se.closest("button"))return;let we=se.closest("[data-event-id]");if(!we)return;let pt=we.getAttribute("data-event-id");pt&&an(pt)},Ot=R=>{if((R.metaKey||R.ctrlKey)&&R.key==="f"){R.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}R.key==="Escape"&&(ae&&document.activeElement===ae?(qe(),ae.blur(),D.focus()):r&&r())};Me&&Me.addEventListener("click",P),re&&re.addEventListener("change",oe),ae&&ae.addEventListener("input",Pe),Be&&Be.addEventListener("click",qe),V.addEventListener("scroll",Fe),V.addEventListener("wheel",Oe,{passive:!0}),V.addEventListener("click",vt),ve.addEventListener("click",Ze),D.addEventListener("keydown",Ot);function zt(){O&&clearTimeout(O),We!==null&&(cancelAnimationFrame(We),We=null),Se=!1,Te.clear(),Me&&Me.removeEventListener("click",P),re&&re.removeEventListener("change",oe),ae&&ae.removeEventListener("input",Pe),Be&&Be.removeEventListener("click",qe),V.removeEventListener("scroll",Fe),V.removeEventListener("wheel",Oe),V.removeEventListener("click",vt),ve.removeEventListener("click",Ze),D.removeEventListener("keydown",Ot)}return{element:D,update:vr,destroy:zt}}}function eu(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.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",p.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(g)}else p.textContent=a;if(l.append(u,p),i.append(d,l),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",r),i.append(f)}return i}var tu=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>eu(e,n)});if(u)return u}return eu(e,n)};var Bi=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},so=new Bi;so.register("PersonaArtifactCard",tu);function Yh(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function nu(e,n){var Me,ae,Be,Re;let t=(ae=(Me=e.features)==null?void 0:Me.artifacts)==null?void 0:ae.layout,s=((Be=t==null?void 0:t.toolbarPreset)!=null?Be:"default")==="document",o=(Re=t==null?void 0:t.panePadding)==null?void 0:Re.trim(),a=e.markdown?No(e.markdown):null,i=bs(e.sanitize),d=J=>{let De=a?a(J):Fo(J);return i?i(De):De},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let p=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");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.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 v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let x="rendered",k=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?_t({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):_t({icon:"eye",label:"Rendered view"}),L=s?_t({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):_t({icon:"code-2",label:"Source"}),D=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),W=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,E=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,M=t==null?void 0:t.documentToolbarCopyMenuItems,O=!!(E&&M&&M.length>0),j=null,$,H=null,F=null;if(s&&(W||E)&&!O){if($=W?Ha({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E){let J=ge("chevron-down",14,"currentColor",2);J&&$.appendChild(J)}}else s&&O?(j=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=W?Ha({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=_t({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"}}),j.append($,H)):s?$=_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=_t({icon:"copy",label:"Copy"});let K=s?_t({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):_t({icon:"refresh-cw",label:"Refresh"}),ne=s?_t({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):_t({icon:"x",label:"Close"}),Se=()=>{var V,ve,ce;let J=(V=Ue.find(te=>te.id===ee))!=null?V:Ue[Ue.length-1],De=(ve=J==null?void 0:J.id)!=null?ve:null,He=(J==null?void 0:J.artifactType)==="markdown"&&(ce=J.markdown)!=null?ce:"",G=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:He,jsonPayload:G,id:De}},We=async()=>{var V;let{markdown:J,jsonPayload:De}=Se(),He=(V=Ue.find(ve=>ve.id===ee))!=null?V:Ue[Ue.length-1],G=(He==null?void 0:He.artifactType)==="markdown"?J:He?De:"";try{await navigator.clipboard.writeText(G)}catch{}};if($.addEventListener("click",async()=>{let J=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(J&&O){let{markdown:De,jsonPayload:He,id:G}=Se();try{await J({actionId:"primary",artifactId:G,markdown:De,jsonPayload:He})}catch{}return}await We()}),H&&(M!=null&&M.length)){let J=()=>{var He;return(He=p.closest("[data-persona-root]"))!=null?He:document.body},De=()=>{F=Eo({items:M.map(He=>({id:He.id,label:He.label})),onSelect:async He=>{let{markdown:G,jsonPayload:V,id:ve}=Se(),ce=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ce?await ce({actionId:He,artifactId:ve,markdown:G,jsonPayload:V}):He==="markdown"||He==="md"?await navigator.clipboard.writeText(G):He==="json"||He==="source"?await navigator.clipboard.writeText(V):await navigator.clipboard.writeText(G||V)}catch{}},anchor:j!=null?j:H,position:"bottom-right",portal:J()})};p.isConnected?De():requestAnimationFrame(De),H.addEventListener("click",He=>{He.stopPropagation(),F==null||F.toggle()})}K.addEventListener("click",async()=>{var J;try{await((J=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:J.call(t))}catch{}Q()}),ne.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let _e=()=>{s&&(C.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};C.addEventListener("click",()=>{x="rendered",_e(),Q()}),L.addEventListener("click",()=>{x="source",_e(),Q()});let fe=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(),k.append(C,L),j?D.append(j,K,ne):D.append($,K,ne),f.append(k,fe,D),_e()):(f.appendChild(g),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let pe=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"),Te=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(pe.style.paddingLeft=o,pe.style.paddingRight=o,Te.style.padding=o),p.appendChild(f),p.appendChild(pe),p.appendChild(Te);let Ue=[],ee=null,xe=!1,Q=()=>{var G,V,ve,ce;let J=s&&Ue.length<=1;pe.classList.toggle("persona-hidden",J),pe.replaceChildren();for(let te of Ue){let me=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");me.type="button",me.textContent=te.title||te.id.slice(0,8),te.id===ee&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>n.onSelect(te.id)),pe.appendChild(me)}Te.replaceChildren();let De=ee&&Ue.find(te=>te.id===ee)||Ue[Ue.length-1];if(!De)return;if(s){let te=De.artifactType==="markdown"?"MD":(G=De.component)!=null?G:"Component",Qe=(De.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";fe.textContent=`${Qe} \xB7 ${te}`}else g.textContent="Artifacts";if(De.artifactType==="markdown"){if(s&&x==="source"){let me=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(V=De.markdown)!=null?V:"",Te.appendChild(me);return}let te=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");te.innerHTML=d((ve=De.markdown)!=null?ve:""),Te.appendChild(te);return}let He=De.component?so.get(De.component):void 0;if(He){let me={message:{id:De.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Qe=He((ce=De.props)!=null?ce:{},me);if(Qe){Te.appendChild(Qe);return}}catch{}}Te.appendChild(Yh(De))},re=()=>{var De;let J=Ue.length>0;if(p.classList.toggle("persona-hidden",!J),l){let He=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,V=((De=He==null?void 0:He.classList.contains("persona-artifact-narrow-host"))!=null?De:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&V&&xe?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(J){var De,He,G;Ue=J.artifacts,ee=(G=(He=J.selectedId)!=null?He:(De=J.artifacts[J.artifacts.length-1])==null?void 0:De.id)!=null?G:null,Ue.length>0&&(xe=!0),Q(),re()},setMobileOpen(J){xe=J,!J&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):re()}}}function Xn(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function ru(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Xn(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Zh(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 za(e,n){var d,l,u,p,f,g,v,x,k,C;if(!Xn(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Zh(e),ru(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"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 r=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(k=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:k.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(C=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:C.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ru(e,n)}var ou=["panel","seamless"];function Va(e,n){var i,d,l,u,p,f;for(let g of ou)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"),!Xn(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=ou.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.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 su(e,n){var t,r,s;return!n||!Xn(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function ey(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function ty(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function ny(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function ry(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function au(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function iu(e,n,t,r,s,o){let a=ey(s,200),i=ry(n,t,r,200);i=Math.max(a,i);let d=ty(o);return d!==null&&(i=Math.min(i,d)),ny(e,a,i)}var lu={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"}},Di=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,k;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=lu[a])!=null?x:lu.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let C=h("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,d.appendChild(C)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var M,O;let L=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${n.id}-${a}-${C.name}`;let D=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=C.label,L.appendChild(D);let W=(M=C.type)!=null?M:"text",E;W==="textarea"?(E=document.createElement("textarea"),E.rows=3):(E=document.createElement("input"),E.type=W),E.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",E.id=`${n.id}-${a}-${C.name}`,E.name=C.name,E.placeholder=(O=C.placeholder)!=null?O:"",C.required&&(E.required=!0),L.appendChild(E),u.appendChild(L)});let p=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=(k=i.submitLabel)!=null?k:"Submit",p.appendChild(f),p.appendChild(g),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async C=>{var E,M;C.preventDefault();let L=(E=t.formEndpoint)!=null?E:"/form",D=new FormData(u),W={};D.forEach((O,j)=>{W[j]=O}),W.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let O=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!O.ok)throw new Error(`Form submission failed (${O.status})`);let j=await O.json();f.textContent=(M=j.message)!=null?M:"Thanks! We'll be in touch soon.",j.success&&j.nextPrompt&&await r.sendMessage(String(j.nextPrompt))}catch(O){f.textContent=O instanceof Error?O.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Ni=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},Ja=new Ni;var cu=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var oy=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},sy=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},Ka=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=oy(e),t=sy(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Fi=e=>typeof e=="string"?e:e==null?"":String(e),Yo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Fi(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=Fi(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Fi(t.text)}}},du=e=>Array.isArray(e)?e.map(n=>String(n)):[],Ga=e=>{let n=new Set(du(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(du(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var ay=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},iy=e=>e.map(n=>({...n,streaming:!1})),ly=e=>e.map(n=>({...n,status:"complete"})),Oi=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?ay(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?iy(t.messages):void 0,artifacts:t.artifacts?ly(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as cy,STR as dy,OBJ as py}from"partial-json";function uy(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function my(e,n){if(!uy(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function $i(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=cy(t,dy|py),o=my(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function gy(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _i(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=so.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function fy(){let e=$i();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ui(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ji(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var hy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function qi(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=hy}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,g.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,g.appendChild(x),f.appendChild(g);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];for(let M=1;M<=5;M++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-star-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`${M} star${M>1?"s":""}: ${l[M-1]}`),O.title=l[M-1],O.dataset.rating=String(M),O.innerHTML=`
|
|
19
|
+
`):""},fh=(e,n)=>{var u,p,f,g,v;let t=e.toolCall,r=(u=n==null?void 0:n.features)==null?void 0:u.toolCallDisplay,s=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",o=gh(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?op(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(g=n==null?void 0:n.toolCall)!=null?g:{},l=a;return s==="tool-name"?l=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=ai(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ai(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Fp=(e,n,t)=>{var u;let r=Ko.has(e),s=(u=t==null?void 0:t.toolCall)!=null?u:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=ge(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Ti=(e,n)=>{var K,ne,Se,We,_e,fe,pe,Te,je;let t=e.toolCall,r=(K=n==null?void 0:n.toolCall)!=null?K:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(Se=(ne=n==null?void 0:n.features)==null?void 0:ne.toolCallDisplay)!=null?Se:{},a=o.expandable!==!1,i=a&&Ko.has(e.id),{summary:d,previewText:l,isActive:u}=fh(e,n),p=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");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let v=String((We=t.startedAt)!=null?We:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",v),ee.textContent=vs(t),ee},k=(fe=r.renderCollapsedSummary)==null?void 0:fe.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(_e=o.collapsedMode)!=null?_e:"tool-call",isActive:u,config:n!=null?n:{},elapsed:vs(t),createElapsedElement:x});typeof k=="string"&&k.trim()?(g.textContent=k,f.appendChild(g)):k instanceof HTMLElement?f.appendChild(k):(g.textContent=d,f.appendChild(g));let w=(pe=o.loadingAnimation)!=null?pe:"none",L=r.activeTextTemplate,D=r.completeTextTemplate,W=u?L:D,E=k instanceof HTMLElement,M=(ee,xe,Q)=>{let re=Q;for(let Me of xe){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(re)),ae.textContent=Me===" "?"\xA0":Me,ee.appendChild(ae),re++}return re},O=(ee,xe)=>{var ae;g.textContent="";let Q=((ae=t.name)==null?void 0:ae.trim())||"tool",re=ma(ee,Q),Me=0;for(let Be of re){let Re=Be.styles.length>0?(()=>{let J=h("span",Be.styles.map(De=>`persona-tool-text-${De}`).join(" "));return g.appendChild(J),J})():g;if(Be.isDuration&&u)Re.appendChild(x());else{let J=Be.isDuration?vs(t):Be.text;xe?Me=M(Re,J,Me):Re.appendChild(document.createTextNode(J))}}};if(!E)if(u&&w!=="none"){let ee=(Te=r.loadingAnimationDuration)!=null?Te:2e3;if(g.setAttribute("data-preserve-animation","true"),w==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),W&&O(W,!1);else if(g.classList.add(`persona-tool-loading-${w}`),g.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),w==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),W)O(W,!0);else{let xe=g.textContent||d;g.textContent="",M(g,xe,0)}}else W&&O(W,!1);let U=null;if(a){U=h("div","persona-flex persona-items-center");let ee=r.toggleTextColor||r.headerTextColor||"currentColor",xe=ge(i?"chevron-up":"chevron-down",16,ee,2);xe?U.appendChild(xe):U.textContent=i?"Hide":"Show";let Q=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(U),p.append(f,Q)}else p.append(f);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&l){let ee=(je=r.renderCollapsedPreview)==null?void 0:je.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});mh($,ee)||($.textContent=l),$.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,$),s;let H=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),t.name){let ee=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ee.style.color=r.contentTextColor:r.headerTextColor&&(ee.style.color=r.headerTextColor),ee.textContent=t.name,H.appendChild(ee)}if(t.args!==void 0){let ee=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Arguments";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=Oo(t.args),ee.append(xe,Q),H.appendChild(ee)}if(t.chunks&&t.chunks.length){let ee=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Activity";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=t.chunks.join(""),ee.append(xe,Q),H.appendChild(ee)}if(t.status==="complete"&&t.result!==void 0){let ee=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Result";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=Oo(t.result),ee.append(xe,Q),H.appendChild(ee)}if(t.status==="complete"&&typeof t.duration=="number"){let ee=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ee.style.color=r.contentTextColor),ee.textContent=`Duration: ${t.duration}ms`,H.appendChild(ee)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),U){U.innerHTML="";let ee=r.toggleTextColor||r.headerTextColor||"currentColor",xe=ge(i?"chevron-up":"chevron-down",16,ee,2);xe?U.appendChild(xe):U.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(p,$,H),s};import{parse as hh,ARR as yh,OBJ as bh,STR as xh}from"partial-json";var $p="ask_user_question",ki=8,Go="data-persona-ask-sheet-for",vh="Other",Ch="Other\u2026",_p="Type your own answer here",jp="Send",wh="Next",Ah="Back",Sh="Submit all",Eh="Skip",Th=3,Mi="data-ask-current-index",Li="data-ask-question-count",Up="data-ask-answers",Pi="data-ask-grouped",qp="data-ask-layout",kh=e=>e.layout==="pills"?"pills":"rows",Mh=e=>e.getAttribute(qp)==="pills"?"pills":"rows",Op=!1,zp=e=>e.replace(/["\\]/g,"\\$&"),to=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===$p,ja=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},no=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=hh(s,xh|bh|yh);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},Os=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>ki&&!Op&&(Op=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${ki}.`)),n.slice(0,ki)},Lh=e=>{var n;return(n=Os(e)[0])!=null?n:null},Ph=(e,n)=>{var t;return(t=Os(e)[n])!=null?t:null},Vp=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Jp=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},Ih=(e,n,t,r)=>{let o=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(n)),o.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=Jp(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Wh=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},Rh=(e,n,t,r)=>{var u,p,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!t){for(let g=0;g<Th;g++)o.appendChild(Wh(r));return o}if(d.forEach((g,v)=>{o.appendChild(Ih(g,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?vh:Ch;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(u=n.freeTextPlaceholder)!=null?u:_p,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:g),x.appendChild(k),v.appendChild(x);let w=Jp(r,a,d.length);w&&v.appendChild(w),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=n.freeTextLabel)!=null?f:g,o.appendChild(v)}}return o},Kp=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:_p,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:jp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Hh=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:jp,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},Bh=(e,n,t)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=t.backLabel)!=null?l:Ah,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:Eh,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===n-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:Sh:(f=t.nextLabel)!=null?f:wh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},To=e=>{let n=e.getAttribute(Up);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Gp=(e,n)=>{e.setAttribute(Up,JSON.stringify(n))},Qn=e=>{var t;let n=Number((t=e.getAttribute(Mi))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},Dh=(e,n)=>{e.setAttribute(Mi,String(Math.max(0,Math.floor(n))))},Qo=e=>{var t;let n=Number((t=e.getAttribute(Li))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},ro=e=>e.getAttribute(Pi)==="true",Nh=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Fh=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},Ua=(e,n)=>{let{payload:t}=no(n),r=Os(t),s=To(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Qp=e=>{let n=To(e),t=Qn(e),r=n[t],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=s.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Xp=e=>{if(!ro(e))return;let n=To(e),t=Qn(e),r=n[t],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ii=(e,n,t)=>{let r=ja(t),s=Mh(e),{payload:o,complete:a}=no(n),i=ro(e),d=Qn(e),l=Qo(e),u=i?Ph(o,d):Lh(o),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=Rh(u,r,a,s);x.replaceWith(L)}if(s!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Kp(r,s))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!k?e.appendChild(Hh(r)):(!p||i)&&k&&k.remove(),e.setAttribute("data-multi-select",p?"true":"false");let w=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=Bh(d,l,r);w?w.replaceWith(L):e.appendChild(L)}else w&&w.remove();Qp(e),Xp(e)},Oh=(e,n,t)=>{let r=ja(n),s=kh(r),o=e.toolCall.id,a=Os(t),i=Math.max(1,a.length),d=i>1,l=Nh(e,a),u=d?Fh(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Go,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(Li,String(i)),p.setAttribute(Mi,String(u)),p.setAttribute(Pi,d?"true":"false"),p.setAttribute(qp,s),Gp(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Vp(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),p.appendChild(f);let k=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),p.appendChild(k),s!=="rows"&&p.appendChild(Kp(r,s)),Ii(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},$h=(e,n,t)=>{let{payload:r}=no(n),s=Math.max(1,Os(r).length);s>Qo(e)&&(e.setAttribute(Li,String(s)),s>1&&!ro(e)&&e.setAttribute(Pi,"true")),Ii(e,n,t)},_h=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=ja(n);Vp(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=no(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},$s=(e,n,t)=>{if(!t||!to(e)||ja(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${Go}]`).forEach(l=>{l.getAttribute(Go)!==s&&l.remove()});let a=t.querySelector(`[${Go}="${zp(s)}"]`);if(a){$h(a,e,n);return}let{payload:i}=no(e),d=Oh(e,n,i);t.appendChild(d)},ko=(e,n)=>{if(!e)return;let t=n?`[${Go}="${zp(n)}"]`:`[${Go}]`;e.querySelectorAll(t).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Wi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),oo=(e,n)=>{let t=To(e),r=Qn(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,Gp(e,t),Qp(e),Xp(e)},qa=(e,n,t,r)=>{let s=Qo(e),o=Math.max(0,Math.min(s-1,r));Dh(e,o),Ii(e,n,t)};var Ri=(e,n)=>{var x,k,w,L,D,W,E,M,O,U,$,H;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(k=r==null?void 0:r.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(w=r==null?void 0:r.titleColor)!=null?w:"currentColor",u=ge(d,20,l,2);u&&i.appendChild(u);let p=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(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(L=r==null?void 0:r.title)!=null?L:"Approval Required",f.appendChild(g),!s){let F=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",t.status),t.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):t.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):t.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),f.appendChild(F)}p.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=t.description,p.appendChild(v),t.parameters){let F=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(F.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(F.style.color=r.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=Oo(t.parameters),p.appendChild(F)}if(s){let F=h("div","persona-flex persona-gap-2 persona-mt-2");F.setAttribute("data-approval-buttons","true");let K=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");K.type="button",K.style.backgroundColor=(D=r==null?void 0:r.approveButtonColor)!=null?D:"var(--persona-approval-approve-bg, #22c55e)",K.style.color=(W=r==null?void 0:r.approveButtonTextColor)!=null?W:"#ffffff",K.setAttribute("data-approval-action","approve");let ne=ge("shield-check",14,(E=r==null?void 0:r.approveButtonTextColor)!=null?E:"#ffffff",2);ne&&(ne.style.marginRight="4px",K.appendChild(ne));let Se=document.createTextNode((M=r==null?void 0:r.approveLabel)!=null?M:"Approve");K.appendChild(Se);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=(O=r==null?void 0:r.denyButtonColor)!=null?O:"transparent",We.style.color=(U=r==null?void 0:r.denyButtonTextColor)!=null?U:"var(--persona-feedback-error, #dc2626)",We.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,We.setAttribute("data-approval-action","deny");let _e=ge("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);_e&&(_e.style.marginRight="4px",We.appendChild(_e));let fe=document.createTextNode((H=r==null?void 0:r.denyLabel)!=null?H:"Deny");We.appendChild(fe),F.append(K,We),p.appendChild(F)}return a.append(i,p),o.appendChild(a),o};var Yp=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let u=document.createDocumentFragment(),p=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'}};r.forEach(g=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=g,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),u.appendChild(v),n.push(v)}),e.appendChild(u)}}};var _s=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var js=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function Xo(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var jh={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)"}},Uh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},qh=["flowName","stepName","reasoningText","text","name","tool","toolName"],zh=100;function Vh(e,n){let t={...jh,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Uh}function Jh(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Kh(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function Gh(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Qh(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Xh(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Yh(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Hi(e,n,t,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Xo(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let g=u.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(p()),l;function p(){var K,ne;let g=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),k=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);k&&x.appendChild(k);let w=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(K=r.timestampFormat)!=null?K:"relative";w.textContent=L==="relative"?Jh(e.timestamp,t):Kh(e.timestamp);let D=null;r.showSequenceNumbers!==!1&&(D=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(n+1));let W=Vh(e.type,r.badgeColors),E=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");E.style.backgroundColor=W.bg,E.style.color=W.text,E.style.borderColor=W.text+"50",E.textContent=e.type;let M=(ne=r.descriptionFields)!=null?ne:qh,O=Gh(e.payload,M),U=null;O&&(U=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=O);let $=h("div","persona-flex-1 persona-min-w-0"),H=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"),F=ge("clipboard","12px","currentColor",1.5);return F&&H.appendChild(F),H.addEventListener("click",async Se=>{Se.stopPropagation(),await Qh(Xh(e)),H.innerHTML="";let We=ge("check","12px","currentColor",1.5);We&&H.appendChild(We),setTimeout(()=>{H.innerHTML="";let _e=ge("clipboard","12px","currentColor",1.5);_e&&H.appendChild(_e)},1500)}),v.appendChild(x),v.appendChild(w),D&&v.appendChild(D),v.appendChild(E),U&&v.appendChild(U),v.appendChild($),v.appendChild(H),g.appendChild(v),d&&g.appendChild(Yh(e,a,i)),g}}function Zp(e){var g,v,x,k,w;let{buffer:n,getFullHistory:t,onClose:r,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,d=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",l=(x=a==null?void 0:a.label)!=null?x:"",u=(w=(k=s==null?void 0:s.features)==null?void 0:k.eventStream)!=null?w:{},p=o.find(L=>L.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let L=p.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return f();function f(){let L=u.classNames,D=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Xo(D,L==null?void 0:L.panel);let W=[],E="",M="",O=null,U=[],$={},H=0,F=Ea(),K=0,ne=0,Se=!1,We=null,_e=!1,fe=0,pe=new Set,Te=new Map,je="",ee="",xe=null,Q,re,Me,ae,Be;function Re(){let R=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),se=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");Xo(se,L==null?void 0:L.headerBar);let Ce=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ce.textContent="Events",Q=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Q.textContent="0";let pt=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 Je=h("option","");Je.value="",Je.textContent="All events",re.appendChild(Je),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 ln=ge("clipboard-copy","12px","currentColor",1.5);ln&&Me.appendChild(ln);let Ct=h("span","persona-text-xs");Ct.textContent="Copy All",Me.appendChild(Ct),se.appendChild(Ce),se.appendChild(Q),se.appendChild(pt),se.appendChild(re),se.appendChild(Me);let ht=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Xo(ht,L==null?void 0:L.searchBar);let St=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),it=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");St&&it.appendChild(St),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"),Xo(ae,L==null?void 0:L.searchInput),ae.type="text",ae.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 Vt=ge("x","12px","currentColor",2);return Vt&&Be.appendChild(Vt),ht.appendChild(it),ht.appendChild(ae),ht.appendChild(Be),R.appendChild(se),R.appendChild(ht),R}let J,De=o.find(R=>R.renderEventStreamToolbar);if(De!=null&&De.renderEventStreamToolbar&&s){let R=De.renderEventStreamToolbar({config:s,defaultRenderer:()=>Re(),eventCount:n.getSize(),filteredCount:0,onFilterChange:se=>{E=se,Ne(),qt()},onSearchChange:se=>{M=se,Ne(),qt()}});J=R!=null?R:Re()}else J=Re();let He=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");He.style.display="none";let G=h("div","persona-flex-1 persona-min-h-0 persona-relative"),V=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");V.style.height="100%";let ve=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");Xo(ve,L==null?void 0:L.scrollIndicator),ve.style.display="none",ve.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let ce=ge(d,"14px","currentColor",2);ce&&ve.appendChild(ce);let te=h("span","");te.textContent=l,ve.appendChild(te);let me=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");me.style.display="none",G.appendChild(V),G.appendChild(me),G.appendChild(ve),D.setAttribute("tabindex","0"),D.appendChild(J),D.appendChild(He),D.appendChild(G);function Qe(){let R=n.getAll(),se={};for(let Ct of R)se[Ct.type]=(se[Ct.type]||0)+1;let Ce=Object.keys(se).sort(),pt=Ce.length!==U.length||!Ce.every((Ct,ht)=>Ct===U[ht]),Je=!pt&&Ce.some(Ct=>se[Ct]!==$[Ct]),Nt=R.length!==Object.values($).reduce((Ct,ht)=>Ct+ht,0);if(!pt&&!Je&&!Nt||(U=Ce,$=se,!re))return;let ln=re.value;if(re.options[0].textContent="All events",pt){for(;re.options.length>1;)re.remove(1);for(let Ct of Ce){let ht=h("option","");ht.value=Ct,ht.textContent=`${Ct} (${se[Ct]||0})`,re.appendChild(ht)}ln&&Ce.includes(ln)?re.value=ln:ln&&(re.value="",E="")}else for(let Ct=1;Ct<re.options.length;Ct++){let ht=re.options[Ct];ht.textContent=`${ht.value} (${se[ht.value]||0})`}}function Ft(){let R=n.getAll();if(E&&(R=R.filter(se=>se.type===E)),M){let se=M.toLowerCase();R=R.filter(Ce=>Ce.type.toLowerCase().includes(se)||Ce.payload.toLowerCase().includes(se))}return R}function ie(){return E!==""||M!==""}function Ne(){H=0,K=0,F.resume(),ve.style.display="none"}function an(R){pe.has(R)?pe.delete(R):pe.add(R),xe=R;let se=V.scrollTop,Ce=F.isFollowing();_e=!0,F.pause(),qt(),V.scrollTop=se,Ce&&F.resume(),_e=!1}function It(){return Ms(V,50)}function qt(){ne=Date.now(),Se=!1,Qe();let R=n.getEvictedCount();R>0?(He.textContent=`${R.toLocaleString()} older events truncated`,He.style.display=""):He.style.display="none",W=Ft();let se=W.length,Ce=n.getSize()>0;Q&&(Q.textContent=String(n.getSize())),se===0&&Ce&&ie()?(me.textContent=M?`No events matching '${M}'`:"No events matching filter",me.style.display="",V.style.display="none"):(me.style.display="none",V.style.display=""),Me&&(Me.title=ie()?`Copy Filtered (${se})`:"Copy All"),i&&!F.isFollowing()&&se>H&&(K+=se-H,te.textContent=l?`${l}${K>0?` (${K})`:""}`:"",ve.style.display=""),H=se;let pt=n.getAll(),Je=pt.length>0?pt[0].timestamp:0,Nt=new Set(W.map(ht=>ht.id));for(let ht of pe)Nt.has(ht)||pe.delete(ht);let ln=E!==je||M!==ee,Ct=Te.size===0&&W.length>0;if(ln||Ct||W.length===0){V.innerHTML="",Te.clear();let ht=document.createDocumentFragment();for(let St=0;St<W.length;St++){let it=Hi(W[St],St,Je,u,pe,an,o,s);Te.set(W[St].id,it),ht.appendChild(it)}V.appendChild(ht),je=E,ee=M,xe=null}else{if(xe!==null){let St=Te.get(xe);if(St&&St.parentNode===V){let it=W.findIndex(Vt=>Vt.id===xe);if(it>=0){let Vt=Hi(W[it],it,Je,u,pe,an,o,s);V.insertBefore(Vt,St),St.remove(),Te.set(xe,Vt)}}xe=null}let ht=new Set(W.map(St=>St.id));for(let[St,it]of Te)ht.has(St)||(it.remove(),Te.delete(St));for(let St=0;St<W.length;St++){let it=W[St];if(!Te.has(it.id)){let Vt=Hi(it,St,Je,u,pe,an,o,s);Te.set(it.id,Vt),V.appendChild(Vt)}}}F.isFollowing()&&(V.scrollTop=V.scrollHeight)}function vr(){if(Date.now()-ne>=zh){We!==null&&(cancelAnimationFrame(We),We=null),qt();return}Se||(Se=!0,We=requestAnimationFrame(()=>{We=null,qt()}))}let dr=(R,se)=>{if(!Me)return;Me.innerHTML="";let Ce=ge(R,"12px","currentColor",1.5);Ce&&Me.appendChild(Ce);let pt=h("span","persona-text-xs");pt.textContent="Copy All",Me.appendChild(pt),setTimeout(()=>{Me.innerHTML="";let Je=ge("clipboard-copy","12px","currentColor",1.5);Je&&Me.appendChild(Je);let Nt=h("span","persona-text-xs");Nt.textContent="Copy All",Me.appendChild(Nt),Me.disabled=!1},se)},P=async()=>{if(Me){Me.disabled=!0;try{let R;ie()?R=W:t?(R=await t(),R.length===0&&(R=n.getAll())):R=n.getAll();let se=R.map(Ce=>{try{return JSON.parse(Ce.payload)}catch{return Ce.payload}});await navigator.clipboard.writeText(JSON.stringify(se,null,2)),dr("check",1500)}catch{dr("x",1500)}}},oe=()=>{re&&(E=re.value,Ne(),qt())},Pe=()=>{!ae||!Be||(Be.style.display=ae.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{M=ae.value,Ne(),qt()},150))},qe=()=>{!ae||!Be||(ae.value="",M="",Be.style.display="none",O&&clearTimeout(O),Ne(),qt())},Fe=()=>{if(_e)return;let R=V.scrollTop,{action:se,nextLastScrollTop:Ce}=Ta({following:F.isFollowing(),currentScrollTop:R,lastScrollTop:fe,nearBottom:It(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});fe=Ce,se==="resume"?(F.resume(),K=0,ve.style.display="none"):se==="pause"&&(F.pause(),i&&(te.textContent=l,ve.style.display=""))},Oe=R=>{let se=ka({following:F.isFollowing(),deltaY:R.deltaY,nearBottom:It(),resumeWhenNearBottom:!0});se==="pause"?(F.pause(),i&&(te.textContent=l,ve.style.display="")):se==="resume"&&(F.resume(),K=0,ve.style.display="none")},Ze=()=>{i&&(V.scrollTop=V.scrollHeight,F.resume(),K=0,ve.style.display="none")},vt=R=>{let se=R.target;if(!se||se.closest("button"))return;let Ce=se.closest("[data-event-id]");if(!Ce)return;let pt=Ce.getAttribute("data-event-id");pt&&an(pt)},Ot=R=>{if((R.metaKey||R.ctrlKey)&&R.key==="f"){R.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}R.key==="Escape"&&(ae&&document.activeElement===ae?(qe(),ae.blur(),D.focus()):r&&r())};Me&&Me.addEventListener("click",P),re&&re.addEventListener("change",oe),ae&&ae.addEventListener("input",Pe),Be&&Be.addEventListener("click",qe),V.addEventListener("scroll",Fe),V.addEventListener("wheel",Oe,{passive:!0}),V.addEventListener("click",vt),ve.addEventListener("click",Ze),D.addEventListener("keydown",Ot);function zt(){O&&clearTimeout(O),We!==null&&(cancelAnimationFrame(We),We=null),Se=!1,Te.clear(),Me&&Me.removeEventListener("click",P),re&&re.removeEventListener("change",oe),ae&&ae.removeEventListener("input",Pe),Be&&Be.removeEventListener("click",qe),V.removeEventListener("scroll",Fe),V.removeEventListener("wheel",Oe),V.removeEventListener("click",vt),ve.removeEventListener("click",Ze),D.removeEventListener("keydown",Ot)}return{element:D,update:vr,destroy:zt}}}function eu(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.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",p.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(g)}else p.textContent=a;if(l.append(u,p),i.append(d,l),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",r),i.append(f)}return i}var tu=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>eu(e,n)});if(u)return u}return eu(e,n)};var Bi=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},so=new Bi;so.register("PersonaArtifactCard",tu);function Zh(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function nu(e,n){var Me,ae,Be,Re;let t=(ae=(Me=e.features)==null?void 0:Me.artifacts)==null?void 0:ae.layout,s=((Be=t==null?void 0:t.toolbarPreset)!=null?Be:"default")==="document",o=(Re=t==null?void 0:t.panePadding)==null?void 0:Re.trim(),a=e.markdown?No(e.markdown):null,i=bs(e.sanitize),d=J=>{let De=a?a(J):Fo(J);return i?i(De):De},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let p=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");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.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 v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let x="rendered",k=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),w=s?_t({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):_t({icon:"eye",label:"Rendered view"}),L=s?_t({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):_t({icon:"code-2",label:"Source"}),D=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),W=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,E=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,M=t==null?void 0:t.documentToolbarCopyMenuItems,O=!!(E&&M&&M.length>0),U=null,$,H=null,F=null;if(s&&(W||E)&&!O){if($=W?Ha({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E){let J=ge("chevron-down",14,"currentColor",2);J&&$.appendChild(J)}}else s&&O?(U=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=W?Ha({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=_t({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"}}),U.append($,H)):s?$=_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=_t({icon:"copy",label:"Copy"});let K=s?_t({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):_t({icon:"refresh-cw",label:"Refresh"}),ne=s?_t({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):_t({icon:"x",label:"Close"}),Se=()=>{var V,ve,ce;let J=(V=je.find(te=>te.id===ee))!=null?V:je[je.length-1],De=(ve=J==null?void 0:J.id)!=null?ve:null,He=(J==null?void 0:J.artifactType)==="markdown"&&(ce=J.markdown)!=null?ce:"",G=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:He,jsonPayload:G,id:De}},We=async()=>{var V;let{markdown:J,jsonPayload:De}=Se(),He=(V=je.find(ve=>ve.id===ee))!=null?V:je[je.length-1],G=(He==null?void 0:He.artifactType)==="markdown"?J:He?De:"";try{await navigator.clipboard.writeText(G)}catch{}};if($.addEventListener("click",async()=>{let J=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(J&&O){let{markdown:De,jsonPayload:He,id:G}=Se();try{await J({actionId:"primary",artifactId:G,markdown:De,jsonPayload:He})}catch{}return}await We()}),H&&(M!=null&&M.length)){let J=()=>{var He;return(He=p.closest("[data-persona-root]"))!=null?He:document.body},De=()=>{F=Eo({items:M.map(He=>({id:He.id,label:He.label})),onSelect:async He=>{let{markdown:G,jsonPayload:V,id:ve}=Se(),ce=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ce?await ce({actionId:He,artifactId:ve,markdown:G,jsonPayload:V}):He==="markdown"||He==="md"?await navigator.clipboard.writeText(G):He==="json"||He==="source"?await navigator.clipboard.writeText(V):await navigator.clipboard.writeText(G||V)}catch{}},anchor:U!=null?U:H,position:"bottom-right",portal:J()})};p.isConnected?De():requestAnimationFrame(De),H.addEventListener("click",He=>{He.stopPropagation(),F==null||F.toggle()})}K.addEventListener("click",async()=>{var J;try{await((J=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:J.call(t))}catch{}Q()}),ne.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let _e=()=>{s&&(w.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};w.addEventListener("click",()=>{x="rendered",_e(),Q()}),L.addEventListener("click",()=>{x="source",_e(),Q()});let fe=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(),k.append(w,L),U?D.append(U,K,ne):D.append($,K,ne),f.append(k,fe,D),_e()):(f.appendChild(g),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let pe=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"),Te=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(pe.style.paddingLeft=o,pe.style.paddingRight=o,Te.style.padding=o),p.appendChild(f),p.appendChild(pe),p.appendChild(Te);let je=[],ee=null,xe=!1,Q=()=>{var G,V,ve,ce;let J=s&&je.length<=1;pe.classList.toggle("persona-hidden",J),pe.replaceChildren();for(let te of je){let me=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");me.type="button",me.textContent=te.title||te.id.slice(0,8),te.id===ee&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>n.onSelect(te.id)),pe.appendChild(me)}Te.replaceChildren();let De=ee&&je.find(te=>te.id===ee)||je[je.length-1];if(!De)return;if(s){let te=De.artifactType==="markdown"?"MD":(G=De.component)!=null?G:"Component",Qe=(De.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";fe.textContent=`${Qe} \xB7 ${te}`}else g.textContent="Artifacts";if(De.artifactType==="markdown"){if(s&&x==="source"){let me=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(V=De.markdown)!=null?V:"",Te.appendChild(me);return}let te=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");te.innerHTML=d((ve=De.markdown)!=null?ve:""),Te.appendChild(te);return}let He=De.component?so.get(De.component):void 0;if(He){let me={message:{id:De.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Qe=He((ce=De.props)!=null?ce:{},me);if(Qe){Te.appendChild(Qe);return}}catch{}}Te.appendChild(Zh(De))},re=()=>{var De;let J=je.length>0;if(p.classList.toggle("persona-hidden",!J),l){let He=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,V=((De=He==null?void 0:He.classList.contains("persona-artifact-narrow-host"))!=null?De:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&V&&xe?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(J){var De,He,G;je=J.artifacts,ee=(G=(He=J.selectedId)!=null?He:(De=J.artifacts[J.artifacts.length-1])==null?void 0:De.id)!=null?G:null,je.length>0&&(xe=!0),Q(),re()},setMobileOpen(J){xe=J,!J&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):re()}}}function Xn(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function ru(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Xn(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function ey(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 za(e,n){var d,l,u,p,f,g,v,x,k,w;if(!Xn(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),ey(e),ru(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"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 r=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(k=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:k.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(w=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:w.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ru(e,n)}var ou=["panel","seamless"];function Va(e,n){var i,d,l,u,p,f;for(let g of ou)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"),!Xn(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=ou.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.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 su(e,n){var t,r,s;return!n||!Xn(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function ty(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function ny(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function ry(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function oy(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function au(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function iu(e,n,t,r,s,o){let a=ty(s,200),i=oy(n,t,r,200);i=Math.max(a,i);let d=ny(o);return d!==null&&(i=Math.min(i,d)),ry(e,a,i)}var lu={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"}},Di=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,k;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=lu[a])!=null?x:lu.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let w=h("p","persona-text-sm persona-text-persona-muted");w.textContent=i.description,d.appendChild(w)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(w=>{var M,O;let L=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${n.id}-${a}-${w.name}`;let D=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=w.label,L.appendChild(D);let W=(M=w.type)!=null?M:"text",E;W==="textarea"?(E=document.createElement("textarea"),E.rows=3):(E=document.createElement("input"),E.type=W),E.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",E.id=`${n.id}-${a}-${w.name}`,E.name=w.name,E.placeholder=(O=w.placeholder)!=null?O:"",w.required&&(E.required=!0),L.appendChild(E),u.appendChild(L)});let p=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=(k=i.submitLabel)!=null?k:"Submit",p.appendChild(f),p.appendChild(g),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async w=>{var E,M;w.preventDefault();let L=(E=t.formEndpoint)!=null?E:"/form",D=new FormData(u),W={};D.forEach((O,U)=>{W[U]=O}),W.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let O=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!O.ok)throw new Error(`Form submission failed (${O.status})`);let U=await O.json();f.textContent=(M=U.message)!=null?M:"Thanks! We'll be in touch soon.",U.success&&U.nextPrompt&&await r.sendMessage(String(U.nextPrompt))}catch(O){f.textContent=O instanceof Error?O.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Ni=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},Ja=new Ni;var cu=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var sy=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},ay=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},Ka=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=sy(e),t=ay(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Fi=e=>typeof e=="string"?e:e==null?"":String(e),Yo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Fi(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=Fi(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Fi(t.text)}}},du=e=>Array.isArray(e)?e.map(n=>String(n)):[],Ga=e=>{let n=new Set(du(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(du(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var iy=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},ly=e=>e.map(n=>({...n,streaming:!1})),cy=e=>e.map(n=>({...n,status:"complete"})),Oi=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?iy(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?ly(t.messages):void 0,artifacts:t.artifacts?cy(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as dy,STR as py,OBJ as uy}from"partial-json";function my(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function gy(e,n){if(!my(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function $i(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=dy(t,py|uy),o=gy(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function fy(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _i(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=so.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function hy(){let e=$i();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function pu(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function ji(e){let n=pu(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Ui(e){let n=pu(e);if(!n)return null;try{let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:n}}}catch{}return null}var yy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function qi(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=yy}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,g.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,g.appendChild(x),f.appendChild(g);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let w=[];for(let M=1;M<=5;M++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-star-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`${M} star${M>1?"s":""}: ${l[M-1]}`),O.title=l[M-1],O.dataset.rating=String(M),O.innerHTML=`
|
|
20
20
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
21
21
|
<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>
|
|
22
22
|
</svg>
|
|
23
|
-
`,O.addEventListener("click",()=>{p=M,C.forEach((j,$)=>{let H=$<M;j.classList.toggle("selected",H),j.setAttribute("aria-checked",$===M-1?"true":"false")})}),C.push(O),k.appendChild(O)}f.appendChild(k);let L=null;if(d){let M=document.createElement("div");M.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=o,L.rows=3,L.setAttribute("aria-label","Additional comments"),M.appendChild(L),f.appendChild(M)}let D=document.createElement("div");D.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(),u.remove()});let E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=a,E.addEventListener("click",async()=>{if(p===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let M=(L==null?void 0:L.value.trim())||void 0;await n(p,M),u.remove()}catch(M){E.disabled=!1,E.textContent=a,console.error("[CSAT Feedback] Failed to submit:",M)}}),D.appendChild(W),D.appendChild(E),f.appendChild(D),u.appendChild(f),u}function zi(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=s,v.appendChild(k),g.appendChild(v);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-nps",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=l;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=u,L.appendChild(D),L.appendChild(W);let E=document.createElement("div");E.className="persona-feedback-numbers";let M=[];for(let F=0;F<=10;F++){let K=document.createElement("button");K.type="button",K.className="persona-feedback-rating-btn persona-feedback-number-btn",K.setAttribute("role","radio"),K.setAttribute("aria-checked","false"),K.setAttribute("aria-label",`Rating ${F} out of 10`),K.textContent=String(F),K.dataset.rating=String(F),F<=6?K.classList.add("persona-feedback-detractor"):F<=8?K.classList.add("persona-feedback-passive"):K.classList.add("persona-feedback-promoter"),K.addEventListener("click",()=>{f=F,M.forEach((ne,Se)=>{ne.classList.toggle("selected",Se===F),ne.setAttribute("aria-checked",Se===F?"true":"false")})}),M.push(K),E.appendChild(K)}C.appendChild(L),C.appendChild(E),g.appendChild(C);let O=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=o,O.rows=3,O.setAttribute("aria-label","Additional comments"),F.appendChild(O),g.appendChild(F)}let j=document.createElement("div");j.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{t==null||t(),p.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(f===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let F=(O==null?void 0:O.value.trim())||void 0;await n(f,F),p.remove()}catch(F){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),j.appendChild($),j.appendChild(H),g.appendChild(j),p.appendChild(g),p}var Zo="persona-chat-history",yy=30*1e3,by={"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 xy(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=by[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function Qa(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function vy(e){var n,t,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function wy(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var Vi=e=>!e||typeof e!="object"?{}:{...e},pu=e=>e.map(n=>({...n,streaming:!1})),uu=(e,n,t)=>{let r=e!=null&&e.markdown?No(e.markdown):null,s=bs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,u,p;let a=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let f=n.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 d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=Fo(a),s?s(d):d}};function mu(e){var i,d,l,u;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=ge(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,n.appendChild(p)}return n}var Ji=(e,n,t)=>{var al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,wl,Cl,Al,Sl,El,Tl,kl,Ml,Ll,Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,Ul,jl,ql,zl,Vl,Jl,Kl,Gl,Ql,Xl,Yl;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=gi(n),s=Ja.getForInstance(r.plugins);r.components&&so.registerAll(r.components);let o=cu(),i=r.persistState===!1?null:(al=r.storageAdapter)!=null?al:Oi(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:b}=m;return b&&(u=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=c!=null?c:{messages:[],metadata:{}},y=p(m);y.metadata&&(d=Vi(y.metadata)),(il=y.messages)!=null&&il.length&&(r={...r,initialMessages:y.messages}),(ll=y.artifacts)!=null&&ll.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(cl=y.selectedArtifactId)!=null?cl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=p({messages:[],metadata:{}});(dl=c.messages)!=null&&dl.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,g=c=>{var y;d=(y=c({...d}))!=null?y:{},Po()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ka],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Yo.message,Yo.messageAndClick],k=Ga({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let C=(ul=(pl=r.launcher)==null?void 0:pl.enabled)!=null?ul:!0,L=(gl=(ml=r.launcher)==null?void 0:ml.autoExpand)!=null?gl:!1,D=(fl=r.autoFocusInput)!=null?fl:!1,W=L,E=C,M=(yl=(hl=r.layout)==null?void 0:hl.header)==null?void 0:yl.layout,O=!1,j=()=>Zr(r),$=()=>C||j(),H=j()?!1:C?L:!0,F=!1,K=null,ne=()=>{F=!0,K&&clearTimeout(K),K=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},Se=uu(r,k,ne),We=(xl=(bl=r.features)==null?void 0:bl.showReasoning)!=null?xl:!0,_e=(wl=(vl=r.features)==null?void 0:vl.showToolCalls)!=null?wl:!0,fe=(Al=(Cl=r.features)==null?void 0:Cl.showEventStreamToggle)!=null?Al:!1,pe=(El=(Sl=r.features)==null?void 0:Sl.scrollToBottom)!=null?El:{},Ue=`${(kl=typeof r.persistState=="object"?(Tl=r.persistState)==null?void 0:Tl.keyPrefix:void 0)!=null?kl:"persona-"}event-stream`,ee=fe?new Us(Ue):null,xe=(Pl=(Ll=(Ml=r.features)==null?void 0:Ml.eventStream)==null?void 0:Ll.maxEvents)!=null?Pl:2e3,Q=fe?new _s(xe,ee):null,re=null,Me=!1,ae=null,Be=0;ee==null||ee.open().then(()=>Q==null?void 0:Q.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Re={onCopy:c=>{var m,y;o.emit("message:copy",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onCopy)==null||y.call(m,c)},onFeedback:c=>{var m,y;o.emit("message:feedback",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,c)}},J=(Il=r.statusIndicator)!=null?Il:{},De=c=>{var m,y,b,T;return c==="idle"?(m=J.idleText)!=null?m:fn.idle:c==="connecting"?(y=J.connectingText)!=null?y:fn.connecting:c==="connected"?(b=J.connectedText)!=null?b:fn.connected:c==="error"?(T=J.errorText)!=null?T:fn.error:fn[c]};function He(c,m,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let T=document.createElement("a");T.href=y.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=m,T.style.color="inherit",T.style.textDecoration="none",c.appendChild(T)}else c.textContent=m}let{wrapper:G,panel:V,pillRoot:ve}=Wp(r),ce=Rp(r,$()),{container:te,body:me,messagesWrapper:Qe,suggestions:Ft,textarea:ie,sendButton:Ne,sendButtonWrapper:an,composerForm:Pt,statusText:qt,introTitle:vr,introSubtitle:dr,closeButton:P,iconHolder:oe,headerTitle:Pe,headerSubtitle:qe,header:Fe,footer:Oe,actionsRow:Ze,leftActions:vt,rightActions:Ot}=ce,zt=ce.setSendButtonMode,R=ce.micButton,se=ce.micButtonWrapper,we=ce.attachmentButton,pt=ce.attachmentButtonWrapper,Je=ce.attachmentInput,Nt=ce.attachmentPreviewsContainer;te.classList.add("persona-relative"),me.classList.add("persona-relative");let ln=12,wt=()=>{var c;return(c=pe.label)!=null?c:""},ht=()=>{var c;return(c=pe.iconName)!=null?c:"arrow-down"},St=()=>pe.enabled!==!1,it=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");it.type="button",it.style.display="none",it.setAttribute("data-persona-scroll-to-bottom","true");let Vt=h("span","persona-flex persona-items-center"),wr=h("span","");it.append(Vt,wr),te.appendChild(it);let Un=()=>{let m=Oe.style.display==="none"?0:Oe.offsetHeight;it.style.bottom=`${m+ln}px`};Un();let Dr=()=>{let c=!!wt();it.setAttribute("aria-label",wt()||"Jump to latest"),it.title=wt(),it.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Vt.innerHTML="";let m=ge(ht(),"14px","currentColor",2);m?(Vt.appendChild(m),Vt.style.display=""):Vt.style.display="none",wr.textContent=wt(),wr.style.display=c?"":"none"};Dr();let xt=null,pr=null,ur=s.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:r,defaultRenderer:()=>{let m=eo({config:r,showClose:$()});return zo(te,m,r),m.header},onClose:()=>It(!1,"user")});if(c){let m=te.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Fe=c)}}let Cr=()=>{var m,y,b,T;if(!Q)return;if(Me=!0,!re&&Q&&(re=Zp({buffer:Q,getFullHistory:()=>Q.getAllFromStore(),onClose:()=>Yn(),config:r,plugins:s})),re&&(me.style.display="none",(m=Oe.parentNode)==null||m.insertBefore(re.element,Oe),re.update()),ct){ct.style.boxShadow=`inset 0 0 0 1.5px ${Sn.actionIconColor}`;let B=(T=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;B&&B.split(/\s+/).forEach(N=>N&&ct.classList.add(N))}let c=()=>{if(!Me)return;let B=Date.now();B-Be>=200&&(re==null||re.update(),Be=B),ae=requestAnimationFrame(c)};Be=0,ae=requestAnimationFrame(c),Mr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Yn=()=>{var c,m,y;if(Me){if(Me=!1,re&&re.element.remove(),me.style.display="",ct){ct.style.boxShadow="";let b=(y=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&ct.classList.remove(T))}ae!==null&&(cancelAnimationFrame(ae),ae=null),Mr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},ct=null;if(fe){let c=(Rl=(Wl=r.features)==null?void 0:Wl.eventStream)==null?void 0:Rl.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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ct=h("button",m),ct.style.width="28px",ct.style.height="28px",ct.style.color=Sn.actionIconColor,ct.type="button",ct.setAttribute("aria-label","Event Stream"),ct.title="Event Stream";let y=ge("activity","18px","currentColor",1.5);y&&ct.appendChild(y);let b=ce.clearChatButtonWrapper,T=ce.closeButtonWrapper,B=b||T;B&&B.parentNode===Fe?Fe.insertBefore(ct,B):Fe.appendChild(ct),ct.addEventListener("click",()=>{Me?Yn():Cr()})}let io=c=>{var b,T,B;let m=r.attachments;if(!(m!=null&&m.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(y,N):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=h("input");N.type="file",N.accept=((b=m.allowedTypes)!=null?b:Hr).join(","),N.multiple=((T=m.maxFiles)!=null?T:4)>1,N.style.display="none",N.setAttribute("aria-label",(B=m.buttonTooltipText)!=null?B:"Attach files"),c.appendChild(N)}},mr=s.find(c=>c.renderComposer);if(mr!=null&&mr.renderComposer){let c=r.composer,m=mr.renderComposer({config:r,defaultRenderer:()=>Ns({config:r}).footer,onSubmit:y=>{var N;if(!_||_.isStreaming())return;let b=y.trim(),T=(N=xt==null?void 0:xt.hasAttachments())!=null?N:!1;if(!b&&!T)return;ds();let B;T&&(B=[],B.push(...xt.getContentParts()),b&&B.push(ya(b))),_.sendMessage(b,{contentParts:B}),T&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Je==null||Je.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((Hl=r.voiceRecognition)==null?void 0:Hl.enabled)===!0?()=>{pr==null||pr()}:void 0});m&&(Oe.replaceWith(m),Oe=m)}let lo=c=>{let m=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),T=c.querySelector("[data-persona-composer-mic]"),B=c.querySelector("[data-persona-composer-status]");m&&(Pt=m),y&&(ie=y),b&&(Ne=b),T&&(R=T,se=T.parentElement),B&&(qt=B);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Ft=N);let z=c.querySelector(".persona-attachment-button");z&&(we=z,pt=z.parentElement),Je=c.querySelector('input[type="file"]'),Nt=c.querySelector(".persona-attachment-previews");let I=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");I&&(Ze=I)};io(Oe),lo(Oe);let En=(Ol=(Bl=r.layout)==null?void 0:Bl.contentMaxWidth)!=null?Ol:j()?(Fl=(Nl=(Dl=r.launcher)==null?void 0:Dl.composerBar)==null?void 0:Nl.contentMaxWidth)!=null?Fl:"720px":void 0;if(En&&(Qe.style.maxWidth=En,Qe.style.marginLeft="auto",Qe.style.marginRight="auto",Qe.style.width="100%"),En&&Pt&&!j()&&(Pt.style.maxWidth=En,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),En&&Ft&&!j()&&(Ft.style.maxWidth=En,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),En&&Nt&&!j()&&(Nt.style.maxWidth=En,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),($l=r.attachments)!=null&&$l.enabled&&Je&&Nt){xt=jo.fromConfig(r.attachments),xt.setPreviewsContainer(Nt),Je.addEventListener("change",y=>{let b=y.target;xt==null||xt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=mu(c);te.appendChild(m)}(()=>{var b,T;let c=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},m=B=>{switch(B){case"body-top":return te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Qe;case"footer-top":return Ft;case"composer":return Pt;case"footer-bottom":return qt;default:return null}},y=(B,N)=>{var z;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")Fe.insertBefore(N,Fe.firstChild);else if(B==="header-right")Fe.appendChild(N);else{let I=Fe.querySelector(".persona-flex-col");I?(z=I.parentNode)==null||z.insertBefore(N,I.nextSibling):Fe.appendChild(N)}break;case"body-top":{let I=me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(N):me.insertBefore(N,me.firstChild);break}case"body-bottom":me.appendChild(N);break;case"footer-top":Ft.replaceWith(N);break;case"footer-bottom":qt.replaceWith(N);break;default:break}};for(let[B,N]of Object.entries(c))if(N)try{let z=N({config:r,defaultContent:()=>m(B)});z&&y(B,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,z)}})();let Nr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let B=y.getAttribute("data-bubble-type");B==="reasoning"?(Jo.has(T)?Jo.delete(T):Jo.add(T),Np(T,b)):B==="tool"&&(Ko.has(T)?Ko.delete(T):Ko.add(T),Fp(T,b,r)),Fn.delete(T)};Qe.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Nr(c))}),Qe.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Nr(c))});let Ar=new Map;Qe.addEventListener("click",c=>{var N;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let B=y.getAttribute("data-action");if(B==="copy"){let I=_.getMessages().find(ye=>ye.id===T);if(I&&Re.onCopy){let ye=I.content||"";navigator.clipboard.writeText(ye).then(()=>{y.classList.add("persona-message-action-success");let le=ge("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Y=ge("copy",14,"currentColor",2);Y&&(y.innerHTML="",y.appendChild(Y))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),Re.onCopy(I)}}else if(B==="upvote"||B==="downvote"){let I=((N=Ar.get(T))!=null?N:null)===B,ye=B==="upvote"?"thumbs-up":"thumbs-down";if(I){Ar.delete(T),y.classList.remove("persona-message-action-active");let le=ge(ye,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=B==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${le}"]`);if(Y){Y.classList.remove("persona-message-action-active");let ze=ge(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Y.innerHTML="",Y.appendChild(ze))}Ar.set(T,B),y.classList.add("persona-message-action-active");let ue=ge(ye,14,"currentColor",2);ue&&(ue.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ue)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ie=_.getMessages().find(Ye=>Ye.id===T);Ie&&Re.onFeedback&&Re.onFeedback({type:B,messageId:Ie.id,message:Ie})}}}),Qe.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let B=y.getAttribute("data-approval-action");if(!B)return;let N=B==="approve"?"approved":"denied",I=_.getMessages().find(le=>le.id===T);if(!(I!=null&&I.approval))return;let ye=b.querySelector("[data-approval-buttons]");ye&&ye.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),_.resolveApproval(I.approval,N)});let mt=null,In=null,Wn={artifacts:[],selectedId:null},yn=!1,Et={current:null};Qe.addEventListener("click",c=>{var Y,ue,be,Ie,Ye;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((be=(ue=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ue.onArtifactAction)==null?void 0:be.call(ue,{type:"download",artifactId:b}))===!0)return;let B=_.getArtifactById(b),N=B==null?void 0:B.markdown,z=(B==null?void 0:B.title)||"artifact";if(!N){let ze=y.closest("[data-open-artifact]"),nt=ze==null?void 0:ze.closest("[data-message-id]"),rt=nt==null?void 0:nt.getAttribute("data-message-id");if(rt){let Ae=_.getMessages().find($e=>$e.id===rt);if(Ae!=null&&Ae.rawContent)try{let $e=JSON.parse(Ae.rawContent);N=(Ie=$e==null?void 0:$e.props)==null?void 0:Ie.markdown,z=((Ye=$e==null?void 0:$e.props)==null?void 0:Ye.title)||z}catch{}}}if(!N)return;let I=new Blob([N],{type:"text/markdown"}),ye=URL.createObjectURL(I),le=document.createElement("a");le.href=ye,le.download=`${z}.md`,le.click(),URL.revokeObjectURL(ye)}),Qe.addEventListener("click",c=>{var B,N,z;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((z=(N=(B=r.features)==null?void 0:B.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:z.call(N,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),yn=!1,_.selectArtifact(b),Bn())}),Qe.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let jn=ce.composerOverlay,qn=(c,m,y)=>{var z,I,ye,le;let b=m.trim();if(!b||!Et.current)return;let T=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",B=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:y.structured,values:(I=y.values)!=null?I:y.source==="multi"?b.split(", "):[b],isFreeText:B,source:y.source},bubbles:!0,composed:!0})),ko(jn,T);let N=Et.current.getMessages().find(Y=>{var ue;return((ue=Y.toolCall)==null?void 0:ue.id)===T});(ye=N==null?void 0:N.agentMetadata)!=null&&ye.awaitingLocalTool?Et.current.resolveAskUserQuestion(N,(le=y.structured)!=null?le:b):Et.current.sendMessage(b)},Rn=c=>{var T;let m=Et.current;if(!m)return;let y=(T=c.getAttribute("data-tool-call-id"))!=null?T:"",b=m.getMessages().find(B=>{var N;return((N=B.toolCall)==null?void 0:N.id)===y});b&&m.persistAskUserQuestionProgress(b,{answers:ja(c,b),currentIndex:Qn(c)})},Fr=c=>Object.entries(c).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Sr=c=>{var T,B,N;if(((B=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let m=Qn(c),y=Qo(c);if(m>=y-1)return;let b=(N=Et.current)==null?void 0:N.getMessages().find(z=>{var I;return((I=z.toolCall)==null?void 0:I.id)===c.getAttribute("data-tool-call-id")});b&&(qa(c,b,r,m+1),Rn(c))};jn.addEventListener("click",c=>{var B,N,z,I,ye,le,Y,ue,be,Ie,Ye,ze,nt,rt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),T==="dismiss"){let Ee=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ee},bubbles:!0,composed:!0})),ko(jn,Ee);let Ae=(N=Et.current)==null?void 0:N.getMessages().find($e=>{var S;return((S=$e.toolCall)==null?void 0:S.id)===Ee});(z=Ae==null?void 0:Ae.agentMetadata)!=null&&z.awaitingLocalTool&&((I=Et.current)==null||I.markAskUserQuestionResolved(Ae),(ye=Et.current)==null||ye.resolveAskUserQuestion(Ae,"(dismissed)"));return}if(T==="pick"){let Ee=y.getAttribute("data-option-label");if(!Ee)return;let Ae=b.getAttribute("data-multi-select")==="true",$e=ro(b);if($e&&Ae){let S=To(b)[Qn(b)],Ce=new Set(Array.isArray(S)?S:[]);Ce.has(Ee)?Ce.delete(Ee):Ce.add(Ee),oo(b,Array.from(Ce)),Rn(b);return}if($e){oo(b,Ee),Rn(b),Sr(b);return}if(Ae){let S=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",S?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!S);let Ce=b.querySelector('[data-ask-user-action="submit-multi"]');Ce&&(Ce.disabled=Wi(b).length===0);return}qn(b,Ee,{source:"pick",values:[Ee]});return}if(T==="submit-multi"){let Ee=Wi(b);if(Ee.length===0)return;qn(b,Ee.join(", "),{source:"multi",values:Ee});return}if(T==="open-free-text"){let Ee=b.querySelector('[data-ask-free-text-row="true"]');if(Ee){Ee.classList.remove("persona-hidden");let Ae=Ee.querySelector('[data-ask-free-text-input="true"]');Ae==null||Ae.focus()}return}if(T==="focus-free-text"){let Ee=b.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus();return}if(T==="submit-free-text"){let Ee=b.querySelector('[data-ask-free-text-input="true"]'),Ae=(le=Ee==null?void 0:Ee.value)!=null?le:"";if(!Ae.trim())return;if(ro(b)){oo(b,Ae.trim()),Rn(b),Sr(b);return}qn(b,Ae,{source:"free-text"});return}if(T==="next"||T==="back"){if(!Et.current)return;let Ee=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",Ae=Et.current.getMessages().find(je=>{var he;return((he=je.toolCall)==null?void 0:he.id)===Ee});if(!Ae)return;let $e=b.querySelector('[data-ask-free-text-input="true"]'),S=(be=(ue=$e==null?void 0:$e.value)==null?void 0:ue.trim())!=null?be:"";if(S){let je=To(b)[Qn(b)];(typeof je!="string"||je!==S)&&oo(b,S)}let Ce=T==="next"?1:-1,Le=Qn(b)+Ce;qa(b,Ae,r,Le),Rn(b);return}if(T==="submit-all"){if(!Et.current)return;let Ee=(Ie=b.getAttribute("data-tool-call-id"))!=null?Ie:"",Ae=Et.current.getMessages().find(je=>{var he;return((he=je.toolCall)==null?void 0:he.id)===Ee});if(!Ae)return;let $e=b.querySelector('[data-ask-free-text-input="true"]'),S=(ze=(Ye=$e==null?void 0:$e.value)==null?void 0:Ye.trim())!=null?ze:"";S&&oo(b,S);let Ce=ja(b,Ae);Et.current.persistAskUserQuestionProgress(Ae,{answers:Ce,currentIndex:Qn(b)});let Le=Fr(Ce);qn(b,Le||"(submitted)",{source:"submit-all",structured:Ce});return}if(T==="skip"){if(!Et.current)return;let Ee=(nt=b.getAttribute("data-tool-call-id"))!=null?nt:"",Ae=Et.current.getMessages().find(he=>{var At;return((At=he.toolCall)==null?void 0:At.id)===Ee});if(!Ae)return;let $e=ro(b),S=Qn(b),Ce=Qo(b),Le=S>=Ce-1;if(!$e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ee},bubbles:!0,composed:!0})),ko(jn,Ee),(rt=Ae.agentMetadata)!=null&&rt.awaitingLocalTool&&(Et.current.markAskUserQuestionResolved(Ae),Et.current.resolveAskUserQuestion(Ae,"(dismissed)"));return}oo(b,"");let je=b.querySelector('[data-ask-free-text-input="true"]');if(je&&(je.value=""),Le){let he=ja(b,Ae),At=Fr(he);qn(b,At||"(skipped)",{source:"submit-all",structured:he});return}qa(b,Ae,r,S+1),Rn(b);return}}),jn.addEventListener("keydown",c=>{var B;if(c.key!=="Enter")return;let y=c.target;if(!((B=y.matches)!=null&&B.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let T=y.value;if(T.trim()){if(ro(b)){oo(b,T.trim()),Rn(b),Sr(b);return}qn(b,T,{source:"free-text"})}});let Or=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let y=jn.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),B=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];B&&(c.preventDefault(),B.click())};document.addEventListener("keydown",Or);let Hn=null,kt=null,bn=null,zn=null,$r=()=>{};function Er(){zn==null||zn(),zn=null}let _r=()=>{var N;if(!Hn||!kt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){kt.style.removeProperty("position"),kt.style.removeProperty("left"),kt.style.removeProperty("top"),kt.style.removeProperty("bottom"),kt.style.removeProperty("width"),kt.style.removeProperty("z-index");return}let b=Hn.firstElementChild;if(!b||b===kt)return;let T=10;kt.style.position="absolute",kt.style.top="0",kt.style.bottom="0",kt.style.width=`${T}px`,kt.style.zIndex="5";let B=b.offsetWidth-T/2;kt.style.left=`${Math.max(0,B)}px`},gr=()=>{},Bn=()=>{var y,b,T,B,N;if(!mt||!Xn(r))return;za(e,r),Va(e,r),gr();let c=(B=(T=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?B:520,m=V.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),mt.update(Wn),yn?(mt.setMobileOpen(!1),mt.element.classList.add("persona-hidden"),(N=mt.backdrop)==null||N.classList.add("persona-hidden")):Wn.artifacts.length>0&&(mt.element.classList.remove("persona-hidden"),mt.setMobileOpen(!0)),$r()};if(Xn(r)){V.style.position="relative";let c=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");c.appendChild(te),mt=nu(r,{onSelect:y=>{var b;return(b=Et.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{yn=!0,Bn()}}),mt.element.classList.add("persona-hidden"),Hn=m,m.appendChild(c),m.appendChild(mt.element),mt.backdrop&&V.appendChild(mt.backdrop),V.appendChild(m),$r=()=>{var b,T,B,N;if(!Hn||!mt)return;if(!(((B=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:B.resizable)===!0)){bn==null||bn(),bn=null,Er(),kt&&(kt.remove(),kt=null),mt.element.style.removeProperty("width"),mt.element.style.removeProperty("maxWidth");return}if(!kt){let z=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let I=e.ownerDocument,ye=(N=I.defaultView)!=null?N:window,le=Y=>{var nt,rt;if(!mt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||ye.innerWidth<=640)return;Y.preventDefault(),Er();let ue=Y.clientX,be=mt.element.getBoundingClientRect().width,Ie=(rt=(nt=r.features)==null?void 0:nt.artifacts)==null?void 0:rt.layout,Ye=Ee=>{let Ae=Hn.getBoundingClientRect().width,$e=e.classList.contains("persona-artifact-appearance-seamless"),S=$e?0:au(Hn,ye),Ce=$e?0:z.getBoundingClientRect().width||6,Le=be-(Ee.clientX-ue),je=iu(Le,Ae,S,Ce,Ie==null?void 0:Ie.resizableMinWidth,Ie==null?void 0:Ie.resizableMaxWidth);mt.element.style.width=`${je}px`,mt.element.style.maxWidth="none",_r()},ze=()=>{I.removeEventListener("pointermove",Ye),I.removeEventListener("pointerup",ze),I.removeEventListener("pointercancel",ze),zn=null;try{z.releasePointerCapture(Y.pointerId)}catch{}};zn=ze,I.addEventListener("pointermove",Ye),I.addEventListener("pointerup",ze),I.addEventListener("pointercancel",ze);try{z.setPointerCapture(Y.pointerId)}catch{}};z.addEventListener("pointerdown",le),kt=z,Hn.insertBefore(z,mt.element),bn=()=>{z.removeEventListener("pointerdown",le)}}if(kt){let z=Wn.artifacts.length>0&&!yn;kt.classList.toggle("persona-hidden",!z),_r()}},gr=()=>{var ye,le,Y,ue,be,Ie,Ye,ze,nt,rt,Ee,Ae,$e,S;if(!C||!mt||((le=(ye=r.launcher)==null?void 0:ye.sidebarMode)!=null?le:!1)||on(r)&&lr(r).reveal==="emerge")return;let b=(Y=e.ownerDocument.defaultView)!=null?Y:window,T=(be=(ue=r.launcher)==null?void 0:ue.mobileFullscreen)!=null?be:!0,B=(Ye=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Ye:640;if(T&&b.innerWidth<=B||!su(r,C))return;let N=(rt=(nt=(ze=r.launcher)==null?void 0:ze.width)!=null?nt:r.launcherWidth)!=null?rt:Gn,z=(S=($e=(Ae=(Ee=r.features)==null?void 0:Ee.artifacts)==null?void 0:Ae.layout)==null?void 0:$e.expandedPanelWidth)!=null?S:"min(720px, calc(100vw - 24px))";Wn.artifacts.length>0&&!yn?(V.style.width=z,V.style.maxWidth=z):(V.style.width=N,V.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(In=new ResizeObserver(()=>{Bn()}),In.observe(V))}else V.appendChild(te),j()&&ve&&(ce.peekBanner&&ve.appendChild(ce.peekBanner),ve.appendChild(Oe));e.appendChild(G),ve&&e.appendChild(ve);let Zn=()=>{var je,he,At,tt,Xt,dn,Tt,vn,pn,Ge,ot,wn,mn,fo,ho,yo,Bo,Do,Ut,bo,Qr,ut,kn,Wr,Cn,Mn,Wt,$t;if(j()){V.style.width="100%",V.style.maxWidth="100%";let Rt=(he=(je=r.launcher)==null?void 0:je.composerBar)!=null?he:{},jt=G.dataset.state==="expanded",Ln=(At=Rt.expandedSize)!=null?At:"anchored";if(!(jt&&Ln!=="fullscreen")){te.style.background="",te.style.border="",te.style.borderRadius="",te.style.overflow="",te.style.boxShadow="";return}let en=(Xt=(tt=r.theme)==null?void 0:tt.components)==null?void 0:Xt.panel,yr=Ts(r),Rr=(xo,la)=>{var fs;return xo==null||xo===""?la:(fs=qo(yr,xo))!=null?fs:xo},sa="1px solid var(--persona-border)",aa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ia="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";te.style.background="var(--persona-surface, #ffffff)",te.style.border=Rr(en==null?void 0:en.border,sa),te.style.borderRadius=Rr(en==null?void 0:en.borderRadius,ia),te.style.boxShadow=Rr(en==null?void 0:en.shadow,aa),te.style.overflow="hidden";return}let c=on(r),m=(Tt=(dn=r.launcher)==null?void 0:dn.sidebarMode)!=null?Tt:!1,y=c||m||((pn=(vn=r.launcher)==null?void 0:vn.fullHeight)!=null?pn:!1),b=((Ge=r.launcher)==null?void 0:Ge.enabled)===!1,T=(wn=(ot=r.theme)==null?void 0:ot.components)==null?void 0:wn.panel,B=Ts(r),N=(Rt,jt)=>{var Ln;return Rt==null||Rt===""?jt:(Ln=qo(B,Rt))!=null?Ln:Rt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,I=(ho=(fo=r.launcher)==null?void 0:fo.mobileFullscreen)!=null?ho:!0,ye=(Bo=(yo=r.launcher)==null?void 0:yo.mobileBreakpoint)!=null?Bo:640,le=z.innerWidth<=ye,Y=I&&le&&C,ue=(Ut=(Do=r.launcher)==null?void 0:Do.position)!=null?Ut:"bottom-left",be=ue==="bottom-left"||ue==="top-left",Ie=(Qr=(bo=r.launcher)==null?void 0:bo.zIndex)!=null?Qr:hn,Ye=m||Y?"none":"1px solid var(--persona-border)",ze=Y?"none":m?be?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Y&&(ze="none",Ye="none");let nt=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",rt=N(T==null?void 0:T.border,Ye),Ee=N(T==null?void 0:T.shadow,ze),Ae=N(T==null?void 0:T.borderRadius,nt),$e=me.scrollTop;e.style.cssText="",G.style.cssText="",V.style.cssText="",te.style.cssText="",me.style.cssText="",Oe.style.cssText="";let S=()=>{var jt;if($e<=0)return;((jt=me.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(me.scrollTop===$e)return;let Ln=me.scrollHeight-me.clientHeight;Ln<=0||(me.scrollTop=Math.min($e,Ln))})};if(Y){G.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),G.style.cssText=`
|
|
23
|
+
`,O.addEventListener("click",()=>{p=M,w.forEach((U,$)=>{let H=$<M;U.classList.toggle("selected",H),U.setAttribute("aria-checked",$===M-1?"true":"false")})}),w.push(O),k.appendChild(O)}f.appendChild(k);let L=null;if(d){let M=document.createElement("div");M.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=o,L.rows=3,L.setAttribute("aria-label","Additional comments"),M.appendChild(L),f.appendChild(M)}let D=document.createElement("div");D.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(),u.remove()});let E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=a,E.addEventListener("click",async()=>{if(p===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let M=(L==null?void 0:L.value.trim())||void 0;await n(p,M),u.remove()}catch(M){E.disabled=!1,E.textContent=a,console.error("[CSAT Feedback] Failed to submit:",M)}}),D.appendChild(W),D.appendChild(E),f.appendChild(D),u.appendChild(f),u}function zi(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=s,v.appendChild(k),g.appendChild(v);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-nps",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=l;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=u,L.appendChild(D),L.appendChild(W);let E=document.createElement("div");E.className="persona-feedback-numbers";let M=[];for(let F=0;F<=10;F++){let K=document.createElement("button");K.type="button",K.className="persona-feedback-rating-btn persona-feedback-number-btn",K.setAttribute("role","radio"),K.setAttribute("aria-checked","false"),K.setAttribute("aria-label",`Rating ${F} out of 10`),K.textContent=String(F),K.dataset.rating=String(F),F<=6?K.classList.add("persona-feedback-detractor"):F<=8?K.classList.add("persona-feedback-passive"):K.classList.add("persona-feedback-promoter"),K.addEventListener("click",()=>{f=F,M.forEach((ne,Se)=>{ne.classList.toggle("selected",Se===F),ne.setAttribute("aria-checked",Se===F?"true":"false")})}),M.push(K),E.appendChild(K)}w.appendChild(L),w.appendChild(E),g.appendChild(w);let O=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=o,O.rows=3,O.setAttribute("aria-label","Additional comments"),F.appendChild(O),g.appendChild(F)}let U=document.createElement("div");U.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{t==null||t(),p.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(f===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let F=(O==null?void 0:O.value.trim())||void 0;await n(f,F),p.remove()}catch(F){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),U.appendChild($),U.appendChild(H),g.appendChild(U),p.appendChild(g),p}var Zo="persona-chat-history",by=30*1e3,xy={"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 vy(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=xy[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function Qa(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function Cy(e){var n,t,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function wy(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var Vi=e=>!e||typeof e!="object"?{}:{...e},uu=e=>e.map(n=>({...n,streaming:!1})),mu=(e,n,t)=>{let r=e!=null&&e.markdown?No(e.markdown):null,s=bs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,u,p;let a=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let f=n.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 d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=Fo(a),s?s(d):d}};function gu(e){var i,d,l,u;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=ge(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,n.appendChild(p)}return n}var Ji=(e,n,t)=>{var al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Al,Sl,El,Tl,kl,Ml,Ll,Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,Ul,ql,zl,Vl,Jl,Kl,Gl,Ql,Xl,Yl;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=gi(n),s=Ja.getForInstance(r.plugins);r.components&&so.registerAll(r.components);let o=cu(),i=r.persistState===!1?null:(al=r.storageAdapter)!=null?al:Oi(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:b}=m;return b&&(u=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=c!=null?c:{messages:[],metadata:{}},y=p(m);y.metadata&&(d=Vi(y.metadata)),(il=y.messages)!=null&&il.length&&(r={...r,initialMessages:y.messages}),(ll=y.artifacts)!=null&&ll.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(cl=y.selectedArtifactId)!=null?cl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=p({messages:[],metadata:{}});(dl=c.messages)!=null&&dl.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,g=c=>{var y;d=(y=c({...d}))!=null?y:{},Po()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ka],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Yo.message,Yo.messageAndClick],k=Ga({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let w=(ul=(pl=r.launcher)==null?void 0:pl.enabled)!=null?ul:!0,L=(gl=(ml=r.launcher)==null?void 0:ml.autoExpand)!=null?gl:!1,D=(fl=r.autoFocusInput)!=null?fl:!1,W=L,E=w,M=(yl=(hl=r.layout)==null?void 0:hl.header)==null?void 0:yl.layout,O=!1,U=()=>Zr(r),$=()=>w||U(),H=U()?!1:w?L:!0,F=!1,K=null,ne=()=>{F=!0,K&&clearTimeout(K),K=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},Se=mu(r,k,ne),We=(xl=(bl=r.features)==null?void 0:bl.showReasoning)!=null?xl:!0,_e=(Cl=(vl=r.features)==null?void 0:vl.showToolCalls)!=null?Cl:!0,fe=(Al=(wl=r.features)==null?void 0:wl.showEventStreamToggle)!=null?Al:!1,pe=(El=(Sl=r.features)==null?void 0:Sl.scrollToBottom)!=null?El:{},je=`${(kl=typeof r.persistState=="object"?(Tl=r.persistState)==null?void 0:Tl.keyPrefix:void 0)!=null?kl:"persona-"}event-stream`,ee=fe?new js(je):null,xe=(Pl=(Ll=(Ml=r.features)==null?void 0:Ml.eventStream)==null?void 0:Ll.maxEvents)!=null?Pl:2e3,Q=fe?new _s(xe,ee):null,re=null,Me=!1,ae=null,Be=0;ee==null||ee.open().then(()=>Q==null?void 0:Q.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Re={onCopy:c=>{var m,y;o.emit("message:copy",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onCopy)==null||y.call(m,c)},onFeedback:c=>{var m,y;o.emit("message:feedback",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,c)}},J=(Il=r.statusIndicator)!=null?Il:{},De=c=>{var m,y,b,T;return c==="idle"?(m=J.idleText)!=null?m:fn.idle:c==="connecting"?(y=J.connectingText)!=null?y:fn.connecting:c==="connected"?(b=J.connectedText)!=null?b:fn.connected:c==="error"?(T=J.errorText)!=null?T:fn.error:fn[c]};function He(c,m,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let T=document.createElement("a");T.href=y.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=m,T.style.color="inherit",T.style.textDecoration="none",c.appendChild(T)}else c.textContent=m}let{wrapper:G,panel:V,pillRoot:ve}=Wp(r),ce=Rp(r,$()),{container:te,body:me,messagesWrapper:Qe,suggestions:Ft,textarea:ie,sendButton:Ne,sendButtonWrapper:an,composerForm:It,statusText:qt,introTitle:vr,introSubtitle:dr,closeButton:P,iconHolder:oe,headerTitle:Pe,headerSubtitle:qe,header:Fe,footer:Oe,actionsRow:Ze,leftActions:vt,rightActions:Ot}=ce,zt=ce.setSendButtonMode,R=ce.micButton,se=ce.micButtonWrapper,Ce=ce.attachmentButton,pt=ce.attachmentButtonWrapper,Je=ce.attachmentInput,Nt=ce.attachmentPreviewsContainer;te.classList.add("persona-relative"),me.classList.add("persona-relative");let ln=12,Ct=()=>{var c;return(c=pe.label)!=null?c:""},ht=()=>{var c;return(c=pe.iconName)!=null?c:"arrow-down"},St=()=>pe.enabled!==!1,it=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");it.type="button",it.style.display="none",it.setAttribute("data-persona-scroll-to-bottom","true");let Vt=h("span","persona-flex persona-items-center"),Cr=h("span","");it.append(Vt,Cr),te.appendChild(it);let jn=()=>{let m=Oe.style.display==="none"?0:Oe.offsetHeight;it.style.bottom=`${m+ln}px`};jn();let Dr=()=>{let c=!!Ct();it.setAttribute("aria-label",Ct()||"Jump to latest"),it.title=Ct(),it.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Vt.innerHTML="";let m=ge(ht(),"14px","currentColor",2);m?(Vt.appendChild(m),Vt.style.display=""):Vt.style.display="none",Cr.textContent=Ct(),Cr.style.display=c?"":"none"};Dr();let xt=null,pr=null,ur=s.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:r,defaultRenderer:()=>{let m=eo({config:r,showClose:$()});return zo(te,m,r),m.header},onClose:()=>Mt(!1,"user")});if(c){let m=te.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Fe=c)}}let wr=()=>{var m,y,b,T;if(!Q)return;if(Me=!0,!re&&Q&&(re=Zp({buffer:Q,getFullHistory:()=>Q.getAllFromStore(),onClose:()=>Yn(),config:r,plugins:s})),re&&(me.style.display="none",(m=Oe.parentNode)==null||m.insertBefore(re.element,Oe),re.update()),ct){ct.style.boxShadow=`inset 0 0 0 1.5px ${Sn.actionIconColor}`;let B=(T=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;B&&B.split(/\s+/).forEach(N=>N&&ct.classList.add(N))}let c=()=>{if(!Me)return;let B=Date.now();B-Be>=200&&(re==null||re.update(),Be=B),ae=requestAnimationFrame(c)};Be=0,ae=requestAnimationFrame(c),Mr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Yn=()=>{var c,m,y;if(Me){if(Me=!1,re&&re.element.remove(),me.style.display="",ct){ct.style.boxShadow="";let b=(y=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&ct.classList.remove(T))}ae!==null&&(cancelAnimationFrame(ae),ae=null),Mr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},ct=null;if(fe){let c=(Rl=(Wl=r.features)==null?void 0:Wl.eventStream)==null?void 0:Rl.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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ct=h("button",m),ct.style.width="28px",ct.style.height="28px",ct.style.color=Sn.actionIconColor,ct.type="button",ct.setAttribute("aria-label","Event Stream"),ct.title="Event Stream";let y=ge("activity","18px","currentColor",1.5);y&&ct.appendChild(y);let b=ce.clearChatButtonWrapper,T=ce.closeButtonWrapper,B=b||T;B&&B.parentNode===Fe?Fe.insertBefore(ct,B):Fe.appendChild(ct),ct.addEventListener("click",()=>{Me?Yn():wr()})}let io=c=>{var b,T,B;let m=r.attachments;if(!(m!=null&&m.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(y,N):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=h("input");N.type="file",N.accept=((b=m.allowedTypes)!=null?b:Hr).join(","),N.multiple=((T=m.maxFiles)!=null?T:4)>1,N.style.display="none",N.setAttribute("aria-label",(B=m.buttonTooltipText)!=null?B:"Attach files"),c.appendChild(N)}},mr=s.find(c=>c.renderComposer);if(mr!=null&&mr.renderComposer){let c=r.composer,m=mr.renderComposer({config:r,defaultRenderer:()=>Ns({config:r}).footer,onSubmit:y=>{var N;if(!_||_.isStreaming())return;let b=y.trim(),T=(N=xt==null?void 0:xt.hasAttachments())!=null?N:!1;if(!b&&!T)return;ds();let B;T&&(B=[],B.push(...xt.getContentParts()),b&&B.push(ya(b))),_.sendMessage(b,{contentParts:B}),T&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Je==null||Je.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((Hl=r.voiceRecognition)==null?void 0:Hl.enabled)===!0?()=>{pr==null||pr()}:void 0});m&&(Oe.replaceWith(m),Oe=m)}let lo=c=>{let m=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),T=c.querySelector("[data-persona-composer-mic]"),B=c.querySelector("[data-persona-composer-status]");m&&(It=m),y&&(ie=y),b&&(Ne=b),T&&(R=T,se=T.parentElement),B&&(qt=B);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Ft=N);let z=c.querySelector(".persona-attachment-button");z&&(Ce=z,pt=z.parentElement),Je=c.querySelector('input[type="file"]'),Nt=c.querySelector(".persona-attachment-previews");let I=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");I&&(Ze=I)};io(Oe),lo(Oe);let En=(Ol=(Bl=r.layout)==null?void 0:Bl.contentMaxWidth)!=null?Ol:U()?(Fl=(Nl=(Dl=r.launcher)==null?void 0:Dl.composerBar)==null?void 0:Nl.contentMaxWidth)!=null?Fl:"720px":void 0;if(En&&(Qe.style.maxWidth=En,Qe.style.marginLeft="auto",Qe.style.marginRight="auto",Qe.style.width="100%"),En&&It&&!U()&&(It.style.maxWidth=En,It.style.marginLeft="auto",It.style.marginRight="auto"),En&&Ft&&!U()&&(Ft.style.maxWidth=En,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),En&&Nt&&!U()&&(Nt.style.maxWidth=En,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),($l=r.attachments)!=null&&$l.enabled&&Je&&Nt){xt=Uo.fromConfig(r.attachments),xt.setPreviewsContainer(Nt),Je.addEventListener("change",y=>{let b=y.target;xt==null||xt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=gu(c);te.appendChild(m)}(()=>{var b,T;let c=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},m=B=>{switch(B){case"body-top":return te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Qe;case"footer-top":return Ft;case"composer":return It;case"footer-bottom":return qt;default:return null}},y=(B,N)=>{var z;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")Fe.insertBefore(N,Fe.firstChild);else if(B==="header-right")Fe.appendChild(N);else{let I=Fe.querySelector(".persona-flex-col");I?(z=I.parentNode)==null||z.insertBefore(N,I.nextSibling):Fe.appendChild(N)}break;case"body-top":{let I=me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(N):me.insertBefore(N,me.firstChild);break}case"body-bottom":me.appendChild(N);break;case"footer-top":Ft.replaceWith(N);break;case"footer-bottom":qt.replaceWith(N);break;default:break}};for(let[B,N]of Object.entries(c))if(N)try{let z=N({config:r,defaultContent:()=>m(B)});z&&y(B,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,z)}})();let Nr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let B=y.getAttribute("data-bubble-type");B==="reasoning"?(Jo.has(T)?Jo.delete(T):Jo.add(T),Np(T,b)):B==="tool"&&(Ko.has(T)?Ko.delete(T):Ko.add(T),Fp(T,b,r)),Fn.delete(T)};Qe.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Nr(c))}),Qe.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Nr(c))});let Ar=new Map;Qe.addEventListener("click",c=>{var N;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let B=y.getAttribute("data-action");if(B==="copy"){let I=_.getMessages().find(ye=>ye.id===T);if(I&&Re.onCopy){let ye=I.content||"";navigator.clipboard.writeText(ye).then(()=>{y.classList.add("persona-message-action-success");let le=ge("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Y=ge("copy",14,"currentColor",2);Y&&(y.innerHTML="",y.appendChild(Y))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),Re.onCopy(I)}}else if(B==="upvote"||B==="downvote"){let I=((N=Ar.get(T))!=null?N:null)===B,ye=B==="upvote"?"thumbs-up":"thumbs-down";if(I){Ar.delete(T),y.classList.remove("persona-message-action-active");let le=ge(ye,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=B==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${le}"]`);if(Y){Y.classList.remove("persona-message-action-active");let ze=ge(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Y.innerHTML="",Y.appendChild(ze))}Ar.set(T,B),y.classList.add("persona-message-action-active");let ue=ge(ye,14,"currentColor",2);ue&&(ue.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ue)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ie=_.getMessages().find(Ye=>Ye.id===T);Ie&&Re.onFeedback&&Re.onFeedback({type:B,messageId:Ie.id,message:Ie})}}}),Qe.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let B=y.getAttribute("data-approval-action");if(!B)return;let N=B==="approve"?"approved":"denied",I=_.getMessages().find(le=>le.id===T);if(!(I!=null&&I.approval))return;let ye=b.querySelector("[data-approval-buttons]");ye&&ye.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),_.resolveApproval(I.approval,N)});let mt=null,In=null,Wn={artifacts:[],selectedId:null},yn=!1,Et={current:null};Qe.addEventListener("click",c=>{var Y,ue,be,Ie,Ye;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((be=(ue=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ue.onArtifactAction)==null?void 0:be.call(ue,{type:"download",artifactId:b}))===!0)return;let B=_.getArtifactById(b),N=B==null?void 0:B.markdown,z=(B==null?void 0:B.title)||"artifact";if(!N){let ze=y.closest("[data-open-artifact]"),nt=ze==null?void 0:ze.closest("[data-message-id]"),rt=nt==null?void 0:nt.getAttribute("data-message-id");if(rt){let Ae=_.getMessages().find($e=>$e.id===rt);if(Ae!=null&&Ae.rawContent)try{let $e=JSON.parse(Ae.rawContent);N=(Ie=$e==null?void 0:$e.props)==null?void 0:Ie.markdown,z=((Ye=$e==null?void 0:$e.props)==null?void 0:Ye.title)||z}catch{}}}if(!N)return;let I=new Blob([N],{type:"text/markdown"}),ye=URL.createObjectURL(I),le=document.createElement("a");le.href=ye,le.download=`${z}.md`,le.click(),URL.revokeObjectURL(ye)}),Qe.addEventListener("click",c=>{var B,N,z;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((z=(N=(B=r.features)==null?void 0:B.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:z.call(N,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),yn=!1,_.selectArtifact(b),Bn())}),Qe.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let Un=ce.composerOverlay,qn=(c,m,y)=>{var z,I,ye,le;let b=m.trim();if(!b||!Et.current)return;let T=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",B=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:y.structured,values:(I=y.values)!=null?I:y.source==="multi"?b.split(", "):[b],isFreeText:B,source:y.source},bubbles:!0,composed:!0})),ko(Un,T);let N=Et.current.getMessages().find(Y=>{var ue;return((ue=Y.toolCall)==null?void 0:ue.id)===T});(ye=N==null?void 0:N.agentMetadata)!=null&&ye.awaitingLocalTool?Et.current.resolveAskUserQuestion(N,(le=y.structured)!=null?le:b):Et.current.sendMessage(b)},Rn=c=>{var T;let m=Et.current;if(!m)return;let y=(T=c.getAttribute("data-tool-call-id"))!=null?T:"",b=m.getMessages().find(B=>{var N;return((N=B.toolCall)==null?void 0:N.id)===y});b&&m.persistAskUserQuestionProgress(b,{answers:Ua(c,b),currentIndex:Qn(c)})},Fr=c=>Object.entries(c).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Sr=c=>{var T,B,N;if(((B=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let m=Qn(c),y=Qo(c);if(m>=y-1)return;let b=(N=Et.current)==null?void 0:N.getMessages().find(z=>{var I;return((I=z.toolCall)==null?void 0:I.id)===c.getAttribute("data-tool-call-id")});b&&(qa(c,b,r,m+1),Rn(c))};Un.addEventListener("click",c=>{var B,N,z,I,ye,le,Y,ue,be,Ie,Ye,ze,nt,rt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),T==="dismiss"){let Ee=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ee},bubbles:!0,composed:!0})),ko(Un,Ee);let Ae=(N=Et.current)==null?void 0:N.getMessages().find($e=>{var S;return((S=$e.toolCall)==null?void 0:S.id)===Ee});(z=Ae==null?void 0:Ae.agentMetadata)!=null&&z.awaitingLocalTool&&((I=Et.current)==null||I.markAskUserQuestionResolved(Ae),(ye=Et.current)==null||ye.resolveAskUserQuestion(Ae,"(dismissed)"));return}if(T==="pick"){let Ee=y.getAttribute("data-option-label");if(!Ee)return;let Ae=b.getAttribute("data-multi-select")==="true",$e=ro(b);if($e&&Ae){let S=To(b)[Qn(b)],we=new Set(Array.isArray(S)?S:[]);we.has(Ee)?we.delete(Ee):we.add(Ee),oo(b,Array.from(we)),Rn(b);return}if($e){oo(b,Ee),Rn(b),Sr(b);return}if(Ae){let S=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",S?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!S);let we=b.querySelector('[data-ask-user-action="submit-multi"]');we&&(we.disabled=Wi(b).length===0);return}qn(b,Ee,{source:"pick",values:[Ee]});return}if(T==="submit-multi"){let Ee=Wi(b);if(Ee.length===0)return;qn(b,Ee.join(", "),{source:"multi",values:Ee});return}if(T==="open-free-text"){let Ee=b.querySelector('[data-ask-free-text-row="true"]');if(Ee){Ee.classList.remove("persona-hidden");let Ae=Ee.querySelector('[data-ask-free-text-input="true"]');Ae==null||Ae.focus()}return}if(T==="focus-free-text"){let Ee=b.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus();return}if(T==="submit-free-text"){let Ee=b.querySelector('[data-ask-free-text-input="true"]'),Ae=(le=Ee==null?void 0:Ee.value)!=null?le:"";if(!Ae.trim())return;if(ro(b)){oo(b,Ae.trim()),Rn(b),Sr(b);return}qn(b,Ae,{source:"free-text"});return}if(T==="next"||T==="back"){if(!Et.current)return;let Ee=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",Ae=Et.current.getMessages().find(Ue=>{var he;return((he=Ue.toolCall)==null?void 0:he.id)===Ee});if(!Ae)return;let $e=b.querySelector('[data-ask-free-text-input="true"]'),S=(be=(ue=$e==null?void 0:$e.value)==null?void 0:ue.trim())!=null?be:"";if(S){let Ue=To(b)[Qn(b)];(typeof Ue!="string"||Ue!==S)&&oo(b,S)}let we=T==="next"?1:-1,Le=Qn(b)+we;qa(b,Ae,r,Le),Rn(b);return}if(T==="submit-all"){if(!Et.current)return;let Ee=(Ie=b.getAttribute("data-tool-call-id"))!=null?Ie:"",Ae=Et.current.getMessages().find(Ue=>{var he;return((he=Ue.toolCall)==null?void 0:he.id)===Ee});if(!Ae)return;let $e=b.querySelector('[data-ask-free-text-input="true"]'),S=(ze=(Ye=$e==null?void 0:$e.value)==null?void 0:Ye.trim())!=null?ze:"";S&&oo(b,S);let we=Ua(b,Ae);Et.current.persistAskUserQuestionProgress(Ae,{answers:we,currentIndex:Qn(b)});let Le=Fr(we);qn(b,Le||"(submitted)",{source:"submit-all",structured:we});return}if(T==="skip"){if(!Et.current)return;let Ee=(nt=b.getAttribute("data-tool-call-id"))!=null?nt:"",Ae=Et.current.getMessages().find(he=>{var At;return((At=he.toolCall)==null?void 0:At.id)===Ee});if(!Ae)return;let $e=ro(b),S=Qn(b),we=Qo(b),Le=S>=we-1;if(!$e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ee},bubbles:!0,composed:!0})),ko(Un,Ee),(rt=Ae.agentMetadata)!=null&&rt.awaitingLocalTool&&(Et.current.markAskUserQuestionResolved(Ae),Et.current.resolveAskUserQuestion(Ae,"(dismissed)"));return}oo(b,"");let Ue=b.querySelector('[data-ask-free-text-input="true"]');if(Ue&&(Ue.value=""),Le){let he=Ua(b,Ae),At=Fr(he);qn(b,At||"(skipped)",{source:"submit-all",structured:he});return}qa(b,Ae,r,S+1),Rn(b);return}}),Un.addEventListener("keydown",c=>{var B;if(c.key!=="Enter")return;let y=c.target;if(!((B=y.matches)!=null&&B.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let T=y.value;if(T.trim()){if(ro(b)){oo(b,T.trim()),Rn(b),Sr(b);return}qn(b,T,{source:"free-text"})}});let Or=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let y=Un.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),B=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];B&&(c.preventDefault(),B.click())};document.addEventListener("keydown",Or);let Hn=null,kt=null,bn=null,zn=null,$r=()=>{};function Er(){zn==null||zn(),zn=null}let _r=()=>{var N;if(!Hn||!kt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){kt.style.removeProperty("position"),kt.style.removeProperty("left"),kt.style.removeProperty("top"),kt.style.removeProperty("bottom"),kt.style.removeProperty("width"),kt.style.removeProperty("z-index");return}let b=Hn.firstElementChild;if(!b||b===kt)return;let T=10;kt.style.position="absolute",kt.style.top="0",kt.style.bottom="0",kt.style.width=`${T}px`,kt.style.zIndex="5";let B=b.offsetWidth-T/2;kt.style.left=`${Math.max(0,B)}px`},gr=()=>{},Bn=()=>{var y,b,T,B,N;if(!mt||!Xn(r))return;za(e,r),Va(e,r),gr();let c=(B=(T=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?B:520,m=V.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),mt.update(Wn),yn?(mt.setMobileOpen(!1),mt.element.classList.add("persona-hidden"),(N=mt.backdrop)==null||N.classList.add("persona-hidden")):Wn.artifacts.length>0&&(mt.element.classList.remove("persona-hidden"),mt.setMobileOpen(!0)),$r()};if(Xn(r)){V.style.position="relative";let c=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");c.appendChild(te),mt=nu(r,{onSelect:y=>{var b;return(b=Et.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{yn=!0,Bn()}}),mt.element.classList.add("persona-hidden"),Hn=m,m.appendChild(c),m.appendChild(mt.element),mt.backdrop&&V.appendChild(mt.backdrop),V.appendChild(m),$r=()=>{var b,T,B,N;if(!Hn||!mt)return;if(!(((B=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:B.resizable)===!0)){bn==null||bn(),bn=null,Er(),kt&&(kt.remove(),kt=null),mt.element.style.removeProperty("width"),mt.element.style.removeProperty("maxWidth");return}if(!kt){let z=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let I=e.ownerDocument,ye=(N=I.defaultView)!=null?N:window,le=Y=>{var nt,rt;if(!mt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||ye.innerWidth<=640)return;Y.preventDefault(),Er();let ue=Y.clientX,be=mt.element.getBoundingClientRect().width,Ie=(rt=(nt=r.features)==null?void 0:nt.artifacts)==null?void 0:rt.layout,Ye=Ee=>{let Ae=Hn.getBoundingClientRect().width,$e=e.classList.contains("persona-artifact-appearance-seamless"),S=$e?0:au(Hn,ye),we=$e?0:z.getBoundingClientRect().width||6,Le=be-(Ee.clientX-ue),Ue=iu(Le,Ae,S,we,Ie==null?void 0:Ie.resizableMinWidth,Ie==null?void 0:Ie.resizableMaxWidth);mt.element.style.width=`${Ue}px`,mt.element.style.maxWidth="none",_r()},ze=()=>{I.removeEventListener("pointermove",Ye),I.removeEventListener("pointerup",ze),I.removeEventListener("pointercancel",ze),zn=null;try{z.releasePointerCapture(Y.pointerId)}catch{}};zn=ze,I.addEventListener("pointermove",Ye),I.addEventListener("pointerup",ze),I.addEventListener("pointercancel",ze);try{z.setPointerCapture(Y.pointerId)}catch{}};z.addEventListener("pointerdown",le),kt=z,Hn.insertBefore(z,mt.element),bn=()=>{z.removeEventListener("pointerdown",le)}}if(kt){let z=Wn.artifacts.length>0&&!yn;kt.classList.toggle("persona-hidden",!z),_r()}},gr=()=>{var ye,le,Y,ue,be,Ie,Ye,ze,nt,rt,Ee,Ae,$e,S;if(!w||!mt||((le=(ye=r.launcher)==null?void 0:ye.sidebarMode)!=null?le:!1)||on(r)&&lr(r).reveal==="emerge")return;let b=(Y=e.ownerDocument.defaultView)!=null?Y:window,T=(be=(ue=r.launcher)==null?void 0:ue.mobileFullscreen)!=null?be:!0,B=(Ye=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Ye:640;if(T&&b.innerWidth<=B||!su(r,w))return;let N=(rt=(nt=(ze=r.launcher)==null?void 0:ze.width)!=null?nt:r.launcherWidth)!=null?rt:Gn,z=(S=($e=(Ae=(Ee=r.features)==null?void 0:Ee.artifacts)==null?void 0:Ae.layout)==null?void 0:$e.expandedPanelWidth)!=null?S:"min(720px, calc(100vw - 24px))";Wn.artifacts.length>0&&!yn?(V.style.width=z,V.style.maxWidth=z):(V.style.width=N,V.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(In=new ResizeObserver(()=>{Bn()}),In.observe(V))}else V.appendChild(te),U()&&ve&&(ce.peekBanner&&ve.appendChild(ce.peekBanner),ve.appendChild(Oe));e.appendChild(G),ve&&e.appendChild(ve);let Zn=()=>{var Ue,he,At,tt,Xt,dn,Tt,vn,pn,Ge,ot,Cn,mn,fo,ho,yo,Bo,Do,jt,bo,Qr,ut,kn,Wr,wn,Mn,Wt,$t;if(U()){V.style.width="100%",V.style.maxWidth="100%";let Rt=(he=(Ue=r.launcher)==null?void 0:Ue.composerBar)!=null?he:{},Ut=G.dataset.state==="expanded",Ln=(At=Rt.expandedSize)!=null?At:"anchored";if(!(Ut&&Ln!=="fullscreen")){te.style.background="",te.style.border="",te.style.borderRadius="",te.style.overflow="",te.style.boxShadow="";return}let en=(Xt=(tt=r.theme)==null?void 0:tt.components)==null?void 0:Xt.panel,yr=Ts(r),Rr=(xo,la)=>{var fs;return xo==null||xo===""?la:(fs=qo(yr,xo))!=null?fs:xo},sa="1px solid var(--persona-border)",aa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ia="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";te.style.background="var(--persona-surface, #ffffff)",te.style.border=Rr(en==null?void 0:en.border,sa),te.style.borderRadius=Rr(en==null?void 0:en.borderRadius,ia),te.style.boxShadow=Rr(en==null?void 0:en.shadow,aa),te.style.overflow="hidden";return}let c=on(r),m=(Tt=(dn=r.launcher)==null?void 0:dn.sidebarMode)!=null?Tt:!1,y=c||m||((pn=(vn=r.launcher)==null?void 0:vn.fullHeight)!=null?pn:!1),b=((Ge=r.launcher)==null?void 0:Ge.enabled)===!1,T=(Cn=(ot=r.theme)==null?void 0:ot.components)==null?void 0:Cn.panel,B=Ts(r),N=(Rt,Ut)=>{var Ln;return Rt==null||Rt===""?Ut:(Ln=qo(B,Rt))!=null?Ln:Rt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,I=(ho=(fo=r.launcher)==null?void 0:fo.mobileFullscreen)!=null?ho:!0,ye=(Bo=(yo=r.launcher)==null?void 0:yo.mobileBreakpoint)!=null?Bo:640,le=z.innerWidth<=ye,Y=I&&le&&w,ue=(jt=(Do=r.launcher)==null?void 0:Do.position)!=null?jt:"bottom-left",be=ue==="bottom-left"||ue==="top-left",Ie=(Qr=(bo=r.launcher)==null?void 0:bo.zIndex)!=null?Qr:hn,Ye=m||Y?"none":"1px solid var(--persona-border)",ze=Y?"none":m?be?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Y&&(ze="none",Ye="none");let nt=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",rt=N(T==null?void 0:T.border,Ye),Ee=N(T==null?void 0:T.shadow,ze),Ae=N(T==null?void 0:T.borderRadius,nt),$e=me.scrollTop;e.style.cssText="",G.style.cssText="",V.style.cssText="",te.style.cssText="",me.style.cssText="",Oe.style.cssText="";let S=()=>{var Ut;if($e<=0)return;((Ut=me.ownerDocument.defaultView)!=null?Ut:window).requestAnimationFrame(()=>{if(me.scrollTop===$e)return;let Ln=me.scrollHeight-me.clientHeight;Ln<=0||(me.scrollTop=Math.min($e,Ln))})};if(Y){G.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),G.style.cssText=`
|
|
24
24
|
position: fixed !important;
|
|
25
25
|
inset: 0 !important;
|
|
26
26
|
width: 100% !important;
|
|
@@ -56,7 +56,7 @@ import{Marked as Ku}from"marked";var Gu=e=>{if(e)return e},ca=e=>{var s,o;let n=
|
|
|
56
56
|
overflow: hidden !important;
|
|
57
57
|
border-radius: 0 !important;
|
|
58
58
|
border: none !important;
|
|
59
|
-
`,me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Oe.style.flexShrink="0",O=!0,S();return}let
|
|
59
|
+
`,me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Oe.style.flexShrink="0",O=!0,S();return}let we=(kn=(ut=r==null?void 0:r.launcher)==null?void 0:ut.width)!=null?kn:r==null?void 0:r.launcherWidth,Le=we!=null?we:Gn;if(!m&&!c)b&&y?(V.style.width="100%",V.style.maxWidth="100%"):(V.style.width=Le,V.style.maxWidth=Le);else if(c)if(lr(r).reveal==="emerge"){let Ut=lr(r).width;V.style.width=Ut,V.style.maxWidth=Ut}else V.style.width="100%",V.style.maxWidth="100%";if(gr(),V.style.boxShadow=Ee,V.style.borderRadius=Ae,te.style.border=rt,te.style.borderRadius=Ae,c&&!Y&&(T==null?void 0:T.border)===void 0&&(te.style.border="none",lr(r).side==="right"?te.style.borderLeft="1px solid var(--persona-border)":te.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.height="100%",b&&(G.style.overflow="hidden"),V.style.display="flex",V.style.flexDirection="column",V.style.flex="1 1 0%",V.style.minHeight="0",V.style.maxHeight="100%",V.style.height="100%",V.style.overflow="hidden",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.overflow="hidden",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Oe.style.flexShrink="0"),G.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&&!b&&!c&&((Wr=cr[ue])!=null?Wr:cr["bottom-right"]).split(" ").forEach(Ut=>G.classList.add(Ut)),m){let Rt=(Mn=(wn=r.launcher)==null?void 0:wn.sidebarWidth)!=null?Mn:"420px";G.style.cssText=`
|
|
60
60
|
position: fixed !important;
|
|
61
61
|
top: 0 !important;
|
|
62
62
|
bottom: 0 !important;
|
|
@@ -97,9 +97,9 @@ import{Marked as Ku}from"marked";var Gu=e=>{if(e)return e},ca=e=>{var s,o;let n=
|
|
|
97
97
|
flex-shrink: 0 !important;
|
|
98
98
|
border-top: none !important;
|
|
99
99
|
padding: 8px 16px 12px 16px !important;
|
|
100
|
-
`}if(!b&&!c){let Rt="max-height: -moz-available !important; max-height: stretch !important;",jt=m?"":"padding-top: 1.25em !important;",Ln=m?"":`z-index: ${($t=(Wt=r.launcher)==null?void 0:Wt.zIndex)!=null?$t:hn} !important;`;G.style.cssText+=Rt+jt+Ln}S()};Zn(),So(e,r),za(e,r),Va(e,r);let dt=[];dt.push(()=>{document.removeEventListener("keydown",Or)});let Jt=null,Kt=null;dt.push(()=>{Jt==null||Jt(),Jt=null,Kt==null||Kt(),Kt=null}),In&&dt.push(()=>{In==null||In.disconnect(),In=null}),dt.push(()=>{bn==null||bn(),bn=null,Er(),kt&&(kt.remove(),kt=null),mt==null||mt.element.style.removeProperty("width"),mt==null||mt.element.style.removeProperty("maxWidth")}),fe&&dt.push(()=>{ae!==null&&(cancelAnimationFrame(ae),ae=null),re==null||re.destroy(),re=null,Q==null||Q.destroy(),Q=null,ee=null});let Dn=null,Ur=()=>{Dn&&(Dn(),Dn=null),r.colorScheme==="auto"&&(Dn=yi(()=>{So(e,r)}))};Ur(),dt.push(()=>{Dn&&(Dn(),Dn=null)});let Vn=(_l=r.features)==null?void 0:_l.streamAnimation;if(Vn!=null&&Vn.type&&Vn.type!=="none"){let c=Is(Vn.type,Vn.plugins);c&&(vi(c,e),dt.push(()=>Tp(e)))}let er=Yp(Ft),Nn=null,_,de=!1,Fn=vp(),tr=new Map,fr=new Map,ts=0,nr=Ea(),rr=0,or=null,Tr=!1,co=!1,js=4,ns=24,qs=80,Lo=new Map,lt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},rs=(jl=(Ul=r.voiceRecognition)==null?void 0:Ul.autoResume)!=null?jl:!1,Jn=c=>{o.emit("voice:state",{active:lt.active,source:c,timestamp:Date.now()})},Tn=()=>{g(c=>({...c,voiceState:{active:lt.active,timestamp:Date.now(),manuallyDeactivated:lt.manuallyDeactivated}}))},zs=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Vi(d.voiceState),m=!!c.active,y=Number((T=c.timestamp)!=null?T:0);lt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-y<yy&&setTimeout(()=>{var B,N;lt.active||(lt.manuallyDeactivated=!1,((N=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:N.type)==="runtype"?_.toggleVoice().then(()=>{lt.active=_.isVoiceActive(),Jn("restore"),_.isVoiceActive()&&Gr()}):mo("restore"))},1e3)},Vs=()=>_?pu(_.getMessages()).filter(c=>!c.__skipPersist):[];function Po(c){if(!(i!=null&&i.save))return;let y={messages:c?pu(c):_?Vs():[],metadata:d,artifacts:Wn.artifacts,selectedArtifactId:Wn.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let kr=null,Js=()=>G.querySelector("#persona-scroll-container")||me,po=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),Tr=!1},os=()=>{or!==null&&(cancelAnimationFrame(or),or=null),co=!1,po()},Mr=()=>{if(!St()||Me){it.parentNode&&it.remove(),it.style.display="none";return}it.parentNode!==te&&te.appendChild(it),Un();let c=ks(me)>0;it.style.display=nr.isFollowing()||!c?"none":""},ss=()=>{nr.pause()&&(os(),Mr())},jr=()=>{nr.resume(),Mr()},qr=(c=!1)=>{nr.isFollowing()&&(!c&&!de||(or!==null&&(cancelAnimationFrame(or),or=null),co=!0,or=requestAnimationFrame(()=>{or=null,co=!1,nr.isFollowing()&&Ks(Js(),c?220:140)})))},Ks=(c,m=500)=>{let y=c.scrollTop,b=ks(c),T=b-y;if(Math.abs(T)<1){rr=c.scrollTop;return}if(Math.abs(T)>=qs){po(),Tr=!0,c.scrollTop=b,rr=c.scrollTop,Tr=!1;return}po();let B=performance.now();Tr=!0;let N=I=>1-Math.pow(1-I,3),z=I=>{if(!nr.isFollowing()){po();return}let ye=ks(c);ye!==b&&(b=ye,T=b-y);let le=I-B,Y=Math.min(le/m,1),ue=N(Y),be=y+T*ue;c.scrollTop=be,rr=c.scrollTop,Y<1?kr=requestAnimationFrame(z):(c.scrollTop=b,rr=c.scrollTop,kr=null,Tr=!1)};kr=requestAnimationFrame(z)},Gs=c=>{let m=new Map;c.forEach(y=>{let b=Lo.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Lo.clear(),m.forEach((y,b)=>{Lo.set(b,y)})},uo=(c,m,y)=>{var ze,nt,rt,Ee,Ae,$e;let b=document.createElement("div"),B=(()=>{var Ce;let S=s.find(Le=>Le.renderLoadingIndicator);if(S!=null&&S.renderLoadingIndicator)return S.renderLoadingIndicator;if((Ce=r.loadingIndicator)!=null&&Ce.render)return r.loadingIndicator.render})(),N=(S,Ce)=>Ce==null?!1:typeof Ce=="string"?(S.textContent=Ce,!0):(S.appendChild(Ce),!0),z=new Set,I=new Set,ye=s.some(S=>S.renderAskUserQuestion),le=[],Y=[],ue=r.enableComponentStreaming!==!1;if(m.forEach(S=>{var vn,pn,Ge,ot,wn,mn,fo,ho,yo,Bo,Do,Ut,bo,Qr;z.add(S.id);let Ce=ye&&to(S),Le=!Ce&&S.role==="assistant"&&!S.variant&&ue&&Ui(S);if(!Le&&fr.has(S.id)){let ut=c.querySelector(`#wrapper-${S.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),fr.delete(S.id)}let je=to(S)?`:${(vn=S.agentMetadata)!=null&&vn.askUserQuestionAnswered?"a":"u"}:${(pn=S.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(S.agentMetadata.askUserQuestionAnswers).length:0}`:"",he=xp(S,ts)+je,At=Ce||Le?null:wp(Fn,S.id,he);if(At){b.appendChild(At.cloneNode(!0)),to(S)&&((Ge=S.toolCall)!=null&&Ge.id)&&((ot=S.agentMetadata)==null?void 0:ot.awaitingLocalTool)===!0&&!((wn=S.agentMetadata)!=null&&wn.askUserQuestionAnswered)&&(I.add(S.toolCall.id),$s(S,r,ce.composerOverlay));return}let tt=null,Xt=s.find(ut=>!!(S.variant==="reasoning"&&ut.renderReasoning||S.variant==="tool"&&ut.renderToolCall||S.variant==="approval"&&ut.renderApproval||!S.variant&&ut.renderMessage)),dn=(mn=r.layout)==null?void 0:mn.messages;if(to(S)&&((fo=S.agentMetadata)==null?void 0:fo.askUserQuestionAnswered)===!0){tr.delete(S.id);let ut=c.querySelector(`#wrapper-${S.id}`);ut==null||ut.removeAttribute("data-preserve-runtime");return}if(to(S)&&((yo=(ho=r.features)==null?void 0:ho.askUserQuestion)==null?void 0:yo.enabled)!==!1){let ut=s.find(kn=>typeof kn.renderAskUserQuestion=="function");if(ut&&Et.current){let kn=tr.get(S.id),Wr=kn!==he,Cn=null;if(Wr){let{payload:$t,complete:Rt}=no(S),jt=S.id,Ln=()=>{var $n;return($n=Et.current)==null?void 0:$n.getMessages().find(en=>en.id===jt)};Cn=ut.renderAskUserQuestion({message:S,payload:$t,complete:Rt,resolve:$n=>{var yr;let en=Ln();en&&((yr=Et.current)==null||yr.resolveAskUserQuestion(en,$n))},dismiss:()=>{var en,yr,Rr;let $n=Ln();(en=$n==null?void 0:$n.agentMetadata)!=null&&en.awaitingLocalTool&&((yr=Et.current)==null||yr.markAskUserQuestionResolved($n),(Rr=Et.current)==null||Rr.resolveAskUserQuestion($n,"(dismissed)"))},config:r})}let Mn=kn!=null;if(Wr&&Cn===null&&!Mn){((Bo=S.agentMetadata)==null?void 0:Bo.awaitingLocalTool)===!0&&!((Do=S.agentMetadata)!=null&&Do.askUserQuestionAnswered)&&(I.add(S.toolCall.id),$s(S,r,ce.composerOverlay));return}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${S.id}`,Wt.setAttribute("data-wrapper-id",S.id),Wt.setAttribute("data-ask-plugin-stub","true"),Wt.setAttribute("data-preserve-runtime","true"),b.appendChild(Wt),le.push({messageId:S.id,fingerprint:he,bubble:Cn});return}else{((Ut=S.agentMetadata)==null?void 0:Ut.awaitingLocalTool)===!0&&!((bo=S.agentMetadata)!=null&&bo.askUserQuestionAnswered)&&(I.add(S.toolCall.id),$s(S,r,ce.composerOverlay));return}}else if(Xt)if(S.variant==="reasoning"&&S.reasoning&&Xt.renderReasoning){if(!We)return;tt=Xt.renderReasoning({message:S,defaultRenderer:()=>Ei(S,r),config:r})}else if(S.variant==="tool"&&S.toolCall&&Xt.renderToolCall){if(!_e)return;tt=Xt.renderToolCall({message:S,defaultRenderer:()=>Ti(S,r),config:r})}else if(S.variant==="approval"&&S.approval&&Xt.renderApproval){if(r.approval===!1)return;tt=Xt.renderApproval({message:S,defaultRenderer:()=>Ri(S,r),config:r})}else Xt.renderMessage&&(tt=Xt.renderMessage({message:S,defaultRenderer:()=>{let ut=Fs(S,y,dn,r.messageActions,Re,{loadingIndicatorRenderer:B,widgetConfig:r});return S.role!=="user"&&Di(ut,S,r,_),ut},config:r}));if(!tt&&Le){let ut=ji(S);if(ut){let kn=fr.get(S.id),Wr=kn!==he,Cn=r.wrapComponentDirectiveInBubble!==!1,Mn=null;if(Wr){let Wt=_i(ut,{config:r,message:S,transform:y});if(Wt)if(Cn){let $t=document.createElement("div");if($t.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(" "),$t.id=`bubble-${S.id}`,$t.setAttribute("data-message-id",S.id),S.content&&S.content.trim()){let Rt=document.createElement("div");Rt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Rt.innerHTML=y({text:S.content,message:S,streaming:!!S.streaming,raw:S.rawContent}),$t.appendChild(Rt)}$t.appendChild(Wt),Mn=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${S.id}`,$t.setAttribute("data-message-id",S.id),$t.setAttribute("data-persona-component-directive","true"),S.content&&S.content.trim()){let Rt=document.createElement("div");Rt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Rt.innerHTML=y({text:S.content,message:S,streaming:!!S.streaming,raw:S.rawContent}),$t.appendChild(Rt)}$t.appendChild(Wt),Mn=$t}}if(Mn||kn!=null){let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${S.id}`,Wt.setAttribute("data-wrapper-id",S.id),Wt.setAttribute("data-component-directive-stub","true"),Wt.setAttribute("data-preserve-runtime","true"),Cn||Wt.classList.add("persona-w-full"),b.appendChild(Wt),Y.push({messageId:S.id,fingerprint:he,bubble:Mn});return}}}if(!tt)if(S.variant==="reasoning"&&S.reasoning){if(!We)return;tt=Ei(S,r)}else if(S.variant==="tool"&&S.toolCall){if(!_e)return;tt=Ti(S,r)}else if(S.variant==="approval"&&S.approval){if(r.approval===!1)return;tt=Ri(S,r)}else{let ut=(Qr=r.layout)==null?void 0:Qr.messages;ut!=null&&ut.renderUserMessage&&S.role==="user"?tt=ut.renderUserMessage({message:S,config:r,streaming:!!S.streaming}):ut!=null&&ut.renderAssistantMessage&&S.role==="assistant"?tt=ut.renderAssistantMessage({message:S,config:r,streaming:!!S.streaming}):tt=Fs(S,y,ut,r.messageActions,Re,{loadingIndicatorRenderer:B,widgetConfig:r}),S.role!=="user"&&tt&&Di(tt,S,r,_)}let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id=`wrapper-${S.id}`,Tt.setAttribute("data-wrapper-id",S.id),S.role==="user"&&Tt.classList.add("persona-justify-end"),(tt==null?void 0:tt.getAttribute("data-persona-component-directive"))==="true"&&Tt.classList.add("persona-w-full"),Tt.appendChild(tt),Cp(Fn,S.id,he,Tt),b.appendChild(Tt)}),ce.composerOverlay&&ce.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ce=>{let Le=Ce.getAttribute("data-persona-ask-sheet-for");Le&&!I.has(Le)&&ko(ce.composerOverlay,Le)}),(nt=(ze=r.features)==null?void 0:ze.toolCallDisplay)!=null&&nt.grouped){let S=[],Ce=[];m.forEach(Le=>{if(Le.variant==="tool"&&Le.toolCall&&_e){Ce.push(Le);return}Ce.length>1&&S.push(Ce),Ce=[]}),Ce.length>1&&S.push(Ce),S.forEach((Le,je)=>{var pn,Ge;let he=Le.map(ot=>Array.from(b.children).find(wn=>wn instanceof HTMLElement&&wn.getAttribute("data-wrapper-id")===ot.id)).filter(ot=>!!ot);if(he.length<2)return;let At=document.createElement("div");At.className="persona-flex",At.id=`wrapper-tool-group-${je}-${Le[0].id}`,At.setAttribute("data-wrapper-id",`tool-group-${je}-${Le[0].id}`);let tt=document.createElement("div");tt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",tt.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${Le.length} tools`,Tt=(Ge=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Ge.call(pn,{messages:Le,toolCalls:Le.map(ot=>ot.toolCall).filter(ot=>!!ot),defaultSummary:dn,config:r});N(Xt,Tt)||(Xt.textContent=dn);let vn=document.createElement("div");vn.className="persona-tool-group-stack persona-flex persona-flex-col",tt.append(Xt,vn),At.appendChild(tt),he[0].before(At),he.forEach((ot,wn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),wn<he.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(ot),vn.appendChild(mn)})})}Ap(Fn,z);let be=m.some(S=>S.role==="assistant"&&S.streaming),Ie=m[m.length-1],Ye=(Ie==null?void 0:Ie.role)==="assistant"&&!Ie.streaming&&Ie.variant!=="approval";if(de&&m.some(S=>S.role==="user")&&!be&&!Ye){let S={config:r,streaming:!0,location:"standalone",defaultRenderer:Vo},Ce=s.find(je=>je.renderLoadingIndicator),Le=null;if(Ce!=null&&Ce.renderLoadingIndicator&&(Le=Ce.renderLoadingIndicator(S)),Le===null&&((rt=r.loadingIndicator)!=null&&rt.render)&&(Le=r.loadingIndicator.render(S)),Le===null&&(Le=Vo()),Le){let je=document.createElement("div"),he=((Ee=r.loadingIndicator)==null?void 0:Ee.showBubble)!==!1;je.className=he?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),je.setAttribute("data-typing-indicator","true"),je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",je.appendChild(Le);let At=document.createElement("div");At.className="persona-flex",At.id="wrapper-typing-indicator",At.setAttribute("data-wrapper-id","typing-indicator"),At.appendChild(je),b.appendChild(At)}}if(!de&&m.length>0){let S=m[m.length-1],Ce={config:r,lastMessage:S,messageCount:m.length},Le=s.find(he=>he.renderIdleIndicator),je=null;if(Le!=null&&Le.renderIdleIndicator&&(je=Le.renderIdleIndicator(Ce)),je===null&&((Ae=r.loadingIndicator)!=null&&Ae.renderIdle)&&(je=r.loadingIndicator.renderIdle(Ce)),je){let he=document.createElement("div"),At=(($e=r.loadingIndicator)==null?void 0:$e.showBubble)!==!1;he.className=At?["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(" "),he.setAttribute("data-idle-indicator","true"),he.appendChild(je);let tt=document.createElement("div");tt.className="persona-flex",tt.id="wrapper-idle-indicator",tt.setAttribute("data-wrapper-id","idle-indicator"),tt.appendChild(he),b.appendChild(tt)}}if(Sa(c,b),le.length>0)for(let{messageId:S,fingerprint:Ce,bubble:Le}of le){let je=c.querySelector(`#wrapper-${S}`);je&&Le!==null&&(je.replaceChildren(Le),je.setAttribute("data-bubble-fp",Ce),tr.set(S,Ce))}if(tr.size>0)for(let S of tr.keys())z.has(S)||tr.delete(S);if(Y.length>0)for(let{messageId:S,fingerprint:Ce,bubble:Le}of Y){let je=c.querySelector(`#wrapper-${S}`);je&&Le!==null&&(je.replaceChildren(Le),je.setAttribute("data-bubble-fp",Ce),fr.set(S,Ce))}if(fr.size>0)for(let S of fr.keys())z.has(S)||fr.delete(S)},zr=null,Qs=()=>{var y;if(zr)return;let c=b=>{let T=b.composedPath();T.includes(G)||ve&&T.includes(ve)||It(!1,"user")};zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},as=()=>{var m;if(!zr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",zr,!0),zr=null};dt.push(()=>as());let Vr=null,Xs=()=>{var y;if(Vr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||It(!1,"user"))};Vr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},is=()=>{var m;if(!Vr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Vr,!0),Vr=null};dt.push(()=>is());let Jr=!1,ls=new Set,Ys=()=>{var m,y,b,T;let c=(b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},Lr=()=>{var nt,rt,Ee,Ae;if(!j())return;let c=ce.peekBanner,m=ce.peekTextNode;if(!c||!m)return;if(H){c.classList.remove("persona-pill-peek--visible");return}let y=(nt=_==null?void 0:_.getMessages())!=null?nt:[],b;for(let $e=y.length-1;$e>=0;$e--){let S=y[$e];if(S.role==="assistant"&&S.content){b=S;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let T=b.content,B=!!b.streaming,N=Ys(),z=Ma(N),I=z.type!=="none"?Is(z.type,N==null?void 0:N.plugins):null,ye=((rt=I==null?void 0:I.isAnimating)==null?void 0:rt.call(I,b))===!0,le=I!==null&&(B||ye);le&&I&&!ls.has(I.name)&&(vi(I,e),ls.add(I.name));let Y=le&&(I!=null&&I.containerClass)?I.containerClass:null,ue=(Ee=m.dataset.personaPeekStreamClass)!=null?Ee:null;ue&&ue!==Y&&(m.classList.remove(ue),delete m.dataset.personaPeekStreamClass),Y&&ue!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),le?(m.style.setProperty("--persona-stream-step",`${z.speed}ms`),m.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let be=le?La(T,z.buffer,I,b,B):T;if(le&&z.placeholder==="skeleton"&&B&&(!be||!be.trim())){let $e=document.createElement("div"),S=Rs();S.classList.add("persona-pill-peek__skeleton"),$e.appendChild(S),Sa(m,$e)}else{let $e=Math.max(0,be.length-100),S=be.length>100?be.slice(-100):be,Ce=Fo(S);if(!le||!I){let Le=be.length>100?`\u2026${S}`:S;m.textContent!==Le&&(m.textContent=Le)}else{let Le=Ce;(I.wrap==="char"||I.wrap==="word")&&(Le=Ws(Ce,I.wrap,`peek-${b.id}`,{skipTags:I.skipTags,startIndex:$e}));let je=document.createElement("div");if(je.innerHTML=Le,I.useCaret&&S.length>0){let he=Pa(),At=je.querySelectorAll(".persona-stream-char, .persona-stream-word"),tt=At[At.length-1];tt!=null&&tt.parentNode?tt.parentNode.insertBefore(he,tt.nextSibling):je.appendChild(he)}Sa(m,je),(Ae=I.onAfterRender)==null||Ae.call(I,{container:m,bubble:c,messageId:b.id,message:b,speed:z.speed,duration:z.duration})}}let ze=de||Jr;c.classList.toggle("persona-pill-peek--visible",ze)};if(j()){let c=ce.peekBanner;if(c){let b=T=>{T.preventDefault(),T.stopPropagation(),It(!0,"user")};c.addEventListener("pointerdown",b),dt.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Jr||(Jr=!0,Lr())},y=()=>{Jr&&(Jr=!1,Lr())};V.addEventListener("pointerenter",m),V.addEventListener("pointerleave",y),dt.push(()=>{V.removeEventListener("pointerenter",m),V.removeEventListener("pointerleave",y)}),ve&&(ve.addEventListener("pointerenter",m),ve.addEventListener("pointerleave",y),dt.push(()=>{ve.removeEventListener("pointerenter",m),ve.removeEventListener("pointerleave",y)}))}let Zs=c=>{var ue,be,Ie,Ye,ze,nt,rt,Ee;let m=(be=(ue=r.launcher)==null?void 0:ue.composerBar)!=null?be:{},y=(Ie=m.expandedSize)!=null?Ie:"anchored",b=(Ye=m.bottomOffset)!=null?Ye:"16px",T=m.collapsedMaxWidth,B=(ze=m.expandedMaxWidth)!=null?ze:"880px",N=(nt=m.expandedTopOffset)!=null?nt:"5vh",z=(rt=m.modalMaxWidth)!=null?rt:"880px",I=(Ee=m.modalMaxHeight)!=null?Ee:"min(90vh, 800px)",ye="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",Y=G.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",ve){let Ae=ve.style;Ae.bottom=b,Ae.width=T!=null?T:""}if(c&&y!=="fullscreen"){if(y==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=z,Y.maxWidth=ye,Y.maxHeight=I,Y.height=I;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${le})`,Y.top=N,Y.width=B,Y.maxWidth=ye}},Kr=()=>{var I,ye,le,Y,ue,be,Ie,Ye;if(!$())return;if(j()){let nt=(le=((ye=(I=r.launcher)==null?void 0:I.composerBar)!=null?ye:{}).expandedSize)!=null?le:"anchored",rt=H?"expanded":"collapsed";G.dataset.state=rt,G.dataset.expandedSize=nt,ve&&(ve.dataset.state=rt,ve.dataset.expandedSize=nt),G.style.removeProperty("display"),G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Zs(H),te.style.display=H?"flex":"none",Zn(),H?(Qs(),Xs()):(as(),is()),Lr();return}let c=on(r),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,y=(be=(ue=r.launcher)==null?void 0:ue.mobileBreakpoint)!=null?be:640,b=(Ye=(Ie=r.launcher)==null?void 0:Ie.mobileFullscreen)!=null?Ye:!0,T=m.innerWidth<=y,B=b&&T&&C,N=lr(r).reveal;H?(G.style.removeProperty("display"),G.style.display=c?"flex":"",G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0"),V.classList.add("persona-scale-100","persona-opacity-100"),A?A.element.style.display="none":q&&(q.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!B?(G.style.removeProperty("display"),G.style.display="flex",G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(G.style.setProperty("display","none","important"),G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(G.style.display="",G.classList.add("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100"),V.classList.add("persona-scale-95","persona-opacity-0")),A?A.element.style.display=c?"none":"":q&&(q.style.display=c?"none":""))},It=(c,m="user")=>{var B,N;if(!$()||H===c)return;let y=H;H=c,Kr();let b=(()=>{var Ie,Ye,ze,nt,rt,Ee,Ae,$e,S,Ce;let z=(Ye=(Ie=r.launcher)==null?void 0:Ie.sidebarMode)!=null?Ye:!1,I=(ze=e.ownerDocument.defaultView)!=null?ze:window,ye=(rt=(nt=r.launcher)==null?void 0:nt.mobileFullscreen)!=null?rt:!0,le=(Ae=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?Ae:640,Y=I.innerWidth<=le,ue=on(r)&&ye&&Y,be=j()&&((Ce=(S=($e=r.launcher)==null?void 0:$e.composerBar)==null?void 0:S.expandedSize)!=null?Ce:"fullscreen")==="fullscreen";return z||ye&&Y&&C||ue||be})();if(H&&b){if(!Jt){let z=e.getRootNode(),I=z instanceof ShadowRoot?z.host:e.closest(".persona-host");I&&(Jt=wi(I,(N=(B=r.launcher)==null?void 0:B.zIndex)!=null?N:hn))}Kt||(Kt=Ci(e.ownerDocument))}else H||(Jt==null||Jt(),Jt=null,Kt==null||Kt(),Kt=null);H&&(ke(),qr(!0));let T={open:H,source:m,timestamp:Date.now()};H&&!y?o.emit("widget:opened",T):!H&&y&&o.emit("widget:closed",T),o.emit("widget:state",{open:H,launcherEnabled:C,voiceActive:lt.active,streaming:_.isStreaming()})},Io=c=>{zt(c?"stop":"send"),R&&(R.disabled=c),er.buttons.forEach(m=>{m.disabled=c}),Oe.dataset.personaComposerStreaming=c?"true":"false",Oe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Wo=()=>{lt.active||ie&&ie.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Wo(),200)});let cs=()=>{var y,b,T,B,N,z,I,ye,le,Y,ue;vr.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",dr.textContent=(B=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",ie.placeholder=(z=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?z:"How can I help...";let c=me.querySelector("[data-persona-intro-card]");if(c){let be=((I=r.copy)==null?void 0:I.showWelcomeCard)!==!1;c.style.display=be?"":"none",be?(me.classList.remove("persona-gap-3"),me.classList.add("persona-gap-6")):(me.classList.remove("persona-gap-6"),me.classList.add("persona-gap-3"))}!((le=(ye=r.sendButton)==null?void 0:ye.useIcon)!=null&&le)&&!(_!=null&&_.isStreaming())&&(Ne.textContent=(ue=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ue:"Send"),ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{g(m=>({...m,sessionId:c}))}});let hr=null,ea=()=>{hr==null&&(hr=setInterval(()=>{let c=Qe.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(hr),hr=null;return}let m=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=pa(m-b))})},100))};if(_=new As(r,{onMessagesChanged(c){uo(Qe,c,Se),ea(),_&&(c.some(T=>T.role==="user")?er.render([],_,ie,c):er.render(r.suggestionChips,_,ie,c,r.suggestionChipsConfig)),qr(!de),Gs(c);let m=[...c].reverse().find(b=>b.role==="user"),y=lt.lastUserMessageId;m&&m.id!==y&&(lt.lastUserMessageId=m.id,o.emit("user:message",m)),lt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Po(c),Lr()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};He(qt,(T=>{var B,N,z,I;return T==="idle"?(B=m.idleText)!=null?B:fn.idle:T==="connecting"?(N=m.connectingText)!=null?N:fn.connecting:T==="connected"?(z=m.connectedText)!=null?z:fn.connected:T==="error"?(I=m.errorText)!=null?I:fn.error:fn[T]})(c),m,c)},onStreamingChanged(c){de=c,Io(c),_&&uo(Qe,_.getMessages(),Se),c||qr(!0),Lr()},onVoiceStatusChanged(c){var m,y;if(((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":ar(),na();break;case"speaking":ar(),ra();break;default:c==="idle"&&_.isBargeInActive()?(ar(),Gr(),R==null||R.setAttribute("aria-label","End voice session")):(lt.active=!1,ar(),Jn("system"),Tn());break}},onArtifactsState(c){Wn=c,Bn(),Po()}}),Et.current=_,((zl=(ql=r.voiceRecognition)==null?void 0:ql.provider)==null?void 0:zl.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Q||r.onSSEEvent)&&_.setSSEEventCallback((c,m)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,m),Q==null||Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,y,b;c&&(c.metadata&&(d=Vi(c.metadata),k.syncFromMetadata()),(m=c.messages)!=null&&m.length&&_.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&_.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ds=()=>{var m,y,b;!j()||H||!((b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||It(!0,"auto")},ps=c=>{var T;if(c.preventDefault(),_.isStreaming()){_.cancel();return}let m=ie.value.trim(),y=(T=xt==null?void 0:xt.hasAttachments())!=null?T:!1;if(!m&&!y)return;ds();let b;y&&(b=[],b.push(...xt.getContentParts()),m&&b.push(ya(m))),ie.value="",ie.style.height="auto",_.sendMessage(m,{contentParts:b}),y&&xt.clearAttachments()},us=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Ne.click())},ms=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!xt)return;let m=xy(c.clipboardData);m.length!==0&&(c.preventDefault(),await xt.handleFiles(m))},xn=null,On=!1,Pr=null,et=null,gs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,mo=(c="user")=>{var B,N,z,I,ye,le,Y;if(On||_.isStreaming())return;let m=gs();if(!m)return;xn=new m;let b=(N=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?N:2e3;xn.continuous=!0,xn.interimResults=!0,xn.lang="en-US";let T=ie.value;xn.onresult=ue=>{let be="",Ie="";for(let ze=0;ze<ue.results.length;ze++){let nt=ue.results[ze],rt=nt[0].transcript;nt.isFinal?be+=rt+" ":Ie=rt}let Ye=T+be+Ie;ie.value=Ye,Pr&&clearTimeout(Pr),(be||Ie)&&(Pr=window.setTimeout(()=>{let ze=ie.value.trim();ze&&xn&&On&&(sr(),ie.value="",ie.style.height="auto",_.sendMessage(ze,{viaVoice:!0}))},b))},xn.onerror=ue=>{ue.error!=="no-speech"&&sr()},xn.onend=()=>{if(On){let ue=ie.value.trim();ue&&ue!==T.trim()&&(ie.value="",ie.style.height="auto",_.sendMessage(ue,{viaVoice:!0})),sr()}};try{if(xn.start(),On=!0,lt.active=!0,c!=="system"&&(lt.manuallyDeactivated=!1),Jn(c),Tn(),R){let ue=(z=r.voiceRecognition)!=null?z:{};et={backgroundColor:R.style.backgroundColor,color:R.style.color,borderColor:R.style.borderColor,iconName:(I=ue.iconName)!=null?I:"mic",iconSize:parseFloat((Y=(le=ue.iconSize)!=null?le:(ye=r.sendButton)==null?void 0:ye.size)!=null?Y:"40")||24};let be=ue.recordingBackgroundColor,Ie=ue.recordingIconColor,Ye=ue.recordingBorderColor;if(R.classList.add("persona-voice-recording"),R.style.backgroundColor=be!=null?be:"var(--persona-voice-recording-bg, #ef4444)",R.style.color=Ie!=null?Ie:"var(--persona-voice-recording-indicator, #ffffff)",Ie){let ze=R.querySelector("svg");ze&&ze.setAttribute("stroke",Ie)}Ye&&(R.style.borderColor=Ye),R.setAttribute("aria-label","Stop voice recognition")}}catch{sr("system")}},sr=(c="user")=>{if(On){if(On=!1,Pr&&(clearTimeout(Pr),Pr=null),xn){try{xn.stop()}catch{}xn=null}if(lt.active=!1,Jn(c),Tn(),R){if(R.classList.remove("persona-voice-recording"),et){R.style.backgroundColor=et.backgroundColor,R.style.color=et.color,R.style.borderColor=et.borderColor;let m=R.querySelector("svg");m&&m.setAttribute("stroke",et.color||"currentColor"),et=null}R.setAttribute("aria-label","Start voice recognition")}}},ta=(c,m)=>{var nt,rt,Ee,Ae,$e,S,Ce,Le;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((nt=c==null?void 0:c.provider)==null?void 0:nt.type)==="runtype";if(!(y||b))return null;let B=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let z=(rt=c==null?void 0:c.iconName)!=null?rt:"mic",I=(Ee=m==null?void 0:m.size)!=null?Ee:"40px",ye=(Ae=c==null?void 0:c.iconSize)!=null?Ae:I,le=parseFloat(ye)||24,Y=($e=c==null?void 0:c.backgroundColor)!=null?$e:m==null?void 0:m.backgroundColor,ue=(S=c==null?void 0:c.iconColor)!=null?S:m==null?void 0:m.textColor;N.style.width=ye,N.style.height=ye,N.style.minWidth=ye,N.style.minHeight=ye,N.style.fontSize="18px",N.style.lineHeight="1",ue?N.style.color=ue:N.style.color="var(--persona-text, #111827)";let Ie=ge(z,le,ue||"currentColor",1.5);Ie?N.appendChild(Ie):N.textContent="\u{1F3A4}",Y?N.style.backgroundColor=Y:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),B.appendChild(N);let Ye=(Ce=c==null?void 0:c.tooltipText)!=null?Ce:"Start voice recognition";if(((Le=c==null?void 0:c.showTooltip)!=null?Le:!1)&&Ye){let je=h("div","persona-send-button-tooltip");je.textContent=Ye,B.appendChild(je)}return{micButton:N,micButtonWrapper:B}},Ro=()=>{var m,y,b,T,B;if(!R||et)return;let c=(m=r.voiceRecognition)!=null?m:{};et={backgroundColor:R.style.backgroundColor,color:R.style.color,borderColor:R.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((B=(T=c.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},Ho=(c,m)=>{var B,N,z,I,ye;if(!R)return;let y=R.querySelector("svg");y&&y.remove();let b=(ye=et==null?void 0:et.iconSize)!=null?ye:parseFloat((I=(z=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?z:(N=r.sendButton)==null?void 0:N.size)!=null?I:"40")||24,T=ge(c,b,m,1.5);T&&R.appendChild(T)},go=()=>{R&&R.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Gr=()=>{var T;if(!R)return;Ro();let c=(T=r.voiceRecognition)!=null?T:{},m=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(go(),R.classList.add("persona-voice-recording"),R.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",R.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let B=R.querySelector("svg");B&&B.setAttribute("stroke",y)}b&&(R.style.borderColor=b),R.setAttribute("aria-label","Stop voice recognition")},na=()=>{var z,I,ye,le,Y,ue,be,Ie;if(!R)return;Ro();let c=(z=r.voiceRecognition)!=null?z:{},m=_.getVoiceInterruptionMode(),y=(I=c.processingIconName)!=null?I:"loader",b=(le=(ye=c.processingIconColor)!=null?ye:et==null?void 0:et.color)!=null?le:"",T=(ue=(Y=c.processingBackgroundColor)!=null?Y:et==null?void 0:et.backgroundColor)!=null?ue:"",B=(Ie=(be=c.processingBorderColor)!=null?be:et==null?void 0:et.borderColor)!=null?Ie:"";go(),R.classList.add("persona-voice-processing"),R.style.backgroundColor=T,R.style.borderColor=B;let N=b||"currentColor";R.style.color=N,Ho(y,N),R.setAttribute("aria-label","Processing voice input"),m==="none"&&(R.style.cursor="default")},ra=()=>{var ye,le,Y,ue,be,Ie,Ye,ze,nt,rt,Ee,Ae;if(!R)return;Ro();let c=(ye=r.voiceRecognition)!=null?ye:{},m=_.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:y,T=(Ie=c.speakingIconColor)!=null?Ie:m==="barge-in"?(ue=(Y=c.recordingIconColor)!=null?Y:et==null?void 0:et.color)!=null?ue:"":(be=et==null?void 0:et.color)!=null?be:"",B=(nt=c.speakingBackgroundColor)!=null?nt:m==="barge-in"?(Ye=c.recordingBackgroundColor)!=null?Ye:"var(--persona-voice-recording-bg, #ef4444)":(ze=et==null?void 0:et.backgroundColor)!=null?ze:"",N=(Ae=c.speakingBorderColor)!=null?Ae:m==="barge-in"?(rt=c.recordingBorderColor)!=null?rt:"":(Ee=et==null?void 0:et.borderColor)!=null?Ee:"";go(),R.classList.add("persona-voice-speaking"),R.style.backgroundColor=B,R.style.borderColor=N;let z=T||"currentColor";R.style.color=z,Ho(b,z);let I=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";R.setAttribute("aria-label",I),m==="none"&&(R.style.cursor="default"),m==="barge-in"&&R.classList.add("persona-voice-recording")},ar=()=>{var c,m,y;R&&(go(),et&&(R.style.backgroundColor=(c=et.backgroundColor)!=null?c:"",R.style.color=(m=et.color)!=null?m:"",R.style.borderColor=(y=et.borderColor)!=null?y:"",Ho(et.iconName,et.color||"currentColor"),et=null),R.style.cursor="",R.setAttribute("aria-label","Start voice recognition"))},Ir=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let y=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{lt.active=!1,lt.manuallyDeactivated=!0,Tn(),Jn("user"),ar()});return}_.toggleVoice().then(()=>{lt.active=_.isVoiceActive(),lt.manuallyDeactivated=!_.isVoiceActive(),Tn(),Jn("user"),_.isVoiceActive()?Gr():ar()});return}if(On){let y=ie.value.trim();lt.manuallyDeactivated=!0,Tn(),sr("user"),y&&(ie.value="",ie.style.height="auto",_.sendMessage(y))}else lt.manuallyDeactivated=!1,Tn(),mo("user")};pr=Ir,R&&(R.addEventListener("click",Ir),dt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),ar()):sr("system"),R&&R.removeEventListener("click",Ir)}));let Ve=o.on("assistant:complete",()=>{rs&&(lt.active||lt.manuallyDeactivated||rs==="assistant"&&!lt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!lt.active&&!lt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.toggleVoice().then(()=>{lt.active=_.isVoiceActive(),Jn("auto"),_.isVoiceActive()&&Gr()}):mo("auto"))},600))});dt.push(Ve);let w=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(w);let U=()=>{It(!H,"user")},A=null,q=null;if(C&&!j()){let c=s.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Bs(r,U).element,onToggle:U});m&&(q=m)}q||(A=Bs(r,U))}A?e.appendChild(A.element):q&&e.appendChild(q),Kr(),er.render(r.suggestionChips,_,ie,void 0,r.suggestionChipsConfig),cs(),Io(_.isStreaming()),qr(!0),zs(),D&&(!C||j()?setTimeout(()=>Wo(),0):H&&setTimeout(()=>Wo(),200));let ke=()=>{var I,ye,le,Y,ue,be,Ie,Ye,ze,nt,rt,Ee,Ae,$e,S,Ce,Le,je,he,At,tt,Xt;if(j()){Un(),Kr();return}let c=on(r),m=(ye=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?ye:!1,y=c||m||((Y=(le=r.launcher)==null?void 0:le.fullHeight)!=null?Y:!1),b=(ue=e.ownerDocument.defaultView)!=null?ue:window,T=(Ie=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Ie:!0,B=(ze=(Ye=r.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?ze:640,N=b.innerWidth<=B,z=T&&N&&C;try{if(z){Zn(),So(e,r);return}if(O&&(O=!1,Zn(),So(e,r)),!C&&!c){V.style.height="",V.style.width="";return}if(!m&&!c){let dn=(rt=(nt=r==null?void 0:r.launcher)==null?void 0:nt.width)!=null?rt:r==null?void 0:r.launcherWidth,Tt=dn!=null?dn:Gn;V.style.width=Tt,V.style.maxWidth=Tt}if(gr(),!y){let dn=b.innerHeight,Tt=64,vn=(Ae=(Ee=r.launcher)==null?void 0:Ee.heightOffset)!=null?Ae:0,pn=Math.max(200,dn-Tt),Ge=Math.min(640,pn),ot=Math.max(200,Ge-vn);V.style.height=`${ot}px`}}finally{if(Un(),Kr(),H&&C){let Tt=(($e=e.ownerDocument.defaultView)!=null?$e:window).innerWidth<=((Ce=(S=r.launcher)==null?void 0:S.mobileBreakpoint)!=null?Ce:640),vn=(je=(Le=r.launcher)==null?void 0:Le.sidebarMode)!=null?je:!1,pn=(At=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?At:!0,Ge=on(r)&&pn&&Tt,ot=vn||pn&&Tt&&C||Ge;if(ot&&!Kt){let wn=e.getRootNode(),mn=wn instanceof ShadowRoot?wn.host:e.closest(".persona-host");mn&&!Jt&&(Jt=wi(mn,(Xt=(tt=r.launcher)==null?void 0:tt.zIndex)!=null?Xt:hn)),Kt=Ci(e.ownerDocument)}else ot||(Jt==null||Jt(),Jt=null,Kt==null||Kt(),Kt=null)}}};ke();let Z=(Vl=e.ownerDocument.defaultView)!=null?Vl:window;if(Z.addEventListener("resize",ke),dt.push(()=>Z.removeEventListener("resize",ke)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Un()});c.observe(Oe),dt.push(()=>c.disconnect())}rr=me.scrollTop;let Xe=me.scrollHeight,Ke=()=>{let c=me.scrollTop,m=me.scrollHeight,y=m<Xe;Xe=m;let{action:b,nextLastScrollTop:T}=Ta({following:nr.isFollowing(),currentScrollTop:c,lastScrollTop:rr,nearBottom:Ms(me,ns),userScrollThreshold:js,isAutoScrolling:Tr||co||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rr=T,b==="resume"){jr();return}b==="pause"&&ss()};me.addEventListener("scroll",Ke,{passive:!0}),dt.push(()=>me.removeEventListener("scroll",Ke));let Mt=c=>{let m=ka({following:nr.isFollowing(),deltaY:c.deltaY,nearBottom:Ms(me,ns),resumeWhenNearBottom:!0});m==="pause"?ss():m==="resume"&&jr()};me.addEventListener("wheel",Mt,{passive:!0}),dt.push(()=>me.removeEventListener("wheel",Mt)),it.addEventListener("click",()=>{me.scrollTop=me.scrollHeight,rr=me.scrollTop,jr(),qr(!0)}),dt.push(()=>it.remove()),dt.push(()=>{os()});let gt=()=>{P&&(Nn&&(P.removeEventListener("click",Nn),Nn=null),$()?(P.style.display="",Nn=()=>{It(!1,"user")},P.addEventListener("click",Nn)):P.style.display="none")};gt(),(()=>{let{clearChatButton:c}=ce;c&&c.addEventListener("click",()=>{_.clearMessages(),Fn.clear(),jr(),ko(ce.composerOverlay);try{localStorage.removeItem(Zo),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zo}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Zo)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},k.syncFromMetadata(),Q==null||Q.clear(),re==null||re.update()})})(),Pt&&Pt.addEventListener("submit",ps),ie==null||ie.addEventListener("keydown",us),ie==null||ie.addEventListener("paste",ms);let Ht="persona-attachment-drop-active",Gt=0,yt=()=>{Gt=0,te.classList.remove(Ht)},ft=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&xt!==null},tn=c=>{!Qa(c.dataTransfer)||!ft()||(Gt++,Gt===1&&te.classList.add(Ht))},un=c=>{!Qa(c.dataTransfer)||!ft()||(Gt--,Gt<=0&&yt())},cn=c=>{!Qa(c.dataTransfer)||!ft()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Qt=c=>{var y;if(!Qa(c.dataTransfer)||!ft())return;c.preventDefault(),c.stopPropagation(),yt();let m=Array.from((y=c.dataTransfer.files)!=null?y:[]);m.length!==0&&xt.handleFiles(m)},sn=!0;te.addEventListener("dragenter",tn,sn),te.addEventListener("dragleave",un,sn),e.addEventListener("dragover",cn,sn),e.addEventListener("drop",Qt,sn);let oa=e.ownerDocument,ol=c=>{ft()&&c.preventDefault()},sl=c=>{ft()&&c.preventDefault()};oa.addEventListener("dragover",ol),oa.addEventListener("drop",sl),dt.push(()=>{Pt&&Pt.removeEventListener("submit",ps),ie==null||ie.removeEventListener("keydown",us),ie==null||ie.removeEventListener("paste",ms)}),dt.push(()=>{te.removeEventListener("dragenter",tn,sn),te.removeEventListener("dragleave",un,sn),e.removeEventListener("dragover",cn,sn),e.removeEventListener("drop",Qt,sn),oa.removeEventListener("dragover",ol),oa.removeEventListener("drop",sl),yt()}),dt.push(()=>{_.cancel()}),A?dt.push(()=>{A==null||A.destroy()}):q&&dt.push(()=>{q==null||q.remove()});let Zt={update(c){var en,yr,Rr,sa,aa,ia,xo,la,fs,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc,Ac,Sc,Ec,Tc,kc,Mc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,Uc,jc,qc,zc,Vc,Jc,Kc,Gc,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Ed,Td,kd,Md,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,Ud,jd,qd,zd,Vd,Jd,Kd;let m=r.toolCall,y=r.messageActions,b=(en=r.layout)==null?void 0:en.messages,T=r.colorScheme,B=r.loadingIndicator,N=r.iterationDisplay,z=(yr=r.features)==null?void 0:yr.showReasoning,I=(Rr=r.features)==null?void 0:Rr.showToolCalls,ye=(sa=r.features)==null?void 0:sa.toolCallDisplay,le=(aa=r.features)==null?void 0:aa.reasoningDisplay;r={...r,...c},Zn(),So(e,r),za(e,r),Va(e,r),Bn(),r.colorScheme!==T&&Ur();let Y=Ja.getForInstance(r.plugins);s.length=0,s.push(...Y),C=(xo=(ia=r.launcher)==null?void 0:ia.enabled)!=null?xo:!0,L=(fs=(la=r.launcher)==null?void 0:la.autoExpand)!=null?fs:!1,We=(ec=(Zl=r.features)==null?void 0:Zl.showReasoning)!=null?ec:!0,_e=(nc=(tc=r.features)==null?void 0:tc.showToolCalls)!=null?nc:!0,pe=(oc=(rc=r.features)==null?void 0:rc.scrollToBottom)!=null?oc:{},Dr(),Mr();let ue=fe;if(fe=(ac=(sc=r.features)==null?void 0:sc.showEventStreamToggle)!=null?ac:!1,fe&&!ue){if(Q||(ee=new Us(Ue),Q=new _s(xe,ee),ee.open().then(()=>Q==null?void 0:Q.restore()).catch(()=>{}),_.setSSEEventCallback((X,bt)=>{var Bt;(Bt=r.onSSEEvent)==null||Bt.call(r,X,bt),Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(bt)})})),!ct&&Fe){let X=(lc=(ic=r.features)==null?void 0:ic.eventStream)==null?void 0:lc.classNames,bt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");ct=h("button",bt),ct.style.width="28px",ct.style.height="28px",ct.style.color=Sn.actionIconColor,ct.type="button",ct.setAttribute("aria-label","Event Stream"),ct.title="Event Stream";let Bt=ge("activity","18px","currentColor",1.5);Bt&&ct.appendChild(Bt);let st=ce.clearChatButtonWrapper,Ct=ce.closeButtonWrapper,nn=st||Ct;nn&&nn.parentNode===Fe?Fe.insertBefore(ct,nn):Fe.appendChild(ct),ct.addEventListener("click",()=>{Me?Yn():Cr()})}}else!fe&&ue&&(Yn(),ct&&(ct.remove(),ct=null),Q==null||Q.clear(),ee==null||ee.destroy(),Q=null,ee=null);if(((cc=r.launcher)==null?void 0:cc.enabled)===!1&&A&&(A.destroy(),A=null),((dc=r.launcher)==null?void 0:dc.enabled)===!1&&q&&(q.remove(),q=null),((pc=r.launcher)==null?void 0:pc.enabled)!==!1&&!A&&!q){let X=s.find(bt=>bt.renderLauncher);if(X!=null&&X.renderLauncher){let bt=X.renderLauncher({config:r,defaultRenderer:()=>Bs(r,U).element,onToggle:U});bt&&(q=bt,e.appendChild(q))}q||(A=Bs(r,U),e.appendChild(A.element))}A&&A.update(r),Pe&&((uc=r.launcher)==null?void 0:uc.title)!==void 0&&(Pe.textContent=r.launcher.title),qe&&((mc=r.launcher)==null?void 0:mc.subtitle)!==void 0&&(qe.textContent=r.launcher.subtitle);let be=(gc=r.layout)==null?void 0:gc.header;if((be==null?void 0:be.layout)!==M&&Fe){let X=be?Ds(r,be,{showClose:$(),onClose:()=>It(!1,"user")}):eo({config:r,showClose:$(),onClose:()=>It(!1,"user")});Fe.replaceWith(X.header),Fe=X.header,oe=X.iconHolder,Pe=X.headerTitle,qe=X.headerSubtitle,P=X.closeButton,M=be==null?void 0:be.layout}else if(be&&(oe&&(oe.style.display=be.showIcon===!1?"none":""),Pe&&(Pe.style.display=be.showTitle===!1?"none":""),qe&&(qe.style.display=be.showSubtitle===!1?"none":""),P&&(P.style.display=be.showCloseButton===!1?"none":""),ce.clearChatButtonWrapper)){let X=be.showClearChat;if(X!==void 0){ce.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:bt}=ce;bt&&!bt.classList.contains("persona-absolute")&&(X?bt.classList.remove("persona-ml-auto"):bt.classList.add("persona-ml-auto"))}}let Ye=((fc=r.layout)==null?void 0:fc.showHeader)!==!1;Fe&&(Fe.style.display=Ye?"":"none");let ze=((hc=r.layout)==null?void 0:hc.showFooter)!==!1;Oe&&(Oe.style.display=ze?"":"none"),Un(),Mr(),C!==E?C?It(L,"auto"):(H=!0,Kr()):L!==W&&It(L,"auto"),W=L,E=C,ke(),gt();let Ee=JSON.stringify(c.toolCall)!==JSON.stringify(m),Ae=JSON.stringify(r.messageActions)!==JSON.stringify(y),$e=JSON.stringify((yc=r.layout)==null?void 0:yc.messages)!==JSON.stringify(b),S=((bc=r.loadingIndicator)==null?void 0:bc.render)!==(B==null?void 0:B.render)||((xc=r.loadingIndicator)==null?void 0:xc.renderIdle)!==(B==null?void 0:B.renderIdle)||((vc=r.loadingIndicator)==null?void 0:vc.showBubble)!==(B==null?void 0:B.showBubble),Ce=r.iterationDisplay!==N,Le=((Cc=(wc=r.features)==null?void 0:wc.showReasoning)!=null?Cc:!0)!==(z!=null?z:!0)||((Sc=(Ac=r.features)==null?void 0:Ac.showToolCalls)!=null?Sc:!0)!==(I!=null?I:!0)||JSON.stringify((Ec=r.features)==null?void 0:Ec.toolCallDisplay)!==JSON.stringify(ye)||JSON.stringify((Tc=r.features)==null?void 0:Tc.reasoningDisplay)!==JSON.stringify(le);(Ee||Ae||$e||S||Ce||Le)&&_&&(ts++,uo(Qe,_.getMessages(),Se));let he=(kc=r.launcher)!=null?kc:{},At=(Mc=he.headerIconHidden)!=null?Mc:!1,tt=(Pc=(Lc=r.layout)==null?void 0:Lc.header)==null?void 0:Pc.showIcon,Xt=At||tt===!1,dn=he.headerIconName,Tt=(Ic=he.headerIconSize)!=null?Ic:"48px";if(oe){let X=te.querySelector(".persona-border-b-persona-divider"),bt=X==null?void 0:X.querySelector(".persona-flex-col");if(Xt)oe.style.display="none",X&&bt&&!X.contains(bt)&&X.insertBefore(bt,X.firstChild);else{if(oe.style.display="",oe.style.height=Tt,oe.style.width=Tt,X&&bt&&(X.contains(oe)?oe.nextSibling!==bt&&(oe.remove(),X.insertBefore(oe,bt)):X.insertBefore(oe,bt)),dn){let st=parseFloat(Tt)||24,Ct=ge(dn,st*.6,"#ffffff",2);Ct?oe.replaceChildren(Ct):oe.textContent=(Wc=he.agentIconText)!=null?Wc:"\u{1F4AC}"}else if(he.iconUrl){let st=oe.querySelector("img");if(st)st.src=he.iconUrl,st.style.height=Tt,st.style.width=Tt;else{let Ct=document.createElement("img");Ct.src=he.iconUrl,Ct.alt="",Ct.className="persona-rounded-xl persona-object-cover",Ct.style.height=Tt,Ct.style.width=Tt,oe.replaceChildren(Ct)}}else{let st=oe.querySelector("svg"),Ct=oe.querySelector("img");(st||Ct)&&oe.replaceChildren(),oe.textContent=(Rc=he.agentIconText)!=null?Rc:"\u{1F4AC}"}let Bt=oe.querySelector("img");Bt&&(Bt.style.height=Tt,Bt.style.width=Tt)}}let vn=(Bc=(Hc=r.layout)==null?void 0:Hc.header)==null?void 0:Bc.showTitle,pn=(Nc=(Dc=r.layout)==null?void 0:Dc.header)==null?void 0:Nc.showSubtitle;if(Pe&&(Pe.style.display=vn===!1?"none":""),qe&&(qe.style.display=pn===!1?"none":""),P){((Oc=(Fc=r.layout)==null?void 0:Fc.header)==null?void 0:Oc.showCloseButton)===!1?P.style.display="none":P.style.display="";let bt=($c=he.closeButtonSize)!=null?$c:"32px",Bt=(_c=he.closeButtonPlacement)!=null?_c:"inline";P.style.height=bt,P.style.width=bt;let{closeButtonWrapper:st}=ce,Ct=Bt==="top-right",nn=st==null?void 0:st.classList.contains("persona-absolute");if(st&&Ct!==nn)if(st.remove(),Ct)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",te.style.position="relative",te.appendChild(st);else{let at=(jc=(Uc=he.clearChat)==null?void 0:Uc.placement)!=null?jc:"inline",rn=(zc=(qc=he.clearChat)==null?void 0:qc.enabled)!=null?zc:!0;st.className=rn&&at==="inline"?"":"persona-ml-auto";let Pn=te.querySelector(".persona-border-b-persona-divider");Pn&&Pn.appendChild(st)}if(P.style.color=he.closeButtonColor||Sn.actionIconColor,he.closeButtonBackgroundColor?(P.style.backgroundColor=he.closeButtonBackgroundColor,P.classList.remove("hover:persona-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let at=he.closeButtonBorderWidth||"0px",rn=he.closeButtonBorderColor||"transparent";P.style.border=`${at} solid ${rn}`,P.classList.remove("persona-border-none")}else P.style.border="",P.classList.add("persona-border-none");he.closeButtonBorderRadius?(P.style.borderRadius=he.closeButtonBorderRadius,P.classList.remove("persona-rounded-full")):(P.style.borderRadius="",P.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(P.style.paddingLeft=he.closeButtonPaddingX,P.style.paddingRight=he.closeButtonPaddingX):(P.style.paddingLeft="",P.style.paddingRight=""),he.closeButtonPaddingY?(P.style.paddingTop=he.closeButtonPaddingY,P.style.paddingBottom=he.closeButtonPaddingY):(P.style.paddingTop="",P.style.paddingBottom="");let gn=(Vc=he.closeButtonIconName)!=null?Vc:"x",ir=(Jc=he.closeButtonIconText)!=null?Jc:"\xD7";P.innerHTML="";let An=ge(gn,"28px","currentColor",1);An?P.appendChild(An):P.textContent=ir;let Yt=(Kc=he.closeButtonTooltipText)!=null?Kc:"Close chat",_n=(Gc=he.closeButtonShowTooltip)!=null?Gc:!0;if(P.setAttribute("aria-label",Yt),st&&(st._cleanupTooltip&&(st._cleanupTooltip(),delete st._cleanupTooltip),_n&&Yt)){let at=null,rn=()=>{if(at||!P)return;let vo=P.ownerDocument,hs=vo.body;if(!hs)return;at=br(vo,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let ys=br(vo,"div");ys.className="persona-clear-chat-tooltip-arrow",at.appendChild(ys);let wo=P.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(Xr),at.style.left=`${wo.left+wo.width/2}px`,at.style.top=`${wo.top-8}px`,at.style.transform="translate(-50%, -100%)",hs.appendChild(at)},Pn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};st.addEventListener("mouseenter",rn),st.addEventListener("mouseleave",Pn),P.addEventListener("focus",rn),P.addEventListener("blur",Pn),st._cleanupTooltip=()=>{Pn(),st&&(st.removeEventListener("mouseenter",rn),st.removeEventListener("mouseleave",Pn)),P&&(P.removeEventListener("focus",rn),P.removeEventListener("blur",Pn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:ot}=ce;if(Ge){let X=(Qc=he.clearChat)!=null?Qc:{},bt=(Xc=X.enabled)!=null?Xc:!0,Bt=(Zc=(Yc=r.layout)==null?void 0:Yc.header)==null?void 0:Zc.showClearChat,st=Bt!==void 0?Bt:bt,Ct=(ed=X.placement)!=null?ed:"inline";if(ot){ot.style.display=st?"":"none";let{closeButtonWrapper:nn}=ce;!j()&&nn&&!nn.classList.contains("persona-absolute")&&(st?nn.classList.remove("persona-ml-auto"):nn.classList.add("persona-ml-auto"));let gn=Ct==="top-right",ir=ot.classList.contains("persona-absolute");if(!j()&&gn!==ir&&st){if(ot.remove(),gn)ot.className="persona-absolute persona-top-4 persona-z-50",ot.style.right="48px",te.style.position="relative",te.appendChild(ot);else{ot.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ot.style.right="";let Yt=te.querySelector(".persona-border-b-persona-divider"),_n=ce.closeButtonWrapper;Yt&&_n&&_n.parentElement===Yt?Yt.insertBefore(ot,_n):Yt&&Yt.appendChild(ot)}let An=ce.closeButtonWrapper;An&&!An.classList.contains("persona-absolute")&&(gn?An.classList.add("persona-ml-auto"):An.classList.remove("persona-ml-auto"))}}if(st){if(!j()){let at=(td=X.size)!=null?td:"32px";Ge.style.height=at,Ge.style.width=at}let nn=(nd=X.iconName)!=null?nd:"refresh-cw",gn=(rd=X.iconColor)!=null?rd:"";Ge.style.color=gn||Sn.actionIconColor,Ge.innerHTML="";let ir=j()?"14px":"20px",An=ge(nn,ir,"currentColor",2);if(An&&Ge.appendChild(An),X.backgroundColor?(Ge.style.backgroundColor=X.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let at=X.borderWidth||"0px",rn=X.borderColor||"transparent";Ge.style.border=`${at} solid ${rn}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");X.borderRadius?(Ge.style.borderRadius=X.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),X.paddingX?(Ge.style.paddingLeft=X.paddingX,Ge.style.paddingRight=X.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),X.paddingY?(Ge.style.paddingTop=X.paddingY,Ge.style.paddingBottom=X.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Yt=(od=X.tooltipText)!=null?od:"Clear chat",_n=(sd=X.showTooltip)!=null?sd:!0;if(Ge.setAttribute("aria-label",Yt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),_n&&Yt)){let at=null,rn=()=>{if(at||!Ge)return;let vo=Ge.ownerDocument,hs=vo.body;if(!hs)return;at=br(vo,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let ys=br(vo,"div");ys.className="persona-clear-chat-tooltip-arrow",at.appendChild(ys);let wo=Ge.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(Xr),at.style.left=`${wo.left+wo.width/2}px`,at.style.top=`${wo.top-8}px`,at.style.transform="translate(-50%, -100%)",hs.appendChild(at)},Pn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};ot.addEventListener("mouseenter",rn),ot.addEventListener("mouseleave",Pn),Ge.addEventListener("focus",rn),Ge.addEventListener("blur",Pn),ot._cleanupTooltip=()=>{Pn(),ot&&(ot.removeEventListener("mouseenter",rn),ot.removeEventListener("mouseleave",Pn)),Ge&&(Ge.removeEventListener("focus",rn),Ge.removeEventListener("blur",Pn))}}}}let wn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ka],mn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Yo.message,Yo.messageAndClick];k=Ga({parsers:wn,handlers:mn,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Se=uu(r,k,ne),_.updateConfig(r),uo(Qe,_.getMessages(),Se),er.render(r.suggestionChips,_,ie,void 0,r.suggestionChipsConfig),cs(),Io(_.isStreaming());let fo=((ad=r.voiceRecognition)==null?void 0:ad.enabled)===!0,ho=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),yo=((ld=(id=r.voiceRecognition)==null?void 0:id.provider)==null?void 0:ld.type)==="runtype";if(fo&&(ho||yo))if(!R||!se){let X=ta(r.voiceRecognition,r.sendButton);X&&(R=X.micButton,se=X.micButtonWrapper,Ot.insertBefore(se,an),R.addEventListener("click",Ir),R.disabled=_.isStreaming())}else{let X=(cd=r.voiceRecognition)!=null?cd:{},bt=(dd=r.sendButton)!=null?dd:{},Bt=(pd=X.iconName)!=null?pd:"mic",st=(ud=bt.size)!=null?ud:"40px",Ct=(md=X.iconSize)!=null?md:st,nn=parseFloat(Ct)||24;R.style.width=Ct,R.style.height=Ct,R.style.minWidth=Ct,R.style.minHeight=Ct;let gn=(fd=(gd=X.iconColor)!=null?gd:bt.textColor)!=null?fd:"currentColor";R.innerHTML="";let ir=ge(Bt,nn,gn,2);ir?R.appendChild(ir):R.textContent="\u{1F3A4}";let An=(hd=X.backgroundColor)!=null?hd:bt.backgroundColor;An?R.style.backgroundColor=An:R.style.backgroundColor="",gn?R.style.color=gn:R.style.color="var(--persona-text, #111827)",X.borderWidth?(R.style.borderWidth=X.borderWidth,R.style.borderStyle="solid"):(R.style.borderWidth="",R.style.borderStyle=""),X.borderColor?R.style.borderColor=X.borderColor:R.style.borderColor="",X.paddingX?(R.style.paddingLeft=X.paddingX,R.style.paddingRight=X.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),X.paddingY?(R.style.paddingTop=X.paddingY,R.style.paddingBottom=X.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let Yt=se==null?void 0:se.querySelector(".persona-send-button-tooltip"),_n=(yd=X.tooltipText)!=null?yd:"Start voice recognition";if(((bd=X.showTooltip)!=null?bd:!1)&&_n)if(Yt)Yt.textContent=_n,Yt.style.display="";else{let rn=document.createElement("div");rn.className="persona-send-button-tooltip",rn.textContent=_n,se==null||se.insertBefore(rn,R)}else Yt&&(Yt.style.display="none");se.style.display="",R.disabled=_.isStreaming()}else R&&se&&(se.style.display="none",((vd=(xd=r.voiceRecognition)==null?void 0:xd.provider)==null?void 0:vd.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():On&&sr());if(((wd=r.attachments)==null?void 0:wd.enabled)===!0)if(!pt||!we){let X=(Cd=r.attachments)!=null?Cd:{},Bt=(Sd=((Ad=r.sendButton)!=null?Ad:{}).size)!=null?Sd:"40px";Nt||(Nt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Nt.style.display="none",Pt.insertBefore(Nt,ie)),Je||(Je=document.createElement("input"),Je.type="file",Je.accept=((Ed=X.allowedTypes)!=null?Ed:Hr).join(","),Je.multiple=((Td=X.maxFiles)!=null?Td:4)>1,Je.style.display="none",Je.setAttribute("aria-label","Attach files"),Pt.insertBefore(Je,ie)),pt=h("div","persona-send-button-wrapper"),we=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),we.type="button",we.setAttribute("aria-label",(kd=X.buttonTooltipText)!=null?kd:"Attach file");let st=(Md=X.buttonIconName)!=null?Md:"paperclip",Ct=Bt,nn=parseFloat(Ct)||40,gn=Math.round(nn*.6);we.style.width=Ct,we.style.height=Ct,we.style.minWidth=Ct,we.style.minHeight=Ct,we.style.fontSize="18px",we.style.lineHeight="1",we.style.backgroundColor="transparent",we.style.color="var(--persona-primary, #111827)",we.style.border="none",we.style.borderRadius="6px",we.style.transition="background-color 0.15s ease",we.addEventListener("mouseenter",()=>{we.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),we.addEventListener("mouseleave",()=>{we.style.backgroundColor="transparent"});let ir=ge(st,gn,"currentColor",1.5);ir?we.appendChild(ir):we.textContent="\u{1F4CE}",we.addEventListener("click",_n=>{_n.preventDefault(),Je==null||Je.click()}),pt.appendChild(we);let An=(Ld=X.buttonTooltipText)!=null?Ld:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=An,pt.appendChild(Yt),vt.append(pt),!xt&&Je&&Nt&&(xt=jo.fromConfig(X),xt.setPreviewsContainer(Nt),Je.addEventListener("change",async()=>{xt&&(Je!=null&&Je.files)&&(await xt.handleFileSelect(Je.files),Je.value="")})),te.querySelector(".persona-attachment-drop-overlay")||te.appendChild(mu(X.dropOverlay))}else{pt.style.display="";let X=(Pd=r.attachments)!=null?Pd:{};Je&&(Je.accept=((Id=X.allowedTypes)!=null?Id:Hr).join(","),Je.multiple=((Wd=X.maxFiles)!=null?Wd:4)>1),xt&&xt.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else pt&&(pt.style.display="none"),xt&&xt.clearAttachments(),(Rd=te.querySelector(".persona-attachment-drop-overlay"))==null||Rd.remove();let Ut=(Hd=r.sendButton)!=null?Hd:{},bo=(Bd=Ut.useIcon)!=null?Bd:!1,Qr=(Dd=Ut.iconText)!=null?Dd:"\u2191",ut=Ut.iconName,kn=(Nd=Ut.tooltipText)!=null?Nd:"Send message",Wr=(Fd=Ut.showTooltip)!=null?Fd:!1,Cn=(Od=Ut.size)!=null?Od:"40px",Mn=Ut.backgroundColor,Wt=Ut.textColor;if(bo){if(Ne.style.width=Cn,Ne.style.height=Cn,Ne.style.minWidth=Cn,Ne.style.minHeight=Cn,Ne.style.fontSize="18px",Ne.style.lineHeight="1",Ne.innerHTML="",Wt?Ne.style.color=Wt:Ne.style.color="var(--persona-button-primary-fg, #ffffff)",ut){let X=parseFloat(Cn)||24,bt=(Wt==null?void 0:Wt.trim())||"currentColor",Bt=ge(ut,X,bt,2);Bt?Ne.appendChild(Bt):Ne.textContent=Qr}else Ne.textContent=Qr;Ne.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Mn?(Ne.style.backgroundColor=Mn,Ne.classList.remove("persona-bg-persona-primary")):(Ne.style.backgroundColor="",Ne.classList.add("persona-bg-persona-primary"))}else Ne.textContent=(_d=($d=r.copy)==null?void 0:$d.sendButtonLabel)!=null?_d:"Send",Ne.style.width="",Ne.style.height="",Ne.style.minWidth="",Ne.style.minHeight="",Ne.style.fontSize="",Ne.style.lineHeight="",Ne.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",Mn?(Ne.style.backgroundColor=Mn,Ne.classList.remove("persona-bg-persona-accent")):Ne.classList.add("persona-bg-persona-accent"),Wt?Ne.style.color=Wt:Ne.classList.add("persona-text-white");Ut.borderWidth?(Ne.style.borderWidth=Ut.borderWidth,Ne.style.borderStyle="solid"):(Ne.style.borderWidth="",Ne.style.borderStyle=""),Ut.borderColor?Ne.style.borderColor=Ut.borderColor:Ne.style.borderColor="",Ut.paddingX?(Ne.style.paddingLeft=Ut.paddingX,Ne.style.paddingRight=Ut.paddingX):(Ne.style.paddingLeft="",Ne.style.paddingRight=""),Ut.paddingY?(Ne.style.paddingTop=Ut.paddingY,Ne.style.paddingBottom=Ut.paddingY):(Ne.style.paddingTop="",Ne.style.paddingBottom="");let $t=an==null?void 0:an.querySelector(".persona-send-button-tooltip");if(Wr&&kn)if($t)$t.textContent=kn,$t.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=kn,an==null||an.insertBefore(X,Ne)}else $t&&($t.style.display="none");let Rt=(Vd=(Ud=r.layout)==null?void 0:Ud.contentMaxWidth)!=null?Vd:j()?(zd=(qd=(jd=r.launcher)==null?void 0:jd.composerBar)==null?void 0:qd.contentMaxWidth)!=null?zd:"720px":void 0;Rt?(Qe.style.maxWidth=Rt,Qe.style.marginLeft="auto",Qe.style.marginRight="auto",Qe.style.width="100%",Pt&&(Pt.style.maxWidth=Rt,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Ft&&(Ft.style.maxWidth=Rt,Ft.style.marginLeft="auto",Ft.style.marginRight="auto")):(Qe.style.maxWidth="",Qe.style.marginLeft="",Qe.style.marginRight="",Qe.style.width="",Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""),Ft&&(Ft.style.maxWidth="",Ft.style.marginLeft="",Ft.style.marginRight=""));let jt=(Jd=r.statusIndicator)!=null?Jd:{},Ln=(Kd=jt.visible)!=null?Kd:!0;if(qt.style.display=Ln?"":"none",_){let X=_.getStatus();He(qt,(Bt=>{var st,Ct,nn,gn;return Bt==="idle"?(st=jt.idleText)!=null?st:fn.idle:Bt==="connecting"?(Ct=jt.connectingText)!=null?Ct:fn.connecting:Bt==="connected"?(nn=jt.connectedText)!=null?nn:fn.connected:Bt==="error"?(gn=jt.errorText)!=null?gn:fn.error:fn[Bt]})(X),jt,X)}qt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let $n=jt.align==="left"?"persona-text-left":jt.align==="center"?"persona-text-center":"persona-text-right";qt.classList.add($n)},open(){$()&&It(!0,"api")},close(){$()&&It(!1,"api")},toggle(){$()&&It(!H,"api")},clearChat(){yn=!1,_.clearMessages(),Fn.clear(),jr();try{localStorage.removeItem(Zo),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zo}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Zo)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.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)}d={},k.syncFromMetadata(),Q==null||Q.clear(),re==null||re.update()},setMessage(c){return!ie||_.isStreaming()?!1:(!H&&$()&&It(!0,"system"),ie.value=c,ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let m=(c==null?void 0:c.trim())||ie.value.trim();return m?(!H&&$()&&It(!0,"system"),ie.value="",ie.style.height="auto",_.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return _.isStreaming()?!1:((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(_.isVoiceActive()||(!H&&$()&&It(!0,"system"),lt.manuallyDeactivated=!1,Tn(),_.toggleVoice().then(()=>{lt.active=_.isVoiceActive(),Jn("user"),_.isVoiceActive()&&Gr()})),!0):On?!0:gs()?(!H&&$()&&It(!0,"system"),lt.manuallyDeactivated=!1,Tn(),mo("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{lt.active=!1,lt.manuallyDeactivated=!0,Tn(),Jn("user"),ar()}),!0):!1:On?(lt.manuallyDeactivated=!0,Tn(),sr("user"),!0):!1},injectMessage(c){return!H&&$()&&It(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!H&&$()&&It(!0,"system");let m=_.injectAssistantMessage(c);return F&&(F=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),m},injectUserMessage(c){return!H&&$()&&It(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!H&&$()&&It(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!H&&$()&&It(!0,"system"),_.injectMessageBatch(c)},injectTestMessage(c){!H&&$()&&It(!0,"system"),_.injectTestEvent(c)},async connectStream(c,m){return _.connectStream(c,m)},__pushEventStreamEvent(c){Q&&Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!fe||!Q||Cr()},hideEventStream(){Me&&Yn()},isEventStreamVisible(){return Me},showArtifacts(){Xn(r)&&(yn=!1,Bn(),mt==null||mt.setMobileOpen(!0))},hideArtifacts(){Xn(r)&&(yn=!0,Bn())},upsertArtifact(c){return Xn(r)?(yn=!1,_.upsertArtifact(c)):null},selectArtifact(c){Xn(r)&&_.selectArtifact(c)},clearArtifacts(){Xn(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return C&&!H&&!j()||!ie?!1:(ie.focus(),!0)},async resolveApproval(c,m){let b=_.getMessages().find(T=>{var B;return T.variant==="approval"&&((B=T.approval)==null?void 0:B.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);return _.resolveApproval(b.approval,m)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return o.on(c,m)},off(c,m){o.off(c,m)},isOpen(){return $()&&H},isVoiceActive(){return lt.active},getState(){return{open:$()&&H,launcherEnabled:C,voiceActive:lt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!H&&$()&&It(!0,"system");let m=Qe.querySelector(".persona-feedback-container");m&&m.remove();let y=qi({onSubmit:async(b,T)=>{var B;_.isClientTokenMode()&&await _.submitCSATFeedback(b,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});Qe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!H&&$()&&It(!0,"system");let m=Qe.querySelector(".persona-feedback-container");m&&m.remove();let y=zi({onSubmit:async(b,T)=>{var B;_.isClientTokenMode()&&await _.submitNPSFeedback(b,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});Qe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return _.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return _.submitNPSFeedback(c,m)},destroy(){hr!=null&&(clearInterval(hr),hr=null),dt.forEach(c=>c()),G.remove(),ve==null||ve.remove(),A==null||A.destroy(),q==null||q.remove(),Nn&&P.removeEventListener("click",Nn)}};if((((Jl=t==null?void 0:t.debugTools)!=null?Jl:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:y=>y?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,dt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=z=>{let I=z.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",m),dt.push(()=>{window.removeEventListener("persona:focusInput",m)}),fe){let z=ye=>{let le=ye.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&Zt.showEventStream()},I=ye=>{let le=ye.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",I),dt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",I)})}let y=z=>{let I=z.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.showArtifacts()},b=z=>{let I=z.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.hideArtifacts()},T=z=>{let I=z.detail;I!=null&&I.instanceId&&I.instanceId!==c||I!=null&&I.artifact&&Zt.upsertArtifact(I.artifact)},B=z=>{let I=z.detail;I!=null&&I.instanceId&&I.instanceId!==c||typeof(I==null?void 0:I.id)=="string"&&Zt.selectArtifact(I.id)},N=z=>{let I=z.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",N),dt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",N)})}let Kn=vy(r.persistState);if(Kn&&$()){let c=wy(Kn.storage),m=`${Kn.keyPrefix}widget-open`,y=`${Kn.keyPrefix}widget-voice`,b=`${Kn.keyPrefix}widget-voice-mode`;if(c){let T=((Kl=Kn.persist)==null?void 0:Kl.openState)&&c.getItem(m)==="true",B=((Gl=Kn.persist)==null?void 0:Gl.voiceState)&&c.getItem(y)==="true",N=((Ql=Kn.persist)==null?void 0:Ql.voiceState)&&c.getItem(b)==="true";if(T&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var z;if(B||N)Zt.startVoiceRecognition();else if((z=Kn.persist)!=null&&z.focusInput){let I=e.querySelector("textarea");I&&I.focus()}},100)},0),(Xl=Kn.persist)!=null&&Xl.openState&&(o.on("widget:opened",()=>{c.setItem(m,"true")}),o.on("widget:closed",()=>{c.setItem(m,"false")})),(Yl=Kn.persist)!=null&&Yl.voiceState&&(o.on("voice:state",z=>{c.setItem(y,z.active?"true":"false")}),o.on("user:message",z=>{c.setItem(b,z.viaVoice?"true":"false")})),Kn.clearOnChatClear){let z=()=>{c.removeItem(m),c.removeItem(y),c.removeItem(b)},I=()=>z();window.addEventListener("persona:clear-chat",I),dt.push(()=>{window.removeEventListener("persona:clear-chat",I)})}}}return u&&$()&&setTimeout(()=>{Zt.open()},0),Lr(),Zt};var Cy=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},gu=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Xi=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=""},fu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Xi(e)},Ki=e=>{e.style.transition=""},Gi=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=""},Qi=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Xa=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},Ay=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Sy=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},hu=(e,n,t,r,s,o,a)=>{var v,x,k,C,L,D;let i=lr(o),d=i.reveal==="push";Ay(e,n,t,r,d),Sy(e,n,t,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,p=(C=(k=o==null?void 0:o.launcher)==null?void 0:k.mobileBreakpoint)!=null?C:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Gi(n),Ki(r),fu(r),Qi(t),Xa(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((D=(L=o==null?void 0:o.launcher)==null?void 0:L.zIndex)!=null?D:hn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),fu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Gi(n),Ki(r),Qi(t),Xa(s,r);let W=i.animate?"transform 180ms ease":"none",E=i.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":E;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=W,r.style.transform=M,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ki(r),Xi(r),Xa(s,r);let W=Cy(i.width,e.clientWidth),E=Math.max(0,e.clientWidth),M=i.animate?"transform 180ms ease":"none",O=i.side==="right"?a?`translateX(-${W}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${W}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${E+W}px`,n.style.transition=M,n.style.transform=O,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${E}px`,t.style.maxWidth=`${E}px`,t.style.minWidth=`${E}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Gi(n),Xi(r),Qi(t),Xa(s,r);let W=i.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=a?i.width:"0px",M=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",O=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${E}`,r.style.width=E,r.style.maxWidth=E,r.style.minWidth=E,r.style.minHeight="0",r.style.position="relative",r.style.overflow=W||O?"hidden":"visible",r.style.transition=M,W&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Ey=(e,n)=>{let t=e.ownerDocument.createElement("div");return gu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){gu(t,r)},destroy(){t.remove()}}},Ty=(e,n)=>{var L,D,W,E;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(D=(L=n==null?void 0:n.launcher)==null?void 0:L.enabled)==null||D?(E=(W=n==null?void 0:n.launcher)==null?void 0:W.autoExpand)!=null?E:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),lr(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{hu(a,i,d,l,u,n,p)}),f.observe(a))},x=()=>{hu(a,i,d,l,u,n,p),v()},k=a.ownerDocument.defaultView,C=()=>{x()};return k==null||k.addEventListener("resize",C),lr(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(M){let O=M.launcherEnabled?M.open:!0;p!==O&&(p=O,x())},updateConfig(M){var O,j;n=M,((j=(O=n==null?void 0:n.launcher)==null?void 0:O.enabled)!=null?j:!0)===!1&&(p=!0),x()},destroy(){k==null||k.removeEventListener("resize",C),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},Ya=(e,n)=>on(n)?Ty(e,n):Ey(e,n);var Yi={},ky=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},My=()=>{try{if(typeof Yi!="undefined"&&Yi.url)return new URL("../widget.css",Yi.url).href}catch{}return null},yu=(e,n)=>{let t=My(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},bu=e=>{var k;let n=ky(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=Ya(n,s),a,i=[],d=(C,L)=>{var M,O;let W=!((O=(M=L==null?void 0:L.launcher)==null?void 0:M.enabled)!=null?O:!0)||on(L),E=r.createElement("div");if(E.setAttribute("data-persona-root","true"),W&&(E.style.height="100%",E.style.display="flex",E.style.flexDirection="column",E.style.flex="1",E.style.minHeight="0"),t){let j=C.attachShadow({mode:"open"});j.appendChild(E),yu(j,r)}else C.appendChild(E),yu(C,r);return n.id&&E.setAttribute("data-persona-instance",n.id),E},l=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let C=d(o.host,s);a=Ji(C,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(C=>C()),i=[],a.destroy()};p(),(k=e.onReady)==null||k.call(e);let g=C=>{f(),o.destroy(),o=Ya(n,C),s=C,p()},v={update(C){var O,j,$,H,F,K;let L={...s,...C,launcher:{...(O=s==null?void 0:s.launcher)!=null?O:{},...(j=C==null?void 0:C.launcher)!=null?j:{},dock:{...(H=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?H:{},...(K=(F=C==null?void 0:C.launcher)==null?void 0:F.dock)!=null?K:{}}}},D=on(s),W=on(L),E=Zr(s),M=Zr(L);if(D!==W||E!==M){g(L);return}s=L,o.updateConfig(s),a.update(C),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(C,L,D){if(L==="host")return o.host;if(L in C)return Reflect.get(C,L,D);let W=a[L];return typeof W=="function"?W.bind(a):W}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Au=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Ly=new Set(["button","a","input","select","textarea","details","summary"]),Py=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Zi=/\b(product|card|item|listing|result)\b/i,tl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Iy=3e3,Wy=100;function Su(e){let n=typeof e.className=="string"?e.className:"";if(Zi.test(n)||e.id&&Zi.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Zi.test(r.value))return!0}return!1}function Eu(e){var n;return tl.test(((n=e.textContent)!=null?n:"").trim())}function Tu(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Ry(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function xu(e){let n=e.match(tl);return n?n[0]:null}function vu(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Hy(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var By="commerce-card",Dy="result-card";function wu(e){return!Su(e)||!Eu(e)||!Tu(e)&&!Ry(e)?0:5200}function Cu(e){var r;return!Su(e)||Eu(e)||!Tu(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var ku=[{id:By,scoreElement(e){return wu(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||tl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(wu(e)===0)return null;let{title:t,href:r}=vu(e),s=(u=(l=xu(((d=e.textContent)!=null?d:"").trim()))!=null?l:xu(n.text))!=null?u:"",o=Hy(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
101
|
-
`)}},{id:
|
|
102
|
-
`)}}];function
|
|
100
|
+
`}if(!b&&!c){let Rt="max-height: -moz-available !important; max-height: stretch !important;",Ut=m?"":"padding-top: 1.25em !important;",Ln=m?"":`z-index: ${($t=(Wt=r.launcher)==null?void 0:Wt.zIndex)!=null?$t:hn} !important;`;G.style.cssText+=Rt+Ut+Ln}S()};Zn(),So(e,r),za(e,r),Va(e,r);let dt=[];dt.push(()=>{document.removeEventListener("keydown",Or)});let Jt=null,Kt=null;dt.push(()=>{Jt==null||Jt(),Jt=null,Kt==null||Kt(),Kt=null}),In&&dt.push(()=>{In==null||In.disconnect(),In=null}),dt.push(()=>{bn==null||bn(),bn=null,Er(),kt&&(kt.remove(),kt=null),mt==null||mt.element.style.removeProperty("width"),mt==null||mt.element.style.removeProperty("maxWidth")}),fe&&dt.push(()=>{ae!==null&&(cancelAnimationFrame(ae),ae=null),re==null||re.destroy(),re=null,Q==null||Q.destroy(),Q=null,ee=null});let Dn=null,jr=()=>{Dn&&(Dn(),Dn=null),r.colorScheme==="auto"&&(Dn=yi(()=>{So(e,r)}))};jr(),dt.push(()=>{Dn&&(Dn(),Dn=null)});let Vn=(_l=r.features)==null?void 0:_l.streamAnimation;if(Vn!=null&&Vn.type&&Vn.type!=="none"){let c=Is(Vn.type,Vn.plugins);c&&(vi(c,e),dt.push(()=>Tp(e)))}let er=Yp(Ft),Nn=null,_,de=!1,Fn=vp(),tr=new Map,fr=new Map,ts=0,nr=Ea(),rr=0,or=null,Tr=!1,co=!1,Us=4,ns=24,qs=80,Lo=new Map,lt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},rs=(Ul=(jl=r.voiceRecognition)==null?void 0:jl.autoResume)!=null?Ul:!1,Jn=c=>{o.emit("voice:state",{active:lt.active,source:c,timestamp:Date.now()})},Tn=()=>{g(c=>({...c,voiceState:{active:lt.active,timestamp:Date.now(),manuallyDeactivated:lt.manuallyDeactivated}}))},zs=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Vi(d.voiceState),m=!!c.active,y=Number((T=c.timestamp)!=null?T:0);lt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-y<by&&setTimeout(()=>{var B,N;lt.active||(lt.manuallyDeactivated=!1,((N=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:N.type)==="runtype"?_.toggleVoice().then(()=>{lt.active=_.isVoiceActive(),Jn("restore"),_.isVoiceActive()&&Gr()}):mo("restore"))},1e3)},Vs=()=>_?uu(_.getMessages()).filter(c=>!c.__skipPersist):[];function Po(c){if(!(i!=null&&i.save))return;let y={messages:c?uu(c):_?Vs():[],metadata:d,artifacts:Wn.artifacts,selectedArtifactId:Wn.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let kr=null,Js=()=>G.querySelector("#persona-scroll-container")||me,po=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),Tr=!1},os=()=>{or!==null&&(cancelAnimationFrame(or),or=null),co=!1,po()},Mr=()=>{if(!St()||Me){it.parentNode&&it.remove(),it.style.display="none";return}it.parentNode!==te&&te.appendChild(it),jn();let c=ks(me)>0;it.style.display=nr.isFollowing()||!c?"none":""},ss=()=>{nr.pause()&&(os(),Mr())},Ur=()=>{nr.resume(),Mr()},qr=(c=!1)=>{nr.isFollowing()&&(!c&&!de||(or!==null&&(cancelAnimationFrame(or),or=null),co=!0,or=requestAnimationFrame(()=>{or=null,co=!1,nr.isFollowing()&&Ks(Js(),c?220:140)})))},Ks=(c,m=500)=>{let y=c.scrollTop,b=ks(c),T=b-y;if(Math.abs(T)<1){rr=c.scrollTop;return}if(Math.abs(T)>=qs){po(),Tr=!0,c.scrollTop=b,rr=c.scrollTop,Tr=!1;return}po();let B=performance.now();Tr=!0;let N=I=>1-Math.pow(1-I,3),z=I=>{if(!nr.isFollowing()){po();return}let ye=ks(c);ye!==b&&(b=ye,T=b-y);let le=I-B,Y=Math.min(le/m,1),ue=N(Y),be=y+T*ue;c.scrollTop=be,rr=c.scrollTop,Y<1?kr=requestAnimationFrame(z):(c.scrollTop=b,rr=c.scrollTop,kr=null,Tr=!1)};kr=requestAnimationFrame(z)},Gs=c=>{let m=new Map;c.forEach(y=>{let b=Lo.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Lo.clear(),m.forEach((y,b)=>{Lo.set(b,y)})},uo=(c,m,y)=>{var ze,nt,rt,Ee,Ae,$e;let b=document.createElement("div"),B=(()=>{var we;let S=s.find(Le=>Le.renderLoadingIndicator);if(S!=null&&S.renderLoadingIndicator)return S.renderLoadingIndicator;if((we=r.loadingIndicator)!=null&&we.render)return r.loadingIndicator.render})(),N=(S,we)=>we==null?!1:typeof we=="string"?(S.textContent=we,!0):(S.appendChild(we),!0),z=new Set,I=new Set,ye=s.some(S=>S.renderAskUserQuestion),le=[],Y=[],ue=r.enableComponentStreaming!==!1;if(m.forEach(S=>{var vn,pn,Ge,ot,Cn,mn,fo,ho,yo,Bo,Do,jt,bo,Qr;z.add(S.id);let we=ye&&to(S),Le=!we&&S.role==="assistant"&&!S.variant&&ue&&ji(S);if(!Le&&fr.has(S.id)){let ut=c.querySelector(`#wrapper-${S.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),fr.delete(S.id)}let Ue=to(S)?`:${(vn=S.agentMetadata)!=null&&vn.askUserQuestionAnswered?"a":"u"}:${(pn=S.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(S.agentMetadata.askUserQuestionAnswers).length:0}`:"",he=xp(S,ts)+Ue,At=we||Le?null:Cp(Fn,S.id,he);if(At){b.appendChild(At.cloneNode(!0)),to(S)&&((Ge=S.toolCall)!=null&&Ge.id)&&((ot=S.agentMetadata)==null?void 0:ot.awaitingLocalTool)===!0&&!((Cn=S.agentMetadata)!=null&&Cn.askUserQuestionAnswered)&&(I.add(S.toolCall.id),$s(S,r,ce.composerOverlay));return}let tt=null,Xt=s.find(ut=>!!(S.variant==="reasoning"&&ut.renderReasoning||S.variant==="tool"&&ut.renderToolCall||S.variant==="approval"&&ut.renderApproval||!S.variant&&ut.renderMessage)),dn=(mn=r.layout)==null?void 0:mn.messages;if(to(S)&&((fo=S.agentMetadata)==null?void 0:fo.askUserQuestionAnswered)===!0){tr.delete(S.id);let ut=c.querySelector(`#wrapper-${S.id}`);ut==null||ut.removeAttribute("data-preserve-runtime");return}if(to(S)&&((yo=(ho=r.features)==null?void 0:ho.askUserQuestion)==null?void 0:yo.enabled)!==!1){let ut=s.find(kn=>typeof kn.renderAskUserQuestion=="function");if(ut&&Et.current){let kn=tr.get(S.id),Wr=kn!==he,wn=null;if(Wr){let{payload:$t,complete:Rt}=no(S),Ut=S.id,Ln=()=>{var $n;return($n=Et.current)==null?void 0:$n.getMessages().find(en=>en.id===Ut)};wn=ut.renderAskUserQuestion({message:S,payload:$t,complete:Rt,resolve:$n=>{var yr;let en=Ln();en&&((yr=Et.current)==null||yr.resolveAskUserQuestion(en,$n))},dismiss:()=>{var en,yr,Rr;let $n=Ln();(en=$n==null?void 0:$n.agentMetadata)!=null&&en.awaitingLocalTool&&((yr=Et.current)==null||yr.markAskUserQuestionResolved($n),(Rr=Et.current)==null||Rr.resolveAskUserQuestion($n,"(dismissed)"))},config:r})}let Mn=kn!=null;if(Wr&&wn===null&&!Mn){((Bo=S.agentMetadata)==null?void 0:Bo.awaitingLocalTool)===!0&&!((Do=S.agentMetadata)!=null&&Do.askUserQuestionAnswered)&&(I.add(S.toolCall.id),$s(S,r,ce.composerOverlay));return}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${S.id}`,Wt.setAttribute("data-wrapper-id",S.id),Wt.setAttribute("data-ask-plugin-stub","true"),Wt.setAttribute("data-preserve-runtime","true"),b.appendChild(Wt),le.push({messageId:S.id,fingerprint:he,bubble:wn});return}else{((jt=S.agentMetadata)==null?void 0:jt.awaitingLocalTool)===!0&&!((bo=S.agentMetadata)!=null&&bo.askUserQuestionAnswered)&&(I.add(S.toolCall.id),$s(S,r,ce.composerOverlay));return}}else if(Xt)if(S.variant==="reasoning"&&S.reasoning&&Xt.renderReasoning){if(!We)return;tt=Xt.renderReasoning({message:S,defaultRenderer:()=>Ei(S,r),config:r})}else if(S.variant==="tool"&&S.toolCall&&Xt.renderToolCall){if(!_e)return;tt=Xt.renderToolCall({message:S,defaultRenderer:()=>Ti(S,r),config:r})}else if(S.variant==="approval"&&S.approval&&Xt.renderApproval){if(r.approval===!1)return;tt=Xt.renderApproval({message:S,defaultRenderer:()=>Ri(S,r),config:r})}else Xt.renderMessage&&(tt=Xt.renderMessage({message:S,defaultRenderer:()=>{let ut=Fs(S,y,dn,r.messageActions,Re,{loadingIndicatorRenderer:B,widgetConfig:r});return S.role!=="user"&&Di(ut,S,r,_),ut},config:r}));if(!tt&&Le){let ut=Ui(S);if(ut){let kn=fr.get(S.id),Wr=kn!==he,wn=r.wrapComponentDirectiveInBubble!==!1,Mn=null;if(Wr){let Wt=_i(ut,{config:r,message:S,transform:y});if(Wt)if(wn){let $t=document.createElement("div");if($t.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(" "),$t.id=`bubble-${S.id}`,$t.setAttribute("data-message-id",S.id),S.content&&S.content.trim()){let Rt=document.createElement("div");Rt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Rt.innerHTML=y({text:S.content,message:S,streaming:!!S.streaming,raw:S.rawContent}),$t.appendChild(Rt)}$t.appendChild(Wt),Mn=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${S.id}`,$t.setAttribute("data-message-id",S.id),$t.setAttribute("data-persona-component-directive","true"),S.content&&S.content.trim()){let Rt=document.createElement("div");Rt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Rt.innerHTML=y({text:S.content,message:S,streaming:!!S.streaming,raw:S.rawContent}),$t.appendChild(Rt)}$t.appendChild(Wt),Mn=$t}}if(Mn||kn!=null){let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${S.id}`,Wt.setAttribute("data-wrapper-id",S.id),Wt.setAttribute("data-component-directive-stub","true"),Wt.setAttribute("data-preserve-runtime","true"),wn||Wt.classList.add("persona-w-full"),b.appendChild(Wt),Y.push({messageId:S.id,fingerprint:he,bubble:Mn});return}}}if(!tt)if(S.variant==="reasoning"&&S.reasoning){if(!We)return;tt=Ei(S,r)}else if(S.variant==="tool"&&S.toolCall){if(!_e)return;tt=Ti(S,r)}else if(S.variant==="approval"&&S.approval){if(r.approval===!1)return;tt=Ri(S,r)}else{let ut=(Qr=r.layout)==null?void 0:Qr.messages;ut!=null&&ut.renderUserMessage&&S.role==="user"?tt=ut.renderUserMessage({message:S,config:r,streaming:!!S.streaming}):ut!=null&&ut.renderAssistantMessage&&S.role==="assistant"?tt=ut.renderAssistantMessage({message:S,config:r,streaming:!!S.streaming}):tt=Fs(S,y,ut,r.messageActions,Re,{loadingIndicatorRenderer:B,widgetConfig:r}),S.role!=="user"&&tt&&Di(tt,S,r,_)}let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id=`wrapper-${S.id}`,Tt.setAttribute("data-wrapper-id",S.id),S.role==="user"&&Tt.classList.add("persona-justify-end"),(tt==null?void 0:tt.getAttribute("data-persona-component-directive"))==="true"&&Tt.classList.add("persona-w-full"),Tt.appendChild(tt),wp(Fn,S.id,he,Tt),b.appendChild(Tt)}),ce.composerOverlay&&ce.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(we=>{let Le=we.getAttribute("data-persona-ask-sheet-for");Le&&!I.has(Le)&&ko(ce.composerOverlay,Le)}),(nt=(ze=r.features)==null?void 0:ze.toolCallDisplay)!=null&&nt.grouped){let S=[],we=[];m.forEach(Le=>{if(Le.variant==="tool"&&Le.toolCall&&_e){we.push(Le);return}we.length>1&&S.push(we),we=[]}),we.length>1&&S.push(we),S.forEach((Le,Ue)=>{var pn,Ge;let he=Le.map(ot=>Array.from(b.children).find(Cn=>Cn instanceof HTMLElement&&Cn.getAttribute("data-wrapper-id")===ot.id)).filter(ot=>!!ot);if(he.length<2)return;let At=document.createElement("div");At.className="persona-flex",At.id=`wrapper-tool-group-${Ue}-${Le[0].id}`,At.setAttribute("data-wrapper-id",`tool-group-${Ue}-${Le[0].id}`);let tt=document.createElement("div");tt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",tt.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${Le.length} tools`,Tt=(Ge=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Ge.call(pn,{messages:Le,toolCalls:Le.map(ot=>ot.toolCall).filter(ot=>!!ot),defaultSummary:dn,config:r});N(Xt,Tt)||(Xt.textContent=dn);let vn=document.createElement("div");vn.className="persona-tool-group-stack persona-flex persona-flex-col",tt.append(Xt,vn),At.appendChild(tt),he[0].before(At),he.forEach((ot,Cn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Cn<he.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(ot),vn.appendChild(mn)})})}Ap(Fn,z);let be=m.some(S=>S.role==="assistant"&&S.streaming),Ie=m[m.length-1],Ye=(Ie==null?void 0:Ie.role)==="assistant"&&!Ie.streaming&&Ie.variant!=="approval";if(de&&m.some(S=>S.role==="user")&&!be&&!Ye){let S={config:r,streaming:!0,location:"standalone",defaultRenderer:Vo},we=s.find(Ue=>Ue.renderLoadingIndicator),Le=null;if(we!=null&&we.renderLoadingIndicator&&(Le=we.renderLoadingIndicator(S)),Le===null&&((rt=r.loadingIndicator)!=null&&rt.render)&&(Le=r.loadingIndicator.render(S)),Le===null&&(Le=Vo()),Le){let Ue=document.createElement("div"),he=((Ee=r.loadingIndicator)==null?void 0:Ee.showBubble)!==!1;Ue.className=he?["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(" "),Ue.setAttribute("data-typing-indicator","true"),Ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ue.appendChild(Le);let At=document.createElement("div");At.className="persona-flex",At.id="wrapper-typing-indicator",At.setAttribute("data-wrapper-id","typing-indicator"),At.appendChild(Ue),b.appendChild(At)}}if(!de&&m.length>0){let S=m[m.length-1],we={config:r,lastMessage:S,messageCount:m.length},Le=s.find(he=>he.renderIdleIndicator),Ue=null;if(Le!=null&&Le.renderIdleIndicator&&(Ue=Le.renderIdleIndicator(we)),Ue===null&&((Ae=r.loadingIndicator)!=null&&Ae.renderIdle)&&(Ue=r.loadingIndicator.renderIdle(we)),Ue){let he=document.createElement("div"),At=(($e=r.loadingIndicator)==null?void 0:$e.showBubble)!==!1;he.className=At?["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(" "),he.setAttribute("data-idle-indicator","true"),he.appendChild(Ue);let tt=document.createElement("div");tt.className="persona-flex",tt.id="wrapper-idle-indicator",tt.setAttribute("data-wrapper-id","idle-indicator"),tt.appendChild(he),b.appendChild(tt)}}if(Sa(c,b),le.length>0)for(let{messageId:S,fingerprint:we,bubble:Le}of le){let Ue=c.querySelector(`#wrapper-${S}`);Ue&&Le!==null&&(Ue.replaceChildren(Le),Ue.setAttribute("data-bubble-fp",we),tr.set(S,we))}if(tr.size>0)for(let S of tr.keys())z.has(S)||tr.delete(S);if(Y.length>0)for(let{messageId:S,fingerprint:we,bubble:Le}of Y){let Ue=c.querySelector(`#wrapper-${S}`);Ue&&Le!==null&&(Ue.replaceChildren(Le),Ue.setAttribute("data-bubble-fp",we),fr.set(S,we))}if(fr.size>0)for(let S of fr.keys())z.has(S)||fr.delete(S)},zr=null,Qs=()=>{var y;if(zr)return;let c=b=>{let T=b.composedPath();T.includes(G)||ve&&T.includes(ve)||Mt(!1,"user")};zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},as=()=>{var m;if(!zr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",zr,!0),zr=null};dt.push(()=>as());let Vr=null,Xs=()=>{var y;if(Vr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Mt(!1,"user"))};Vr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},is=()=>{var m;if(!Vr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Vr,!0),Vr=null};dt.push(()=>is());let Jr=!1,ls=new Set,Ys=()=>{var m,y,b,T;let c=(b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},Lr=()=>{var nt,rt,Ee,Ae;if(!U())return;let c=ce.peekBanner,m=ce.peekTextNode;if(!c||!m)return;if(H){c.classList.remove("persona-pill-peek--visible");return}let y=(nt=_==null?void 0:_.getMessages())!=null?nt:[],b;for(let $e=y.length-1;$e>=0;$e--){let S=y[$e];if(S.role==="assistant"&&S.content){b=S;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let T=b.content,B=!!b.streaming,N=Ys(),z=Ma(N),I=z.type!=="none"?Is(z.type,N==null?void 0:N.plugins):null,ye=((rt=I==null?void 0:I.isAnimating)==null?void 0:rt.call(I,b))===!0,le=I!==null&&(B||ye);le&&I&&!ls.has(I.name)&&(vi(I,e),ls.add(I.name));let Y=le&&(I!=null&&I.containerClass)?I.containerClass:null,ue=(Ee=m.dataset.personaPeekStreamClass)!=null?Ee:null;ue&&ue!==Y&&(m.classList.remove(ue),delete m.dataset.personaPeekStreamClass),Y&&ue!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),le?(m.style.setProperty("--persona-stream-step",`${z.speed}ms`),m.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let be=le?La(T,z.buffer,I,b,B):T;if(le&&z.placeholder==="skeleton"&&B&&(!be||!be.trim())){let $e=document.createElement("div"),S=Rs();S.classList.add("persona-pill-peek__skeleton"),$e.appendChild(S),Sa(m,$e)}else{let $e=Math.max(0,be.length-100),S=be.length>100?be.slice(-100):be,we=Fo(S);if(!le||!I){let Le=be.length>100?`\u2026${S}`:S;m.textContent!==Le&&(m.textContent=Le)}else{let Le=we;(I.wrap==="char"||I.wrap==="word")&&(Le=Ws(we,I.wrap,`peek-${b.id}`,{skipTags:I.skipTags,startIndex:$e}));let Ue=document.createElement("div");if(Ue.innerHTML=Le,I.useCaret&&S.length>0){let he=Pa(),At=Ue.querySelectorAll(".persona-stream-char, .persona-stream-word"),tt=At[At.length-1];tt!=null&&tt.parentNode?tt.parentNode.insertBefore(he,tt.nextSibling):Ue.appendChild(he)}Sa(m,Ue),(Ae=I.onAfterRender)==null||Ae.call(I,{container:m,bubble:c,messageId:b.id,message:b,speed:z.speed,duration:z.duration})}}let ze=de||Jr;c.classList.toggle("persona-pill-peek--visible",ze)};if(U()){let c=ce.peekBanner;if(c){let b=T=>{T.preventDefault(),T.stopPropagation(),Mt(!0,"user")};c.addEventListener("pointerdown",b),dt.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Jr||(Jr=!0,Lr())},y=()=>{Jr&&(Jr=!1,Lr())};V.addEventListener("pointerenter",m),V.addEventListener("pointerleave",y),dt.push(()=>{V.removeEventListener("pointerenter",m),V.removeEventListener("pointerleave",y)}),ve&&(ve.addEventListener("pointerenter",m),ve.addEventListener("pointerleave",y),dt.push(()=>{ve.removeEventListener("pointerenter",m),ve.removeEventListener("pointerleave",y)}))}let Zs=c=>{var ue,be,Ie,Ye,ze,nt,rt,Ee;let m=(be=(ue=r.launcher)==null?void 0:ue.composerBar)!=null?be:{},y=(Ie=m.expandedSize)!=null?Ie:"anchored",b=(Ye=m.bottomOffset)!=null?Ye:"16px",T=m.collapsedMaxWidth,B=(ze=m.expandedMaxWidth)!=null?ze:"880px",N=(nt=m.expandedTopOffset)!=null?nt:"5vh",z=(rt=m.modalMaxWidth)!=null?rt:"880px",I=(Ee=m.modalMaxHeight)!=null?Ee:"min(90vh, 800px)",ye="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",Y=G.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",ve){let Ae=ve.style;Ae.bottom=b,Ae.width=T!=null?T:""}if(c&&y!=="fullscreen"){if(y==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=z,Y.maxWidth=ye,Y.maxHeight=I,Y.height=I;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${le})`,Y.top=N,Y.width=B,Y.maxWidth=ye}},Kr=()=>{var I,ye,le,Y,ue,be,Ie,Ye;if(!$())return;if(U()){let nt=(le=((ye=(I=r.launcher)==null?void 0:I.composerBar)!=null?ye:{}).expandedSize)!=null?le:"anchored",rt=H?"expanded":"collapsed";G.dataset.state=rt,G.dataset.expandedSize=nt,ve&&(ve.dataset.state=rt,ve.dataset.expandedSize=nt),G.style.removeProperty("display"),G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Zs(H),te.style.display=H?"flex":"none",Zn(),H?(Qs(),Xs()):(as(),is()),Lr();return}let c=on(r),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,y=(be=(ue=r.launcher)==null?void 0:ue.mobileBreakpoint)!=null?be:640,b=(Ye=(Ie=r.launcher)==null?void 0:Ie.mobileFullscreen)!=null?Ye:!0,T=m.innerWidth<=y,B=b&&T&&w,N=lr(r).reveal;H?(G.style.removeProperty("display"),G.style.display=c?"flex":"",G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0"),V.classList.add("persona-scale-100","persona-opacity-100"),A?A.element.style.display="none":q&&(q.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!B?(G.style.removeProperty("display"),G.style.display="flex",G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(G.style.setProperty("display","none","important"),G.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(G.style.display="",G.classList.add("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100"),V.classList.add("persona-scale-95","persona-opacity-0")),A?A.element.style.display=c?"none":"":q&&(q.style.display=c?"none":""))},Mt=(c,m="user")=>{var B,N;if(!$()||H===c)return;let y=H;H=c,Kr();let b=(()=>{var Ie,Ye,ze,nt,rt,Ee,Ae,$e,S,we;let z=(Ye=(Ie=r.launcher)==null?void 0:Ie.sidebarMode)!=null?Ye:!1,I=(ze=e.ownerDocument.defaultView)!=null?ze:window,ye=(rt=(nt=r.launcher)==null?void 0:nt.mobileFullscreen)!=null?rt:!0,le=(Ae=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?Ae:640,Y=I.innerWidth<=le,ue=on(r)&&ye&&Y,be=U()&&((we=(S=($e=r.launcher)==null?void 0:$e.composerBar)==null?void 0:S.expandedSize)!=null?we:"fullscreen")==="fullscreen";return z||ye&&Y&&w||ue||be})();if(H&&b){if(!Jt){let z=e.getRootNode(),I=z instanceof ShadowRoot?z.host:e.closest(".persona-host");I&&(Jt=Ci(I,(N=(B=r.launcher)==null?void 0:B.zIndex)!=null?N:hn))}Kt||(Kt=wi(e.ownerDocument))}else H||(Jt==null||Jt(),Jt=null,Kt==null||Kt(),Kt=null);H&&(ke(),qr(!0));let T={open:H,source:m,timestamp:Date.now()};H&&!y?o.emit("widget:opened",T):!H&&y&&o.emit("widget:closed",T),o.emit("widget:state",{open:H,launcherEnabled:w,voiceActive:lt.active,streaming:_.isStreaming()})},Io=c=>{zt(c?"stop":"send"),R&&(R.disabled=c),er.buttons.forEach(m=>{m.disabled=c}),Oe.dataset.personaComposerStreaming=c?"true":"false",Oe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Wo=()=>{lt.active||ie&&ie.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Wo(),200)});let cs=()=>{var y,b,T,B,N,z,I,ye,le,Y,ue;vr.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",dr.textContent=(B=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",ie.placeholder=(z=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?z:"How can I help...";let c=me.querySelector("[data-persona-intro-card]");if(c){let be=((I=r.copy)==null?void 0:I.showWelcomeCard)!==!1;c.style.display=be?"":"none",be?(me.classList.remove("persona-gap-3"),me.classList.add("persona-gap-6")):(me.classList.remove("persona-gap-6"),me.classList.add("persona-gap-3"))}!((le=(ye=r.sendButton)==null?void 0:ye.useIcon)!=null&&le)&&!(_!=null&&_.isStreaming())&&(Ne.textContent=(ue=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ue:"Send"),ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{g(m=>({...m,sessionId:c}))}});let hr=null,ea=()=>{hr==null&&(hr=setInterval(()=>{let c=Qe.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(hr),hr=null;return}let m=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=pa(m-b))})},100))};if(_=new As(r,{onMessagesChanged(c){uo(Qe,c,Se),ea(),_&&(c.some(T=>T.role==="user")?er.render([],_,ie,c):er.render(r.suggestionChips,_,ie,c,r.suggestionChipsConfig)),qr(!de),Gs(c);let m=[...c].reverse().find(b=>b.role==="user"),y=lt.lastUserMessageId;m&&m.id!==y&&(lt.lastUserMessageId=m.id,o.emit("user:message",m)),lt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Po(c),Lr()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};He(qt,(T=>{var B,N,z,I;return T==="idle"?(B=m.idleText)!=null?B:fn.idle:T==="connecting"?(N=m.connectingText)!=null?N:fn.connecting:T==="connected"?(z=m.connectedText)!=null?z:fn.connected:T==="error"?(I=m.errorText)!=null?I:fn.error:fn[T]})(c),m,c)},onStreamingChanged(c){de=c,Io(c),_&&uo(Qe,_.getMessages(),Se),c||qr(!0),Lr()},onVoiceStatusChanged(c){var m,y;if(((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":ar(),na();break;case"speaking":ar(),ra();break;default:c==="idle"&&_.isBargeInActive()?(ar(),Gr(),R==null||R.setAttribute("aria-label","End voice session")):(lt.active=!1,ar(),Jn("system"),Tn());break}},onArtifactsState(c){Wn=c,Bn(),Po()}}),Et.current=_,((zl=(ql=r.voiceRecognition)==null?void 0:ql.provider)==null?void 0:zl.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Q||r.onSSEEvent)&&_.setSSEEventCallback((c,m)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,m),Q==null||Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,y,b;c&&(c.metadata&&(d=Vi(c.metadata),k.syncFromMetadata()),(m=c.messages)!=null&&m.length&&_.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&_.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ds=()=>{var m,y,b;!U()||H||!((b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Mt(!0,"auto")},ps=c=>{var T;if(c.preventDefault(),_.isStreaming()){_.cancel();return}let m=ie.value.trim(),y=(T=xt==null?void 0:xt.hasAttachments())!=null?T:!1;if(!m&&!y)return;ds();let b;y&&(b=[],b.push(...xt.getContentParts()),m&&b.push(ya(m))),ie.value="",ie.style.height="auto",_.sendMessage(m,{contentParts:b}),y&&xt.clearAttachments()},us=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Ne.click())},ms=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!xt)return;let m=vy(c.clipboardData);m.length!==0&&(c.preventDefault(),await xt.handleFiles(m))},xn=null,On=!1,Pr=null,et=null,gs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,mo=(c="user")=>{var B,N,z,I,ye,le,Y;if(On||_.isStreaming())return;let m=gs();if(!m)return;xn=new m;let b=(N=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?N:2e3;xn.continuous=!0,xn.interimResults=!0,xn.lang="en-US";let T=ie.value;xn.onresult=ue=>{let be="",Ie="";for(let ze=0;ze<ue.results.length;ze++){let nt=ue.results[ze],rt=nt[0].transcript;nt.isFinal?be+=rt+" ":Ie=rt}let Ye=T+be+Ie;ie.value=Ye,Pr&&clearTimeout(Pr),(be||Ie)&&(Pr=window.setTimeout(()=>{let ze=ie.value.trim();ze&&xn&&On&&(sr(),ie.value="",ie.style.height="auto",_.sendMessage(ze,{viaVoice:!0}))},b))},xn.onerror=ue=>{ue.error!=="no-speech"&&sr()},xn.onend=()=>{if(On){let ue=ie.value.trim();ue&&ue!==T.trim()&&(ie.value="",ie.style.height="auto",_.sendMessage(ue,{viaVoice:!0})),sr()}};try{if(xn.start(),On=!0,lt.active=!0,c!=="system"&&(lt.manuallyDeactivated=!1),Jn(c),Tn(),R){let ue=(z=r.voiceRecognition)!=null?z:{};et={backgroundColor:R.style.backgroundColor,color:R.style.color,borderColor:R.style.borderColor,iconName:(I=ue.iconName)!=null?I:"mic",iconSize:parseFloat((Y=(le=ue.iconSize)!=null?le:(ye=r.sendButton)==null?void 0:ye.size)!=null?Y:"40")||24};let be=ue.recordingBackgroundColor,Ie=ue.recordingIconColor,Ye=ue.recordingBorderColor;if(R.classList.add("persona-voice-recording"),R.style.backgroundColor=be!=null?be:"var(--persona-voice-recording-bg, #ef4444)",R.style.color=Ie!=null?Ie:"var(--persona-voice-recording-indicator, #ffffff)",Ie){let ze=R.querySelector("svg");ze&&ze.setAttribute("stroke",Ie)}Ye&&(R.style.borderColor=Ye),R.setAttribute("aria-label","Stop voice recognition")}}catch{sr("system")}},sr=(c="user")=>{if(On){if(On=!1,Pr&&(clearTimeout(Pr),Pr=null),xn){try{xn.stop()}catch{}xn=null}if(lt.active=!1,Jn(c),Tn(),R){if(R.classList.remove("persona-voice-recording"),et){R.style.backgroundColor=et.backgroundColor,R.style.color=et.color,R.style.borderColor=et.borderColor;let m=R.querySelector("svg");m&&m.setAttribute("stroke",et.color||"currentColor"),et=null}R.setAttribute("aria-label","Start voice recognition")}}},ta=(c,m)=>{var nt,rt,Ee,Ae,$e,S,we,Le;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((nt=c==null?void 0:c.provider)==null?void 0:nt.type)==="runtype";if(!(y||b))return null;let B=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let z=(rt=c==null?void 0:c.iconName)!=null?rt:"mic",I=(Ee=m==null?void 0:m.size)!=null?Ee:"40px",ye=(Ae=c==null?void 0:c.iconSize)!=null?Ae:I,le=parseFloat(ye)||24,Y=($e=c==null?void 0:c.backgroundColor)!=null?$e:m==null?void 0:m.backgroundColor,ue=(S=c==null?void 0:c.iconColor)!=null?S:m==null?void 0:m.textColor;N.style.width=ye,N.style.height=ye,N.style.minWidth=ye,N.style.minHeight=ye,N.style.fontSize="18px",N.style.lineHeight="1",ue?N.style.color=ue:N.style.color="var(--persona-text, #111827)";let Ie=ge(z,le,ue||"currentColor",1.5);Ie?N.appendChild(Ie):N.textContent="\u{1F3A4}",Y?N.style.backgroundColor=Y:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),B.appendChild(N);let Ye=(we=c==null?void 0:c.tooltipText)!=null?we:"Start voice recognition";if(((Le=c==null?void 0:c.showTooltip)!=null?Le:!1)&&Ye){let Ue=h("div","persona-send-button-tooltip");Ue.textContent=Ye,B.appendChild(Ue)}return{micButton:N,micButtonWrapper:B}},Ro=()=>{var m,y,b,T,B;if(!R||et)return;let c=(m=r.voiceRecognition)!=null?m:{};et={backgroundColor:R.style.backgroundColor,color:R.style.color,borderColor:R.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((B=(T=c.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},Ho=(c,m)=>{var B,N,z,I,ye;if(!R)return;let y=R.querySelector("svg");y&&y.remove();let b=(ye=et==null?void 0:et.iconSize)!=null?ye:parseFloat((I=(z=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?z:(N=r.sendButton)==null?void 0:N.size)!=null?I:"40")||24,T=ge(c,b,m,1.5);T&&R.appendChild(T)},go=()=>{R&&R.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Gr=()=>{var T;if(!R)return;Ro();let c=(T=r.voiceRecognition)!=null?T:{},m=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(go(),R.classList.add("persona-voice-recording"),R.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",R.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let B=R.querySelector("svg");B&&B.setAttribute("stroke",y)}b&&(R.style.borderColor=b),R.setAttribute("aria-label","Stop voice recognition")},na=()=>{var z,I,ye,le,Y,ue,be,Ie;if(!R)return;Ro();let c=(z=r.voiceRecognition)!=null?z:{},m=_.getVoiceInterruptionMode(),y=(I=c.processingIconName)!=null?I:"loader",b=(le=(ye=c.processingIconColor)!=null?ye:et==null?void 0:et.color)!=null?le:"",T=(ue=(Y=c.processingBackgroundColor)!=null?Y:et==null?void 0:et.backgroundColor)!=null?ue:"",B=(Ie=(be=c.processingBorderColor)!=null?be:et==null?void 0:et.borderColor)!=null?Ie:"";go(),R.classList.add("persona-voice-processing"),R.style.backgroundColor=T,R.style.borderColor=B;let N=b||"currentColor";R.style.color=N,Ho(y,N),R.setAttribute("aria-label","Processing voice input"),m==="none"&&(R.style.cursor="default")},ra=()=>{var ye,le,Y,ue,be,Ie,Ye,ze,nt,rt,Ee,Ae;if(!R)return;Ro();let c=(ye=r.voiceRecognition)!=null?ye:{},m=_.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:y,T=(Ie=c.speakingIconColor)!=null?Ie:m==="barge-in"?(ue=(Y=c.recordingIconColor)!=null?Y:et==null?void 0:et.color)!=null?ue:"":(be=et==null?void 0:et.color)!=null?be:"",B=(nt=c.speakingBackgroundColor)!=null?nt:m==="barge-in"?(Ye=c.recordingBackgroundColor)!=null?Ye:"var(--persona-voice-recording-bg, #ef4444)":(ze=et==null?void 0:et.backgroundColor)!=null?ze:"",N=(Ae=c.speakingBorderColor)!=null?Ae:m==="barge-in"?(rt=c.recordingBorderColor)!=null?rt:"":(Ee=et==null?void 0:et.borderColor)!=null?Ee:"";go(),R.classList.add("persona-voice-speaking"),R.style.backgroundColor=B,R.style.borderColor=N;let z=T||"currentColor";R.style.color=z,Ho(b,z);let I=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";R.setAttribute("aria-label",I),m==="none"&&(R.style.cursor="default"),m==="barge-in"&&R.classList.add("persona-voice-recording")},ar=()=>{var c,m,y;R&&(go(),et&&(R.style.backgroundColor=(c=et.backgroundColor)!=null?c:"",R.style.color=(m=et.color)!=null?m:"",R.style.borderColor=(y=et.borderColor)!=null?y:"",Ho(et.iconName,et.color||"currentColor"),et=null),R.style.cursor="",R.setAttribute("aria-label","Start voice recognition"))},Ir=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let y=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{lt.active=!1,lt.manuallyDeactivated=!0,Tn(),Jn("user"),ar()});return}_.toggleVoice().then(()=>{lt.active=_.isVoiceActive(),lt.manuallyDeactivated=!_.isVoiceActive(),Tn(),Jn("user"),_.isVoiceActive()?Gr():ar()});return}if(On){let y=ie.value.trim();lt.manuallyDeactivated=!0,Tn(),sr("user"),y&&(ie.value="",ie.style.height="auto",_.sendMessage(y))}else lt.manuallyDeactivated=!1,Tn(),mo("user")};pr=Ir,R&&(R.addEventListener("click",Ir),dt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),ar()):sr("system"),R&&R.removeEventListener("click",Ir)}));let Ve=o.on("assistant:complete",()=>{rs&&(lt.active||lt.manuallyDeactivated||rs==="assistant"&&!lt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!lt.active&&!lt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.toggleVoice().then(()=>{lt.active=_.isVoiceActive(),Jn("auto"),_.isVoiceActive()&&Gr()}):mo("auto"))},600))});dt.push(Ve);let C=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(C);let j=()=>{Mt(!H,"user")},A=null,q=null;if(w&&!U()){let c=s.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Bs(r,j).element,onToggle:j});m&&(q=m)}q||(A=Bs(r,j))}A?e.appendChild(A.element):q&&e.appendChild(q),Kr(),er.render(r.suggestionChips,_,ie,void 0,r.suggestionChipsConfig),cs(),Io(_.isStreaming()),qr(!0),zs(),D&&(!w||U()?setTimeout(()=>Wo(),0):H&&setTimeout(()=>Wo(),200));let ke=()=>{var I,ye,le,Y,ue,be,Ie,Ye,ze,nt,rt,Ee,Ae,$e,S,we,Le,Ue,he,At,tt,Xt;if(U()){jn(),Kr();return}let c=on(r),m=(ye=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?ye:!1,y=c||m||((Y=(le=r.launcher)==null?void 0:le.fullHeight)!=null?Y:!1),b=(ue=e.ownerDocument.defaultView)!=null?ue:window,T=(Ie=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Ie:!0,B=(ze=(Ye=r.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?ze:640,N=b.innerWidth<=B,z=T&&N&&w;try{if(z){Zn(),So(e,r);return}if(O&&(O=!1,Zn(),So(e,r)),!w&&!c){V.style.height="",V.style.width="";return}if(!m&&!c){let dn=(rt=(nt=r==null?void 0:r.launcher)==null?void 0:nt.width)!=null?rt:r==null?void 0:r.launcherWidth,Tt=dn!=null?dn:Gn;V.style.width=Tt,V.style.maxWidth=Tt}if(gr(),!y){let dn=b.innerHeight,Tt=64,vn=(Ae=(Ee=r.launcher)==null?void 0:Ee.heightOffset)!=null?Ae:0,pn=Math.max(200,dn-Tt),Ge=Math.min(640,pn),ot=Math.max(200,Ge-vn);V.style.height=`${ot}px`}}finally{if(jn(),Kr(),H&&w){let Tt=(($e=e.ownerDocument.defaultView)!=null?$e:window).innerWidth<=((we=(S=r.launcher)==null?void 0:S.mobileBreakpoint)!=null?we:640),vn=(Ue=(Le=r.launcher)==null?void 0:Le.sidebarMode)!=null?Ue:!1,pn=(At=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?At:!0,Ge=on(r)&&pn&&Tt,ot=vn||pn&&Tt&&w||Ge;if(ot&&!Kt){let Cn=e.getRootNode(),mn=Cn instanceof ShadowRoot?Cn.host:e.closest(".persona-host");mn&&!Jt&&(Jt=Ci(mn,(Xt=(tt=r.launcher)==null?void 0:tt.zIndex)!=null?Xt:hn)),Kt=wi(e.ownerDocument)}else ot||(Jt==null||Jt(),Jt=null,Kt==null||Kt(),Kt=null)}}};ke();let Z=(Vl=e.ownerDocument.defaultView)!=null?Vl:window;if(Z.addEventListener("resize",ke),dt.push(()=>Z.removeEventListener("resize",ke)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{jn()});c.observe(Oe),dt.push(()=>c.disconnect())}rr=me.scrollTop;let Xe=me.scrollHeight,Ke=()=>{let c=me.scrollTop,m=me.scrollHeight,y=m<Xe;Xe=m;let{action:b,nextLastScrollTop:T}=Ta({following:nr.isFollowing(),currentScrollTop:c,lastScrollTop:rr,nearBottom:Ms(me,ns),userScrollThreshold:Us,isAutoScrolling:Tr||co||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rr=T,b==="resume"){Ur();return}b==="pause"&&ss()};me.addEventListener("scroll",Ke,{passive:!0}),dt.push(()=>me.removeEventListener("scroll",Ke));let Lt=c=>{let m=ka({following:nr.isFollowing(),deltaY:c.deltaY,nearBottom:Ms(me,ns),resumeWhenNearBottom:!0});m==="pause"?ss():m==="resume"&&Ur()};me.addEventListener("wheel",Lt,{passive:!0}),dt.push(()=>me.removeEventListener("wheel",Lt)),it.addEventListener("click",()=>{me.scrollTop=me.scrollHeight,rr=me.scrollTop,Ur(),qr(!0)}),dt.push(()=>it.remove()),dt.push(()=>{os()});let gt=()=>{P&&(Nn&&(P.removeEventListener("click",Nn),Nn=null),$()?(P.style.display="",Nn=()=>{Mt(!1,"user")},P.addEventListener("click",Nn)):P.style.display="none")};gt(),(()=>{let{clearChatButton:c}=ce;c&&c.addEventListener("click",()=>{_.clearMessages(),Fn.clear(),Ur(),ko(ce.composerOverlay);try{localStorage.removeItem(Zo),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zo}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Zo)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},k.syncFromMetadata(),Q==null||Q.clear(),re==null||re.update()})})(),It&&It.addEventListener("submit",ps),ie==null||ie.addEventListener("keydown",us),ie==null||ie.addEventListener("paste",ms);let Ht="persona-attachment-drop-active",Gt=0,yt=()=>{Gt=0,te.classList.remove(Ht)},ft=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&xt!==null},tn=c=>{!Qa(c.dataTransfer)||!ft()||(Gt++,Gt===1&&te.classList.add(Ht))},un=c=>{!Qa(c.dataTransfer)||!ft()||(Gt--,Gt<=0&&yt())},cn=c=>{!Qa(c.dataTransfer)||!ft()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Qt=c=>{var y;if(!Qa(c.dataTransfer)||!ft())return;c.preventDefault(),c.stopPropagation(),yt();let m=Array.from((y=c.dataTransfer.files)!=null?y:[]);m.length!==0&&xt.handleFiles(m)},sn=!0;te.addEventListener("dragenter",tn,sn),te.addEventListener("dragleave",un,sn),e.addEventListener("dragover",cn,sn),e.addEventListener("drop",Qt,sn);let oa=e.ownerDocument,ol=c=>{ft()&&c.preventDefault()},sl=c=>{ft()&&c.preventDefault()};oa.addEventListener("dragover",ol),oa.addEventListener("drop",sl),dt.push(()=>{It&&It.removeEventListener("submit",ps),ie==null||ie.removeEventListener("keydown",us),ie==null||ie.removeEventListener("paste",ms)}),dt.push(()=>{te.removeEventListener("dragenter",tn,sn),te.removeEventListener("dragleave",un,sn),e.removeEventListener("dragover",cn,sn),e.removeEventListener("drop",Qt,sn),oa.removeEventListener("dragover",ol),oa.removeEventListener("drop",sl),yt()}),dt.push(()=>{_.cancel()}),A?dt.push(()=>{A==null||A.destroy()}):q&&dt.push(()=>{q==null||q.remove()});let Zt={update(c){var en,yr,Rr,sa,aa,ia,xo,la,fs,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc,Ac,Sc,Ec,Tc,kc,Mc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,qc,zc,Vc,Jc,Kc,Gc,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,Cd,wd,Ad,Sd,Ed,Td,kd,Md,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,jd,Ud,qd,zd,Vd,Jd,Kd;let m=r.toolCall,y=r.messageActions,b=(en=r.layout)==null?void 0:en.messages,T=r.colorScheme,B=r.loadingIndicator,N=r.iterationDisplay,z=(yr=r.features)==null?void 0:yr.showReasoning,I=(Rr=r.features)==null?void 0:Rr.showToolCalls,ye=(sa=r.features)==null?void 0:sa.toolCallDisplay,le=(aa=r.features)==null?void 0:aa.reasoningDisplay;r={...r,...c},Zn(),So(e,r),za(e,r),Va(e,r),Bn(),r.colorScheme!==T&&jr();let Y=Ja.getForInstance(r.plugins);s.length=0,s.push(...Y),w=(xo=(ia=r.launcher)==null?void 0:ia.enabled)!=null?xo:!0,L=(fs=(la=r.launcher)==null?void 0:la.autoExpand)!=null?fs:!1,We=(ec=(Zl=r.features)==null?void 0:Zl.showReasoning)!=null?ec:!0,_e=(nc=(tc=r.features)==null?void 0:tc.showToolCalls)!=null?nc:!0,pe=(oc=(rc=r.features)==null?void 0:rc.scrollToBottom)!=null?oc:{},Dr(),Mr();let ue=fe;if(fe=(ac=(sc=r.features)==null?void 0:sc.showEventStreamToggle)!=null?ac:!1,fe&&!ue){if(Q||(ee=new js(je),Q=new _s(xe,ee),ee.open().then(()=>Q==null?void 0:Q.restore()).catch(()=>{}),_.setSSEEventCallback((X,bt)=>{var Bt;(Bt=r.onSSEEvent)==null||Bt.call(r,X,bt),Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(bt)})})),!ct&&Fe){let X=(lc=(ic=r.features)==null?void 0:ic.eventStream)==null?void 0:lc.classNames,bt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");ct=h("button",bt),ct.style.width="28px",ct.style.height="28px",ct.style.color=Sn.actionIconColor,ct.type="button",ct.setAttribute("aria-label","Event Stream"),ct.title="Event Stream";let Bt=ge("activity","18px","currentColor",1.5);Bt&&ct.appendChild(Bt);let st=ce.clearChatButtonWrapper,wt=ce.closeButtonWrapper,nn=st||wt;nn&&nn.parentNode===Fe?Fe.insertBefore(ct,nn):Fe.appendChild(ct),ct.addEventListener("click",()=>{Me?Yn():wr()})}}else!fe&&ue&&(Yn(),ct&&(ct.remove(),ct=null),Q==null||Q.clear(),ee==null||ee.destroy(),Q=null,ee=null);if(((cc=r.launcher)==null?void 0:cc.enabled)===!1&&A&&(A.destroy(),A=null),((dc=r.launcher)==null?void 0:dc.enabled)===!1&&q&&(q.remove(),q=null),((pc=r.launcher)==null?void 0:pc.enabled)!==!1&&!A&&!q){let X=s.find(bt=>bt.renderLauncher);if(X!=null&&X.renderLauncher){let bt=X.renderLauncher({config:r,defaultRenderer:()=>Bs(r,j).element,onToggle:j});bt&&(q=bt,e.appendChild(q))}q||(A=Bs(r,j),e.appendChild(A.element))}A&&A.update(r),Pe&&((uc=r.launcher)==null?void 0:uc.title)!==void 0&&(Pe.textContent=r.launcher.title),qe&&((mc=r.launcher)==null?void 0:mc.subtitle)!==void 0&&(qe.textContent=r.launcher.subtitle);let be=(gc=r.layout)==null?void 0:gc.header;if((be==null?void 0:be.layout)!==M&&Fe){let X=be?Ds(r,be,{showClose:$(),onClose:()=>Mt(!1,"user")}):eo({config:r,showClose:$(),onClose:()=>Mt(!1,"user")});Fe.replaceWith(X.header),Fe=X.header,oe=X.iconHolder,Pe=X.headerTitle,qe=X.headerSubtitle,P=X.closeButton,M=be==null?void 0:be.layout}else if(be&&(oe&&(oe.style.display=be.showIcon===!1?"none":""),Pe&&(Pe.style.display=be.showTitle===!1?"none":""),qe&&(qe.style.display=be.showSubtitle===!1?"none":""),P&&(P.style.display=be.showCloseButton===!1?"none":""),ce.clearChatButtonWrapper)){let X=be.showClearChat;if(X!==void 0){ce.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:bt}=ce;bt&&!bt.classList.contains("persona-absolute")&&(X?bt.classList.remove("persona-ml-auto"):bt.classList.add("persona-ml-auto"))}}let Ye=((fc=r.layout)==null?void 0:fc.showHeader)!==!1;Fe&&(Fe.style.display=Ye?"":"none");let ze=((hc=r.layout)==null?void 0:hc.showFooter)!==!1;Oe&&(Oe.style.display=ze?"":"none"),jn(),Mr(),w!==E?w?Mt(L,"auto"):(H=!0,Kr()):L!==W&&Mt(L,"auto"),W=L,E=w,ke(),gt();let Ee=JSON.stringify(c.toolCall)!==JSON.stringify(m),Ae=JSON.stringify(r.messageActions)!==JSON.stringify(y),$e=JSON.stringify((yc=r.layout)==null?void 0:yc.messages)!==JSON.stringify(b),S=((bc=r.loadingIndicator)==null?void 0:bc.render)!==(B==null?void 0:B.render)||((xc=r.loadingIndicator)==null?void 0:xc.renderIdle)!==(B==null?void 0:B.renderIdle)||((vc=r.loadingIndicator)==null?void 0:vc.showBubble)!==(B==null?void 0:B.showBubble),we=r.iterationDisplay!==N,Le=((wc=(Cc=r.features)==null?void 0:Cc.showReasoning)!=null?wc:!0)!==(z!=null?z:!0)||((Sc=(Ac=r.features)==null?void 0:Ac.showToolCalls)!=null?Sc:!0)!==(I!=null?I:!0)||JSON.stringify((Ec=r.features)==null?void 0:Ec.toolCallDisplay)!==JSON.stringify(ye)||JSON.stringify((Tc=r.features)==null?void 0:Tc.reasoningDisplay)!==JSON.stringify(le);(Ee||Ae||$e||S||we||Le)&&_&&(ts++,uo(Qe,_.getMessages(),Se));let he=(kc=r.launcher)!=null?kc:{},At=(Mc=he.headerIconHidden)!=null?Mc:!1,tt=(Pc=(Lc=r.layout)==null?void 0:Lc.header)==null?void 0:Pc.showIcon,Xt=At||tt===!1,dn=he.headerIconName,Tt=(Ic=he.headerIconSize)!=null?Ic:"48px";if(oe){let X=te.querySelector(".persona-border-b-persona-divider"),bt=X==null?void 0:X.querySelector(".persona-flex-col");if(Xt)oe.style.display="none",X&&bt&&!X.contains(bt)&&X.insertBefore(bt,X.firstChild);else{if(oe.style.display="",oe.style.height=Tt,oe.style.width=Tt,X&&bt&&(X.contains(oe)?oe.nextSibling!==bt&&(oe.remove(),X.insertBefore(oe,bt)):X.insertBefore(oe,bt)),dn){let st=parseFloat(Tt)||24,wt=ge(dn,st*.6,"#ffffff",2);wt?oe.replaceChildren(wt):oe.textContent=(Wc=he.agentIconText)!=null?Wc:"\u{1F4AC}"}else if(he.iconUrl){let st=oe.querySelector("img");if(st)st.src=he.iconUrl,st.style.height=Tt,st.style.width=Tt;else{let wt=document.createElement("img");wt.src=he.iconUrl,wt.alt="",wt.className="persona-rounded-xl persona-object-cover",wt.style.height=Tt,wt.style.width=Tt,oe.replaceChildren(wt)}}else{let st=oe.querySelector("svg"),wt=oe.querySelector("img");(st||wt)&&oe.replaceChildren(),oe.textContent=(Rc=he.agentIconText)!=null?Rc:"\u{1F4AC}"}let Bt=oe.querySelector("img");Bt&&(Bt.style.height=Tt,Bt.style.width=Tt)}}let vn=(Bc=(Hc=r.layout)==null?void 0:Hc.header)==null?void 0:Bc.showTitle,pn=(Nc=(Dc=r.layout)==null?void 0:Dc.header)==null?void 0:Nc.showSubtitle;if(Pe&&(Pe.style.display=vn===!1?"none":""),qe&&(qe.style.display=pn===!1?"none":""),P){((Oc=(Fc=r.layout)==null?void 0:Fc.header)==null?void 0:Oc.showCloseButton)===!1?P.style.display="none":P.style.display="";let bt=($c=he.closeButtonSize)!=null?$c:"32px",Bt=(_c=he.closeButtonPlacement)!=null?_c:"inline";P.style.height=bt,P.style.width=bt;let{closeButtonWrapper:st}=ce,wt=Bt==="top-right",nn=st==null?void 0:st.classList.contains("persona-absolute");if(st&&wt!==nn)if(st.remove(),wt)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",te.style.position="relative",te.appendChild(st);else{let at=(Uc=(jc=he.clearChat)==null?void 0:jc.placement)!=null?Uc:"inline",rn=(zc=(qc=he.clearChat)==null?void 0:qc.enabled)!=null?zc:!0;st.className=rn&&at==="inline"?"":"persona-ml-auto";let Pn=te.querySelector(".persona-border-b-persona-divider");Pn&&Pn.appendChild(st)}if(P.style.color=he.closeButtonColor||Sn.actionIconColor,he.closeButtonBackgroundColor?(P.style.backgroundColor=he.closeButtonBackgroundColor,P.classList.remove("hover:persona-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let at=he.closeButtonBorderWidth||"0px",rn=he.closeButtonBorderColor||"transparent";P.style.border=`${at} solid ${rn}`,P.classList.remove("persona-border-none")}else P.style.border="",P.classList.add("persona-border-none");he.closeButtonBorderRadius?(P.style.borderRadius=he.closeButtonBorderRadius,P.classList.remove("persona-rounded-full")):(P.style.borderRadius="",P.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(P.style.paddingLeft=he.closeButtonPaddingX,P.style.paddingRight=he.closeButtonPaddingX):(P.style.paddingLeft="",P.style.paddingRight=""),he.closeButtonPaddingY?(P.style.paddingTop=he.closeButtonPaddingY,P.style.paddingBottom=he.closeButtonPaddingY):(P.style.paddingTop="",P.style.paddingBottom="");let gn=(Vc=he.closeButtonIconName)!=null?Vc:"x",ir=(Jc=he.closeButtonIconText)!=null?Jc:"\xD7";P.innerHTML="";let An=ge(gn,"28px","currentColor",1);An?P.appendChild(An):P.textContent=ir;let Yt=(Kc=he.closeButtonTooltipText)!=null?Kc:"Close chat",_n=(Gc=he.closeButtonShowTooltip)!=null?Gc:!0;if(P.setAttribute("aria-label",Yt),st&&(st._cleanupTooltip&&(st._cleanupTooltip(),delete st._cleanupTooltip),_n&&Yt)){let at=null,rn=()=>{if(at||!P)return;let vo=P.ownerDocument,hs=vo.body;if(!hs)return;at=br(vo,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let ys=br(vo,"div");ys.className="persona-clear-chat-tooltip-arrow",at.appendChild(ys);let Co=P.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(Xr),at.style.left=`${Co.left+Co.width/2}px`,at.style.top=`${Co.top-8}px`,at.style.transform="translate(-50%, -100%)",hs.appendChild(at)},Pn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};st.addEventListener("mouseenter",rn),st.addEventListener("mouseleave",Pn),P.addEventListener("focus",rn),P.addEventListener("blur",Pn),st._cleanupTooltip=()=>{Pn(),st&&(st.removeEventListener("mouseenter",rn),st.removeEventListener("mouseleave",Pn)),P&&(P.removeEventListener("focus",rn),P.removeEventListener("blur",Pn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:ot}=ce;if(Ge){let X=(Qc=he.clearChat)!=null?Qc:{},bt=(Xc=X.enabled)!=null?Xc:!0,Bt=(Zc=(Yc=r.layout)==null?void 0:Yc.header)==null?void 0:Zc.showClearChat,st=Bt!==void 0?Bt:bt,wt=(ed=X.placement)!=null?ed:"inline";if(ot){ot.style.display=st?"":"none";let{closeButtonWrapper:nn}=ce;!U()&&nn&&!nn.classList.contains("persona-absolute")&&(st?nn.classList.remove("persona-ml-auto"):nn.classList.add("persona-ml-auto"));let gn=wt==="top-right",ir=ot.classList.contains("persona-absolute");if(!U()&&gn!==ir&&st){if(ot.remove(),gn)ot.className="persona-absolute persona-top-4 persona-z-50",ot.style.right="48px",te.style.position="relative",te.appendChild(ot);else{ot.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ot.style.right="";let Yt=te.querySelector(".persona-border-b-persona-divider"),_n=ce.closeButtonWrapper;Yt&&_n&&_n.parentElement===Yt?Yt.insertBefore(ot,_n):Yt&&Yt.appendChild(ot)}let An=ce.closeButtonWrapper;An&&!An.classList.contains("persona-absolute")&&(gn?An.classList.add("persona-ml-auto"):An.classList.remove("persona-ml-auto"))}}if(st){if(!U()){let at=(td=X.size)!=null?td:"32px";Ge.style.height=at,Ge.style.width=at}let nn=(nd=X.iconName)!=null?nd:"refresh-cw",gn=(rd=X.iconColor)!=null?rd:"";Ge.style.color=gn||Sn.actionIconColor,Ge.innerHTML="";let ir=U()?"14px":"20px",An=ge(nn,ir,"currentColor",2);if(An&&Ge.appendChild(An),X.backgroundColor?(Ge.style.backgroundColor=X.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let at=X.borderWidth||"0px",rn=X.borderColor||"transparent";Ge.style.border=`${at} solid ${rn}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");X.borderRadius?(Ge.style.borderRadius=X.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),X.paddingX?(Ge.style.paddingLeft=X.paddingX,Ge.style.paddingRight=X.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),X.paddingY?(Ge.style.paddingTop=X.paddingY,Ge.style.paddingBottom=X.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Yt=(od=X.tooltipText)!=null?od:"Clear chat",_n=(sd=X.showTooltip)!=null?sd:!0;if(Ge.setAttribute("aria-label",Yt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),_n&&Yt)){let at=null,rn=()=>{if(at||!Ge)return;let vo=Ge.ownerDocument,hs=vo.body;if(!hs)return;at=br(vo,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let ys=br(vo,"div");ys.className="persona-clear-chat-tooltip-arrow",at.appendChild(ys);let Co=Ge.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(Xr),at.style.left=`${Co.left+Co.width/2}px`,at.style.top=`${Co.top-8}px`,at.style.transform="translate(-50%, -100%)",hs.appendChild(at)},Pn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};ot.addEventListener("mouseenter",rn),ot.addEventListener("mouseleave",Pn),Ge.addEventListener("focus",rn),Ge.addEventListener("blur",Pn),ot._cleanupTooltip=()=>{Pn(),ot&&(ot.removeEventListener("mouseenter",rn),ot.removeEventListener("mouseleave",Pn)),Ge&&(Ge.removeEventListener("focus",rn),Ge.removeEventListener("blur",Pn))}}}}let Cn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ka],mn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Yo.message,Yo.messageAndClick];k=Ga({parsers:Cn,handlers:mn,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Se=mu(r,k,ne),_.updateConfig(r),uo(Qe,_.getMessages(),Se),er.render(r.suggestionChips,_,ie,void 0,r.suggestionChipsConfig),cs(),Io(_.isStreaming());let fo=((ad=r.voiceRecognition)==null?void 0:ad.enabled)===!0,ho=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),yo=((ld=(id=r.voiceRecognition)==null?void 0:id.provider)==null?void 0:ld.type)==="runtype";if(fo&&(ho||yo))if(!R||!se){let X=ta(r.voiceRecognition,r.sendButton);X&&(R=X.micButton,se=X.micButtonWrapper,Ot.insertBefore(se,an),R.addEventListener("click",Ir),R.disabled=_.isStreaming())}else{let X=(cd=r.voiceRecognition)!=null?cd:{},bt=(dd=r.sendButton)!=null?dd:{},Bt=(pd=X.iconName)!=null?pd:"mic",st=(ud=bt.size)!=null?ud:"40px",wt=(md=X.iconSize)!=null?md:st,nn=parseFloat(wt)||24;R.style.width=wt,R.style.height=wt,R.style.minWidth=wt,R.style.minHeight=wt;let gn=(fd=(gd=X.iconColor)!=null?gd:bt.textColor)!=null?fd:"currentColor";R.innerHTML="";let ir=ge(Bt,nn,gn,2);ir?R.appendChild(ir):R.textContent="\u{1F3A4}";let An=(hd=X.backgroundColor)!=null?hd:bt.backgroundColor;An?R.style.backgroundColor=An:R.style.backgroundColor="",gn?R.style.color=gn:R.style.color="var(--persona-text, #111827)",X.borderWidth?(R.style.borderWidth=X.borderWidth,R.style.borderStyle="solid"):(R.style.borderWidth="",R.style.borderStyle=""),X.borderColor?R.style.borderColor=X.borderColor:R.style.borderColor="",X.paddingX?(R.style.paddingLeft=X.paddingX,R.style.paddingRight=X.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),X.paddingY?(R.style.paddingTop=X.paddingY,R.style.paddingBottom=X.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let Yt=se==null?void 0:se.querySelector(".persona-send-button-tooltip"),_n=(yd=X.tooltipText)!=null?yd:"Start voice recognition";if(((bd=X.showTooltip)!=null?bd:!1)&&_n)if(Yt)Yt.textContent=_n,Yt.style.display="";else{let rn=document.createElement("div");rn.className="persona-send-button-tooltip",rn.textContent=_n,se==null||se.insertBefore(rn,R)}else Yt&&(Yt.style.display="none");se.style.display="",R.disabled=_.isStreaming()}else R&&se&&(se.style.display="none",((vd=(xd=r.voiceRecognition)==null?void 0:xd.provider)==null?void 0:vd.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():On&&sr());if(((Cd=r.attachments)==null?void 0:Cd.enabled)===!0)if(!pt||!Ce){let X=(wd=r.attachments)!=null?wd:{},Bt=(Sd=((Ad=r.sendButton)!=null?Ad:{}).size)!=null?Sd:"40px";Nt||(Nt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Nt.style.display="none",It.insertBefore(Nt,ie)),Je||(Je=document.createElement("input"),Je.type="file",Je.accept=((Ed=X.allowedTypes)!=null?Ed:Hr).join(","),Je.multiple=((Td=X.maxFiles)!=null?Td:4)>1,Je.style.display="none",Je.setAttribute("aria-label","Attach files"),It.insertBefore(Je,ie)),pt=h("div","persona-send-button-wrapper"),Ce=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ce.type="button",Ce.setAttribute("aria-label",(kd=X.buttonTooltipText)!=null?kd:"Attach file");let st=(Md=X.buttonIconName)!=null?Md:"paperclip",wt=Bt,nn=parseFloat(wt)||40,gn=Math.round(nn*.6);Ce.style.width=wt,Ce.style.height=wt,Ce.style.minWidth=wt,Ce.style.minHeight=wt,Ce.style.fontSize="18px",Ce.style.lineHeight="1",Ce.style.backgroundColor="transparent",Ce.style.color="var(--persona-primary, #111827)",Ce.style.border="none",Ce.style.borderRadius="6px",Ce.style.transition="background-color 0.15s ease",Ce.addEventListener("mouseenter",()=>{Ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ce.addEventListener("mouseleave",()=>{Ce.style.backgroundColor="transparent"});let ir=ge(st,gn,"currentColor",1.5);ir?Ce.appendChild(ir):Ce.textContent="\u{1F4CE}",Ce.addEventListener("click",_n=>{_n.preventDefault(),Je==null||Je.click()}),pt.appendChild(Ce);let An=(Ld=X.buttonTooltipText)!=null?Ld:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=An,pt.appendChild(Yt),vt.append(pt),!xt&&Je&&Nt&&(xt=Uo.fromConfig(X),xt.setPreviewsContainer(Nt),Je.addEventListener("change",async()=>{xt&&(Je!=null&&Je.files)&&(await xt.handleFileSelect(Je.files),Je.value="")})),te.querySelector(".persona-attachment-drop-overlay")||te.appendChild(gu(X.dropOverlay))}else{pt.style.display="";let X=(Pd=r.attachments)!=null?Pd:{};Je&&(Je.accept=((Id=X.allowedTypes)!=null?Id:Hr).join(","),Je.multiple=((Wd=X.maxFiles)!=null?Wd:4)>1),xt&&xt.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else pt&&(pt.style.display="none"),xt&&xt.clearAttachments(),(Rd=te.querySelector(".persona-attachment-drop-overlay"))==null||Rd.remove();let jt=(Hd=r.sendButton)!=null?Hd:{},bo=(Bd=jt.useIcon)!=null?Bd:!1,Qr=(Dd=jt.iconText)!=null?Dd:"\u2191",ut=jt.iconName,kn=(Nd=jt.tooltipText)!=null?Nd:"Send message",Wr=(Fd=jt.showTooltip)!=null?Fd:!1,wn=(Od=jt.size)!=null?Od:"40px",Mn=jt.backgroundColor,Wt=jt.textColor;if(bo){if(Ne.style.width=wn,Ne.style.height=wn,Ne.style.minWidth=wn,Ne.style.minHeight=wn,Ne.style.fontSize="18px",Ne.style.lineHeight="1",Ne.innerHTML="",Wt?Ne.style.color=Wt:Ne.style.color="var(--persona-button-primary-fg, #ffffff)",ut){let X=parseFloat(wn)||24,bt=(Wt==null?void 0:Wt.trim())||"currentColor",Bt=ge(ut,X,bt,2);Bt?Ne.appendChild(Bt):Ne.textContent=Qr}else Ne.textContent=Qr;Ne.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Mn?(Ne.style.backgroundColor=Mn,Ne.classList.remove("persona-bg-persona-primary")):(Ne.style.backgroundColor="",Ne.classList.add("persona-bg-persona-primary"))}else Ne.textContent=(_d=($d=r.copy)==null?void 0:$d.sendButtonLabel)!=null?_d:"Send",Ne.style.width="",Ne.style.height="",Ne.style.minWidth="",Ne.style.minHeight="",Ne.style.fontSize="",Ne.style.lineHeight="",Ne.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",Mn?(Ne.style.backgroundColor=Mn,Ne.classList.remove("persona-bg-persona-accent")):Ne.classList.add("persona-bg-persona-accent"),Wt?Ne.style.color=Wt:Ne.classList.add("persona-text-white");jt.borderWidth?(Ne.style.borderWidth=jt.borderWidth,Ne.style.borderStyle="solid"):(Ne.style.borderWidth="",Ne.style.borderStyle=""),jt.borderColor?Ne.style.borderColor=jt.borderColor:Ne.style.borderColor="",jt.paddingX?(Ne.style.paddingLeft=jt.paddingX,Ne.style.paddingRight=jt.paddingX):(Ne.style.paddingLeft="",Ne.style.paddingRight=""),jt.paddingY?(Ne.style.paddingTop=jt.paddingY,Ne.style.paddingBottom=jt.paddingY):(Ne.style.paddingTop="",Ne.style.paddingBottom="");let $t=an==null?void 0:an.querySelector(".persona-send-button-tooltip");if(Wr&&kn)if($t)$t.textContent=kn,$t.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=kn,an==null||an.insertBefore(X,Ne)}else $t&&($t.style.display="none");let Rt=(Vd=(jd=r.layout)==null?void 0:jd.contentMaxWidth)!=null?Vd:U()?(zd=(qd=(Ud=r.launcher)==null?void 0:Ud.composerBar)==null?void 0:qd.contentMaxWidth)!=null?zd:"720px":void 0;Rt?(Qe.style.maxWidth=Rt,Qe.style.marginLeft="auto",Qe.style.marginRight="auto",Qe.style.width="100%",It&&(It.style.maxWidth=Rt,It.style.marginLeft="auto",It.style.marginRight="auto"),Ft&&(Ft.style.maxWidth=Rt,Ft.style.marginLeft="auto",Ft.style.marginRight="auto")):(Qe.style.maxWidth="",Qe.style.marginLeft="",Qe.style.marginRight="",Qe.style.width="",It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""),Ft&&(Ft.style.maxWidth="",Ft.style.marginLeft="",Ft.style.marginRight=""));let Ut=(Jd=r.statusIndicator)!=null?Jd:{},Ln=(Kd=Ut.visible)!=null?Kd:!0;if(qt.style.display=Ln?"":"none",_){let X=_.getStatus();He(qt,(Bt=>{var st,wt,nn,gn;return Bt==="idle"?(st=Ut.idleText)!=null?st:fn.idle:Bt==="connecting"?(wt=Ut.connectingText)!=null?wt:fn.connecting:Bt==="connected"?(nn=Ut.connectedText)!=null?nn:fn.connected:Bt==="error"?(gn=Ut.errorText)!=null?gn:fn.error:fn[Bt]})(X),Ut,X)}qt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let $n=Ut.align==="left"?"persona-text-left":Ut.align==="center"?"persona-text-center":"persona-text-right";qt.classList.add($n)},open(){$()&&Mt(!0,"api")},close(){$()&&Mt(!1,"api")},toggle(){$()&&Mt(!H,"api")},clearChat(){yn=!1,_.clearMessages(),Fn.clear(),Ur();try{localStorage.removeItem(Zo),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zo}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Zo)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.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)}d={},k.syncFromMetadata(),Q==null||Q.clear(),re==null||re.update()},setMessage(c){return!ie||_.isStreaming()?!1:(!H&&$()&&Mt(!0,"system"),ie.value=c,ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let m=(c==null?void 0:c.trim())||ie.value.trim();return m?(!H&&$()&&Mt(!0,"system"),ie.value="",ie.style.height="auto",_.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return _.isStreaming()?!1:((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(_.isVoiceActive()||(!H&&$()&&Mt(!0,"system"),lt.manuallyDeactivated=!1,Tn(),_.toggleVoice().then(()=>{lt.active=_.isVoiceActive(),Jn("user"),_.isVoiceActive()&&Gr()})),!0):On?!0:gs()?(!H&&$()&&Mt(!0,"system"),lt.manuallyDeactivated=!1,Tn(),mo("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{lt.active=!1,lt.manuallyDeactivated=!0,Tn(),Jn("user"),ar()}),!0):!1:On?(lt.manuallyDeactivated=!0,Tn(),sr("user"),!0):!1},injectMessage(c){return!H&&$()&&Mt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!H&&$()&&Mt(!0,"system");let m=_.injectAssistantMessage(c);return F&&(F=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),m},injectUserMessage(c){return!H&&$()&&Mt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!H&&$()&&Mt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!H&&$()&&Mt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!H&&$()&&Mt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!H&&$()&&Mt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,m){return _.connectStream(c,m)},__pushEventStreamEvent(c){Q&&Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!fe||!Q||wr()},hideEventStream(){Me&&Yn()},isEventStreamVisible(){return Me},showArtifacts(){Xn(r)&&(yn=!1,Bn(),mt==null||mt.setMobileOpen(!0))},hideArtifacts(){Xn(r)&&(yn=!0,Bn())},upsertArtifact(c){return Xn(r)?(yn=!1,_.upsertArtifact(c)):null},selectArtifact(c){Xn(r)&&_.selectArtifact(c)},clearArtifacts(){Xn(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return w&&!H&&!U()||!ie?!1:(ie.focus(),!0)},async resolveApproval(c,m){let b=_.getMessages().find(T=>{var B;return T.variant==="approval"&&((B=T.approval)==null?void 0:B.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);return _.resolveApproval(b.approval,m)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return o.on(c,m)},off(c,m){o.off(c,m)},isOpen(){return $()&&H},isVoiceActive(){return lt.active},getState(){return{open:$()&&H,launcherEnabled:w,voiceActive:lt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!H&&$()&&Mt(!0,"system");let m=Qe.querySelector(".persona-feedback-container");m&&m.remove();let y=qi({onSubmit:async(b,T)=>{var B;_.isClientTokenMode()&&await _.submitCSATFeedback(b,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});Qe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!H&&$()&&Mt(!0,"system");let m=Qe.querySelector(".persona-feedback-container");m&&m.remove();let y=zi({onSubmit:async(b,T)=>{var B;_.isClientTokenMode()&&await _.submitNPSFeedback(b,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});Qe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return _.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return _.submitNPSFeedback(c,m)},destroy(){hr!=null&&(clearInterval(hr),hr=null),dt.forEach(c=>c()),G.remove(),ve==null||ve.remove(),A==null||A.destroy(),q==null||q.remove(),Nn&&P.removeEventListener("click",Nn)}};if((((Jl=t==null?void 0:t.debugTools)!=null?Jl:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:y=>y?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,dt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=z=>{let I=z.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",m),dt.push(()=>{window.removeEventListener("persona:focusInput",m)}),fe){let z=ye=>{let le=ye.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&Zt.showEventStream()},I=ye=>{let le=ye.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",I),dt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",I)})}let y=z=>{let I=z.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.showArtifacts()},b=z=>{let I=z.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.hideArtifacts()},T=z=>{let I=z.detail;I!=null&&I.instanceId&&I.instanceId!==c||I!=null&&I.artifact&&Zt.upsertArtifact(I.artifact)},B=z=>{let I=z.detail;I!=null&&I.instanceId&&I.instanceId!==c||typeof(I==null?void 0:I.id)=="string"&&Zt.selectArtifact(I.id)},N=z=>{let I=z.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",N),dt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",N)})}let Kn=Cy(r.persistState);if(Kn&&$()){let c=wy(Kn.storage),m=`${Kn.keyPrefix}widget-open`,y=`${Kn.keyPrefix}widget-voice`,b=`${Kn.keyPrefix}widget-voice-mode`;if(c){let T=((Kl=Kn.persist)==null?void 0:Kl.openState)&&c.getItem(m)==="true",B=((Gl=Kn.persist)==null?void 0:Gl.voiceState)&&c.getItem(y)==="true",N=((Ql=Kn.persist)==null?void 0:Ql.voiceState)&&c.getItem(b)==="true";if(T&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var z;if(B||N)Zt.startVoiceRecognition();else if((z=Kn.persist)!=null&&z.focusInput){let I=e.querySelector("textarea");I&&I.focus()}},100)},0),(Xl=Kn.persist)!=null&&Xl.openState&&(o.on("widget:opened",()=>{c.setItem(m,"true")}),o.on("widget:closed",()=>{c.setItem(m,"false")})),(Yl=Kn.persist)!=null&&Yl.voiceState&&(o.on("voice:state",z=>{c.setItem(y,z.active?"true":"false")}),o.on("user:message",z=>{c.setItem(b,z.viaVoice?"true":"false")})),Kn.clearOnChatClear){let z=()=>{c.removeItem(m),c.removeItem(y),c.removeItem(b)},I=()=>z();window.addEventListener("persona:clear-chat",I),dt.push(()=>{window.removeEventListener("persona:clear-chat",I)})}}}return u&&$()&&setTimeout(()=>{Zt.open()},0),Lr(),Zt};var Ay=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},fu=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Xi=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=""},hu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Xi(e)},Ki=e=>{e.style.transition=""},Gi=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=""},Qi=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Xa=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},Sy=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Ey=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},yu=(e,n,t,r,s,o,a)=>{var v,x,k,w,L,D;let i=lr(o),d=i.reveal==="push";Sy(e,n,t,r,d),Ey(e,n,t,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,p=(w=(k=o==null?void 0:o.launcher)==null?void 0:k.mobileBreakpoint)!=null?w:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Gi(n),Ki(r),hu(r),Qi(t),Xa(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((D=(L=o==null?void 0:o.launcher)==null?void 0:L.zIndex)!=null?D:hn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),hu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Gi(n),Ki(r),Qi(t),Xa(s,r);let W=i.animate?"transform 180ms ease":"none",E=i.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":E;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=W,r.style.transform=M,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ki(r),Xi(r),Xa(s,r);let W=Ay(i.width,e.clientWidth),E=Math.max(0,e.clientWidth),M=i.animate?"transform 180ms ease":"none",O=i.side==="right"?a?`translateX(-${W}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${W}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${E+W}px`,n.style.transition=M,n.style.transform=O,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${E}px`,t.style.maxWidth=`${E}px`,t.style.minWidth=`${E}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Gi(n),Xi(r),Qi(t),Xa(s,r);let W=i.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=a?i.width:"0px",M=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",O=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${E}`,r.style.width=E,r.style.maxWidth=E,r.style.minWidth=E,r.style.minHeight="0",r.style.position="relative",r.style.overflow=W||O?"hidden":"visible",r.style.transition=M,W&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Ty=(e,n)=>{let t=e.ownerDocument.createElement("div");return fu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){fu(t,r)},destroy(){t.remove()}}},ky=(e,n)=>{var L,D,W,E;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(D=(L=n==null?void 0:n.launcher)==null?void 0:L.enabled)==null||D?(E=(W=n==null?void 0:n.launcher)==null?void 0:W.autoExpand)!=null?E:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),lr(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{yu(a,i,d,l,u,n,p)}),f.observe(a))},x=()=>{yu(a,i,d,l,u,n,p),v()},k=a.ownerDocument.defaultView,w=()=>{x()};return k==null||k.addEventListener("resize",w),lr(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(M){let O=M.launcherEnabled?M.open:!0;p!==O&&(p=O,x())},updateConfig(M){var O,U;n=M,((U=(O=n==null?void 0:n.launcher)==null?void 0:O.enabled)!=null?U:!0)===!1&&(p=!0),x()},destroy(){k==null||k.removeEventListener("resize",w),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},Ya=(e,n)=>on(n)?ky(e,n):Ty(e,n);var Yi={},My=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},Ly=()=>{try{if(typeof Yi!="undefined"&&Yi.url)return new URL("../widget.css",Yi.url).href}catch{}return null},bu=(e,n)=>{let t=Ly(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},xu=e=>{var k;let n=My(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=Ya(n,s),a,i=[],d=(w,L)=>{var M,O;let W=!((O=(M=L==null?void 0:L.launcher)==null?void 0:M.enabled)!=null?O:!0)||on(L),E=r.createElement("div");if(E.setAttribute("data-persona-root","true"),W&&(E.style.height="100%",E.style.display="flex",E.style.flexDirection="column",E.style.flex="1",E.style.minHeight="0"),t){let U=w.attachShadow({mode:"open"});U.appendChild(E),bu(U,r)}else w.appendChild(E),bu(w,r);return n.id&&E.setAttribute("data-persona-instance",n.id),E},l=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let w=d(o.host,s);a=Ji(w,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};p(),(k=e.onReady)==null||k.call(e);let g=w=>{f(),o.destroy(),o=Ya(n,w),s=w,p()},v={update(w){var O,U,$,H,F,K;let L={...s,...w,launcher:{...(O=s==null?void 0:s.launcher)!=null?O:{},...(U=w==null?void 0:w.launcher)!=null?U:{},dock:{...(H=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?H:{},...(K=(F=w==null?void 0:w.launcher)==null?void 0:F.dock)!=null?K:{}}}},D=on(s),W=on(L),E=Zr(s),M=Zr(L);if(D!==W||E!==M){g(L);return}s=L,o.updateConfig(s),a.update(w),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,L,D){if(L==="host")return o.host;if(L in w)return Reflect.get(w,L,D);let W=a[L];return typeof W=="function"?W.bind(a):W}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Su=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Py=new Set(["button","a","input","select","textarea","details","summary"]),Iy=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Zi=/\b(product|card|item|listing|result)\b/i,tl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Wy=3e3,Ry=100;function Eu(e){let n=typeof e.className=="string"?e.className:"";if(Zi.test(n)||e.id&&Zi.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Zi.test(r.value))return!0}return!1}function Tu(e){var n;return tl.test(((n=e.textContent)!=null?n:"").trim())}function ku(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Hy(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function vu(e){let n=e.match(tl);return n?n[0]:null}function Cu(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function By(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var Dy="commerce-card",Ny="result-card";function wu(e){return!Eu(e)||!Tu(e)||!ku(e)&&!Hy(e)?0:5200}function Au(e){var r;return!Eu(e)||Tu(e)||!ku(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Mu=[{id:Dy,scoreElement(e){return wu(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||tl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(wu(e)===0)return null;let{title:t,href:r}=Cu(e),s=(u=(l=vu(((d=e.textContent)!=null?d:"").trim()))!=null?l:vu(n.text))!=null?u:"",o=By(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
101
|
+
`)}},{id:Ny,scoreElement(e){return Au(e)},formatSummary(e,n){if(Au(e)===0)return null;let{title:t,href:r}=Cu(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
|
|
102
|
+
`)}}];function Fy(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Oy(e){var u,p,f,g,v,x,k,w,L,D,W,E,M;let n=(u=e.options)!=null?u:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(v=(g=n.excludeSelector)!=null?g:e.excludeSelector)!=null?v:".persona-host",s=(k=(x=n.maxTextLength)!=null?x:e.maxTextLength)!=null?k:200,o=(L=(w=n.visibleOnly)!=null?w:e.visibleOnly)!=null?L:!0,a=(D=n.root)!=null?D:e.root,i=(W=n.mode)!=null?W:"structured",d=(E=n.maxCandidates)!=null?E:Math.max(500,t*10),l=(M=e.rules)!=null?M:Mu;return i==="simple"&&e.rules&&e.rules.length>0?(Fy(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function el(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var $y=["data-testid","data-product","data-action","data-id","data-name","data-type"];function _y(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||Py.has(n)||t&&Iy.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Lu(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function jy(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(n[u.name]=u.value)}return n}function Pu(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${el(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of $y){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${el(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>el(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function Uy(e){return e==="static"?Ry:Wy}function Iu(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:Pu(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:_y(e),attributes:jy(e)}}function qy(e,n,t,r){let s=Uy(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function zy(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function Vy(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Su.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Lu(l)){i=a.nextNode();continue}let p=Iu(l,e.maxTextLength),f=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(k=>k==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:v,formattingRule:x}=qy(l,p,e.rules,t);s.push({el:l,domIndex:o,enriched:p,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;zy(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let g=l.formattingRule.formatSummary(l.el,l.enriched,t);g&&(u=g)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function Jy(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(Su.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Lu(d)){o=s.nextNode();continue}let u=Iu(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(g=>g==="role");if(!p&&!f){o=s.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Ky(e={}){var r;let n=Oy(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?Jy(n,t):Vy(n,t):[]}var Za=100;function Gy(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
|
|
103
103
|
${a.map(i=>`- ${i.split(`
|
|
104
104
|
`).join(`
|
|
105
105
|
`)}`).join(`
|
|
@@ -113,7 +113,7 @@ ${a.join(`
|
|
|
113
113
|
${a.join(`
|
|
114
114
|
`)}`)}return r.join(`
|
|
115
115
|
|
|
116
|
-
`)}var
|
|
116
|
+
`)}var Wu={name:"@runtypelabs/persona",version:"3.20.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",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 es=Wu.version;function Br(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function Xy(e){if(e)return{getHeaders:Br(e.getHeaders),onFeedback:Br(e.onFeedback),onCopy:Br(e.onCopy),requestMiddleware:Br(e.requestMiddleware),actionHandlers:Br(e.actionHandlers),actionParsers:Br(e.actionParsers),postprocessMessage:Br(e.postprocessMessage),contextProviders:Br(e.contextProviders),streamParser:Br(e.streamParser)}}var Ru=`({ text, message }: any) => {
|
|
117
117
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
118
118
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
119
119
|
let cleanJson = jsonSource
|
|
@@ -126,7 +126,7 @@ ${a.join(`
|
|
|
126
126
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
127
127
|
} catch (e) { return null; }
|
|
128
128
|
return null;
|
|
129
|
-
}`,
|
|
129
|
+
}`,Hu=`function(ctx) {
|
|
130
130
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
131
131
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
132
132
|
var cleanJson = jsonSource
|
|
@@ -139,7 +139,7 @@ ${a.join(`
|
|
|
139
139
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
140
140
|
} catch (e) { return null; }
|
|
141
141
|
return null;
|
|
142
|
-
}`,
|
|
142
|
+
}`,Bu=`(action: any, context: any) => {
|
|
143
143
|
if (action.type !== 'nav_then_click') return;
|
|
144
144
|
const payload = action.payload || action.raw || {};
|
|
145
145
|
const url = payload?.page;
|
|
@@ -156,7 +156,7 @@ ${a.join(`
|
|
|
156
156
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
157
157
|
window.location.href = targetUrl;
|
|
158
158
|
return { handled: true, displayText: text };
|
|
159
|
-
}`,
|
|
159
|
+
}`,Du=`function(action, context) {
|
|
160
160
|
if (action.type !== 'nav_then_click') return;
|
|
161
161
|
var payload = action.payload || action.raw || {};
|
|
162
162
|
var url = payload.page;
|
|
@@ -173,26 +173,26 @@ ${a.join(`
|
|
|
173
173
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
174
174
|
window.location.href = targetUrl;
|
|
175
175
|
return { handled: true, displayText: text };
|
|
176
|
-
}`,
|
|
176
|
+
}`,Yy=`(parsed: any) => {
|
|
177
177
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
178
178
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
179
179
|
if (parsed.action === 'message') return parsed.text || '';
|
|
180
180
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
181
181
|
return parsed.text || null;
|
|
182
|
-
}`,
|
|
182
|
+
}`,Zy=`function(parsed) {
|
|
183
183
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
184
184
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
185
185
|
if (parsed.action === 'message') return parsed.text || '';
|
|
186
186
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
187
187
|
return parsed.text || null;
|
|
188
|
-
}`;function
|
|
189
|
-
`)}function
|
|
190
|
-
`)}function rb(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(r,"theme",e.theme," "),e.launcher&&ao(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...ti(e," ")),r.push(...ni(e," ",t)),r.push(...ri(e," ")),r.push(...oi(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Xy}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Wu}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Wu}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Hu}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Hu}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
191
|
-
`)}function
|
|
192
|
-
`)}function
|
|
188
|
+
}`;function eb(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function ei(e){var n,t;return(t=(n=e.parserType)!=null?n:eb(e.streamParser))!=null?t:"plain"}function ti(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function ni(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function ri(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function oi(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?t.push(`${n} ${d}: "${l}",`):typeof l=="boolean"&&t.push(`${n} ${d}: ${l},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function nl(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function Nu(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),Nu(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function ao(e,n,t,r){t&&(e.push(`${r}${n}: {`),Nu(e,t,`${r} `),e.push(`${r}},`))}function tb(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:Xy(t.hooks)}:void 0;return n==="esm"?nb(r,s):n==="script-installer"?sb(r,s):n==="script-advanced"?ib(r,s):n==="react-component"?rb(r,s):n==="react-advanced"?ob(r,s):ab(r,s)}function nb(e,n){let t=n==null?void 0:n.hooks,r=ei(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(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(...ti(e," ")),o.push(...ni(e," ",t)),o.push(...ri(e," ")),o.push(...oi(e," ")),o.push(...nl(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(`
|
|
189
|
+
`)}function rb(e,n){let t=n==null?void 0:n.hooks,r=ei(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(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(...ti(e," ")),o.push(...ni(e," ",t)),o.push(...ri(e," ")),o.push(...oi(e," ")),o.push(...nl(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(`
|
|
190
|
+
`)}function ob(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(r,"theme",e.theme," "),e.launcher&&ao(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...ti(e," ")),r.push(...ni(e," ",t)),r.push(...ri(e," ")),r.push(...oi(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Yy}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Ru}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Ru}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Bu}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Bu}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
191
|
+
`)}function Fu(e){var s;let n=ei(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function sb(e,n){let t=Fu(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,s=JSON.stringify(r,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${es}/dist/install.global.js" data-config='${s}'></script>`}function ab(e,n){let t=n==null?void 0:n.hooks,r=ei(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${es}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${es}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(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(...ti(e," ")),o.push(...ni(e," ",t)),o.push(...ri(e," ")),o.push(...oi(e," ")),o.push(...nl(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(`
|
|
192
|
+
`)}function ib(e,n){let t=n==null?void 0:n.hooks,r=Fu(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
193
193
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
194
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${es}/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(${
|
|
195
|
-
`)}var
|
|
194
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${es}/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(${Zy});`),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(` ${Hu}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Hu}`),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(` ${Du}`),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(` ${Du}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
|
|
195
|
+
`)}var Ou={desktop:{w:1280,h:800},mobile:{w:390,h:844}},$u=.1,_u=.15,ju=1.5,rl=24,Uu=40,lb=`
|
|
196
196
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
197
197
|
.persona-dc-root {
|
|
198
198
|
display: flex;
|
|
@@ -433,5 +433,5 @@ ${a.join(`
|
|
|
433
433
|
min-height: 300px;
|
|
434
434
|
}
|
|
435
435
|
}
|
|
436
|
-
`;function lb(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=ib,document.head.appendChild(e)}function cb(e,n){let t=e.clientWidth-rl*2-Uu,r=e.clientHeight-rl*2-Uu;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function db(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function pb(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");lb();let u=Math.max(0,Math.min(r,t.length-1)),p=s,f=o,g=null,v=1,x=!1,k=h("div","persona-dc-root"),C=h("div","persona-dc-toolbar"),L=h("div","persona-dc-toolbar-lead"),D=h("div","persona-dc-toolbar-trail"),W=_t({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Be(-1)}),E=h("div");E.style.position="relative";let M=h("button","persona-dc-title-btn");M.type="button",M.setAttribute("aria-expanded","false"),M.setAttribute("aria-haspopup","listbox");let O=h("span","persona-dc-title-text"),j=h("span","persona-dc-title-chevron"),$=ge("chevron-down",12,"currentColor",2);$&&j.appendChild($),M.append(O,j);let H=h("div","persona-dc-dropdown");H.setAttribute("role","listbox"),H.style.display="none";let F=!1;function K(){H.innerHTML="";for(let G=0;G<t.length;G++){let V=t[G],ve=h("button","persona-dc-dropdown-item");ve.type="button",ve.setAttribute("role","option"),ve.setAttribute("aria-current",G===u?"true":"false");let ce=h("span");if(ce.textContent=V.title,ve.appendChild(ce),V.description){let te=h("span","persona-dc-dropdown-desc");te.textContent=V.description,ve.appendChild(te)}ve.addEventListener("click",()=>{Se(),Re(G)}),H.appendChild(ve)}}function ne(){F=!F,H.style.display=F?"":"none",M.setAttribute("aria-expanded",F?"true":"false"),F&&K()}function Se(){F&&(F=!1,H.style.display="none",M.setAttribute("aria-expanded","false"))}M.addEventListener("click",G=>{G.stopPropagation(),ne()});let We=()=>Se();document.addEventListener("click",We),E.append(M,H);let _e=_t({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Be(1)}),fe=h("span","persona-dc-counter");L.append(W,E,_e,fe);let pe=null;i&&(pe=Ba({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:G=>{p=G,Q.dataset.device=p,g=null,J()}}),D.appendChild(pe.element));let Te=null;if(a){let G=h("div","persona-dc-zoom-controls"),V=_t({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let te=g!=null?g:v;g=Math.max($u,te-Ou),J()}});Te=h("span","persona-dc-zoom-level"),Te.title="Reset to 100%",Te.style.cursor="pointer",Te.addEventListener("click",()=>{g=1,J()});let ve=_t({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let te=g!=null?g:v;g=Math.min(_u,te+Ou),J()}}),ce=_t({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,J()}});G.append(V,Te,ve,ce),D.appendChild(G)}if(d){let G=h("div","persona-dc-separator");D.appendChild(G);let V=Ba({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ve=>{f=ve,Q.dataset.colorScheme=f,Me()}});D.appendChild(V.element)}let Ue=h("div","persona-dc-separator");D.appendChild(Ue);let ee=_t({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});D.appendChild(ee),C.append(L,D);let xe=h("div","persona-dc-stage"),Q=h("div","persona-dc-iframe-wrapper");Q.dataset.device=p,Q.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[u].title,Q.appendChild(re),xe.appendChild(Q),k.append(C,xe),e.appendChild(k);function Me(){var G;try{let V=(G=re.contentDocument)==null?void 0:G.body;if(!V)return;f==="dark"?V.classList.add("theme-dark"):V.classList.remove("theme-dark")}catch{}}re.addEventListener("load",()=>Me());function ae(){let G=t[u];O.textContent=G.title,fe.textContent=`${u+1} / ${t.length}`,re.title=G.title}function Be(G){let V=((u+G)%t.length+t.length)%t.length;Re(V)}function Re(G){G<0||G>=t.length||(u=G,re.src=t[u].url,ae(),l==null||l(u,t[u]))}function J(){var ve;if(x)return;let G=(ve=Fu[p])!=null?ve:Fu.desktop;v=cb(xe,G);let V=Math.max($u,Math.min(_u,g!=null?g:v));db(Q,re,G,V,p),Te&&(Te.textContent=`${Math.round(V*100)}%`)}let De=new ResizeObserver(()=>J());De.observe(xe),ae(),re.src=t[u].url,requestAnimationFrame(()=>J());function He(){x||(x=!0,De.disconnect(),document.removeEventListener("click",We),k.remove())}return{element:k,goTo:Re,next:()=>Be(1),prev:()=>Be(-1),getIndex:()=>u,setDevice(G){p=G,Q.dataset.device=G,pe==null||pe.setSelected(G),g=null,J()},setColorScheme(G){f=G,Q.dataset.colorScheme=G},setZoom(G){g=G,J()},destroy:He}}function ub(){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 mb(){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 gb(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:xr(e.colors.primary,.95),100:xr(e.colors.primary,.9),200:xr(e.colors.primary,.8),300:xr(e.colors.primary,.7),400:xr(e.colors.primary,.6),500:e.colors.primary,600:xr(e.colors.primary,.8),700:xr(e.colors.primary,.7),800:xr(e.colors.primary,.6),900:xr(e.colors.primary,.5),950:xr(e.colors.primary,.45)}}),{...n,palette:t}}}}function fb(){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 hb(){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 xr(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function yb(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var bb={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"}}},ju={components:{panel:{borderRadius:"0",shadow:"none"}}},qu={id:"shop",label:"Shopping Assistant",config:{theme:bb,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Gn},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?"]}},zu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:ju}},Vu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:ju}},Ju={shop:qu,minimal:zu,fullscreen:Vu};function xb(e){return Ju[e]}var $C=bu;export{$p as ASK_USER_QUESTION_TOOL_NAME,$o as AgentWidgetClient,As as AgentWidgetSession,jo as AttachmentManager,gp as DEFAULT_COMPONENTS,mi as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Gn as DEFAULT_FLOATING_LAUNCHER_WIDTH,up as DEFAULT_PALETTE,mp as DEFAULT_SEMANTIC,Dt as DEFAULT_WIDGET_CONFIG,Ju as PRESETS,Vu as PRESET_FULLSCREEN,zu as PRESET_MINIMAL,qu as PRESET_SHOP,If as THEME_ZONES,es as VERSION,ub as accessibilityPlugin,mb as animationsPlugin,So as applyThemeVariables,zo as attachHeaderToContainer,gb as brandPlugin,Ns as buildComposer,kp as buildDefaultHeader,eo as buildHeader,Ds as buildHeaderWithLayout,Mp as buildMinimalHeader,Jy as collectEnrichedPageContext,so as componentRegistry,Ga as createActionManager,Ji as createAgentExperience,$h as createAskUserQuestionBubble,ui as createBestAvailableVoiceProvider,ch as createBubbleWithLayout,qi as createCSATFeedback,Ai as createComboButton,fy as createComponentMiddleware,$i as createComponentStreamParser,Zd as createDefaultSanitizer,pb as createDemoCarousel,Xu as createDirectivePostprocessor,Eo as createDropdownMenu,sm as createFlexibleJsonStreamParser,_t as createIconButton,gm as createImagePart,ci as createJsonStreamParser,Ha as createLabelButton,Oi as createLocalStorageAdapter,ca as createMarkdownProcessor,No as createMarkdownProcessorFromConfig,Dp as createMessageActions,zi as createNPSFeedback,ii as createPlainTextParser,yb as createPlugin,li as createRegexJsonParser,Fs as createStandardBubble,ya as createTextPart,Es as createTheme,yi as createThemeObserver,Ba as createToggleGroup,Vo as createTypingIndicator,Uo as createVoiceProvider,Ya as createWidgetHostLayout,di as createXmlParser,$C as default,Yo as defaultActionHandlers,Ka as defaultJsonActionParser,ku as defaultParseRules,Aa as detectColorScheme,Yu as directivePostprocessor,$s as ensureAskUserQuestionSheet,Fo as escapeHtml,ji as extractComponentDirectiveFromMessage,fm as fileToImagePart,Ky as formatEnrichedContext,_o as generateAssistantMessageId,eb as generateCodeSnippet,cm as generateMessageId,Lu as generateStableSelector,ws as generateUserMessageId,Ts as getActiveTheme,bp as getColorScheme,pm as getDisplayText,Lp as getHeaderLayout,mm as getImageParts,xb as getPreset,Ui as hasComponentDirective,um as hasImages,Si as headerLayouts,hb as highContrastPlugin,bu as initAgentWidget,to as isAskUserQuestionMessage,gy as isComponentDirectiveType,on as isDockedMountMode,wa as isVoiceSupported,_f as listRegisteredStreamAnimations,Qd as markdownPostprocessor,gi as mergeWithDefaults,dm as normalizeContent,no as parseAskUserQuestionPayload,Ja as pluginRegistry,fb as reducedMotionPlugin,Of as registerStreamAnimationPlugin,ko as removeAskUserQuestionSheet,_i as renderComponentDirective,Bp as renderLoadingIndicatorWithFallback,ge as renderLucideIcon,lr as resolveDockConfig,bs as resolveSanitizer,fi as resolveTokens,hi as themeToCssVariables,$f as unregisterStreamAnimationPlugin,hm as validateImageFile,fp as validateTheme};
|
|
436
|
+
`;function cb(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=lb,document.head.appendChild(e)}function db(e,n){let t=e.clientWidth-rl*2-Uu,r=e.clientHeight-rl*2-Uu;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function pb(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function ub(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");cb();let u=Math.max(0,Math.min(r,t.length-1)),p=s,f=o,g=null,v=1,x=!1,k=h("div","persona-dc-root"),w=h("div","persona-dc-toolbar"),L=h("div","persona-dc-toolbar-lead"),D=h("div","persona-dc-toolbar-trail"),W=_t({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Be(-1)}),E=h("div");E.style.position="relative";let M=h("button","persona-dc-title-btn");M.type="button",M.setAttribute("aria-expanded","false"),M.setAttribute("aria-haspopup","listbox");let O=h("span","persona-dc-title-text"),U=h("span","persona-dc-title-chevron"),$=ge("chevron-down",12,"currentColor",2);$&&U.appendChild($),M.append(O,U);let H=h("div","persona-dc-dropdown");H.setAttribute("role","listbox"),H.style.display="none";let F=!1;function K(){H.innerHTML="";for(let G=0;G<t.length;G++){let V=t[G],ve=h("button","persona-dc-dropdown-item");ve.type="button",ve.setAttribute("role","option"),ve.setAttribute("aria-current",G===u?"true":"false");let ce=h("span");if(ce.textContent=V.title,ve.appendChild(ce),V.description){let te=h("span","persona-dc-dropdown-desc");te.textContent=V.description,ve.appendChild(te)}ve.addEventListener("click",()=>{Se(),Re(G)}),H.appendChild(ve)}}function ne(){F=!F,H.style.display=F?"":"none",M.setAttribute("aria-expanded",F?"true":"false"),F&&K()}function Se(){F&&(F=!1,H.style.display="none",M.setAttribute("aria-expanded","false"))}M.addEventListener("click",G=>{G.stopPropagation(),ne()});let We=()=>Se();document.addEventListener("click",We),E.append(M,H);let _e=_t({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Be(1)}),fe=h("span","persona-dc-counter");L.append(W,E,_e,fe);let pe=null;i&&(pe=Ba({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:G=>{p=G,Q.dataset.device=p,g=null,J()}}),D.appendChild(pe.element));let Te=null;if(a){let G=h("div","persona-dc-zoom-controls"),V=_t({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let te=g!=null?g:v;g=Math.max(_u,te-$u),J()}});Te=h("span","persona-dc-zoom-level"),Te.title="Reset to 100%",Te.style.cursor="pointer",Te.addEventListener("click",()=>{g=1,J()});let ve=_t({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let te=g!=null?g:v;g=Math.min(ju,te+$u),J()}}),ce=_t({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,J()}});G.append(V,Te,ve,ce),D.appendChild(G)}if(d){let G=h("div","persona-dc-separator");D.appendChild(G);let V=Ba({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ve=>{f=ve,Q.dataset.colorScheme=f,Me()}});D.appendChild(V.element)}let je=h("div","persona-dc-separator");D.appendChild(je);let ee=_t({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});D.appendChild(ee),w.append(L,D);let xe=h("div","persona-dc-stage"),Q=h("div","persona-dc-iframe-wrapper");Q.dataset.device=p,Q.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[u].title,Q.appendChild(re),xe.appendChild(Q),k.append(w,xe),e.appendChild(k);function Me(){var G;try{let V=(G=re.contentDocument)==null?void 0:G.body;if(!V)return;f==="dark"?V.classList.add("theme-dark"):V.classList.remove("theme-dark")}catch{}}re.addEventListener("load",()=>Me());function ae(){let G=t[u];O.textContent=G.title,fe.textContent=`${u+1} / ${t.length}`,re.title=G.title}function Be(G){let V=((u+G)%t.length+t.length)%t.length;Re(V)}function Re(G){G<0||G>=t.length||(u=G,re.src=t[u].url,ae(),l==null||l(u,t[u]))}function J(){var ve;if(x)return;let G=(ve=Ou[p])!=null?ve:Ou.desktop;v=db(xe,G);let V=Math.max(_u,Math.min(ju,g!=null?g:v));pb(Q,re,G,V,p),Te&&(Te.textContent=`${Math.round(V*100)}%`)}let De=new ResizeObserver(()=>J());De.observe(xe),ae(),re.src=t[u].url,requestAnimationFrame(()=>J());function He(){x||(x=!0,De.disconnect(),document.removeEventListener("click",We),k.remove())}return{element:k,goTo:Re,next:()=>Be(1),prev:()=>Be(-1),getIndex:()=>u,setDevice(G){p=G,Q.dataset.device=G,pe==null||pe.setSelected(G),g=null,J()},setColorScheme(G){f=G,Q.dataset.colorScheme=G},setZoom(G){g=G,J()},destroy:He}}function mb(){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 gb(){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 fb(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:xr(e.colors.primary,.95),100:xr(e.colors.primary,.9),200:xr(e.colors.primary,.8),300:xr(e.colors.primary,.7),400:xr(e.colors.primary,.6),500:e.colors.primary,600:xr(e.colors.primary,.8),700:xr(e.colors.primary,.7),800:xr(e.colors.primary,.6),900:xr(e.colors.primary,.5),950:xr(e.colors.primary,.45)}}),{...n,palette:t}}}}function hb(){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 yb(){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 xr(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function bb(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var xb={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"}}},qu={components:{panel:{borderRadius:"0",shadow:"none"}}},zu={id:"shop",label:"Shopping Assistant",config:{theme:xb,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Gn},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?"]}},Vu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:qu}},Ju={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:qu}},Ku={shop:zu,minimal:Vu,fullscreen:Ju};function vb(e){return Ku[e]}var _w=xu;export{$p as ASK_USER_QUESTION_TOOL_NAME,$o as AgentWidgetClient,As as AgentWidgetSession,Uo as AttachmentManager,gp as DEFAULT_COMPONENTS,mi as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Gn as DEFAULT_FLOATING_LAUNCHER_WIDTH,up as DEFAULT_PALETTE,mp as DEFAULT_SEMANTIC,Dt as DEFAULT_WIDGET_CONFIG,Ku as PRESETS,Ju as PRESET_FULLSCREEN,Vu as PRESET_MINIMAL,zu as PRESET_SHOP,Wf as THEME_ZONES,es as VERSION,mb as accessibilityPlugin,gb as animationsPlugin,So as applyThemeVariables,zo as attachHeaderToContainer,fb as brandPlugin,Ns as buildComposer,kp as buildDefaultHeader,eo as buildHeader,Ds as buildHeaderWithLayout,Mp as buildMinimalHeader,Ky as collectEnrichedPageContext,so as componentRegistry,Ga as createActionManager,Ji as createAgentExperience,_h as createAskUserQuestionBubble,ui as createBestAvailableVoiceProvider,dh as createBubbleWithLayout,qi as createCSATFeedback,Ai as createComboButton,hy as createComponentMiddleware,$i as createComponentStreamParser,Zd as createDefaultSanitizer,ub as createDemoCarousel,Yu as createDirectivePostprocessor,Eo as createDropdownMenu,am as createFlexibleJsonStreamParser,_t as createIconButton,fm as createImagePart,ci as createJsonStreamParser,Ha as createLabelButton,Oi as createLocalStorageAdapter,ca as createMarkdownProcessor,No as createMarkdownProcessorFromConfig,Dp as createMessageActions,zi as createNPSFeedback,ii as createPlainTextParser,bb as createPlugin,li as createRegexJsonParser,Fs as createStandardBubble,ya as createTextPart,Es as createTheme,yi as createThemeObserver,Ba as createToggleGroup,Vo as createTypingIndicator,jo as createVoiceProvider,Ya as createWidgetHostLayout,di as createXmlParser,_w as default,Yo as defaultActionHandlers,Ka as defaultJsonActionParser,Mu as defaultParseRules,Aa as detectColorScheme,Zu as directivePostprocessor,$s as ensureAskUserQuestionSheet,Fo as escapeHtml,Ui as extractComponentDirectiveFromMessage,hm as fileToImagePart,Gy as formatEnrichedContext,_o as generateAssistantMessageId,tb as generateCodeSnippet,dm as generateMessageId,Pu as generateStableSelector,Cs as generateUserMessageId,Ts as getActiveTheme,bp as getColorScheme,um as getDisplayText,Lp as getHeaderLayout,gm as getImageParts,vb as getPreset,ji as hasComponentDirective,mm as hasImages,Si as headerLayouts,yb as highContrastPlugin,xu as initAgentWidget,to as isAskUserQuestionMessage,fy as isComponentDirectiveType,on as isDockedMountMode,Ca as isVoiceSupported,jf as listRegisteredStreamAnimations,Qd as markdownPostprocessor,gi as mergeWithDefaults,pm as normalizeContent,no as parseAskUserQuestionPayload,Ja as pluginRegistry,hb as reducedMotionPlugin,$f as registerStreamAnimationPlugin,ko as removeAskUserQuestionSheet,_i as renderComponentDirective,Bp as renderLoadingIndicatorWithFallback,ge as renderLucideIcon,lr as resolveDockConfig,bs as resolveSanitizer,fi as resolveTokens,hi as themeToCssVariables,_f as unregisterStreamAnimationPlugin,ym as validateImageFile,fp as validateTheme};
|
|
437
437
|
//# sourceMappingURL=index.js.map
|