@runtypelabs/persona 3.8.0 → 3.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +5 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +8 -8
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +1 -0
- package/dist/theme-editor.js +1 -0
- package/package.json +1 -1
- package/src/ui.ts +1 -0
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use strict";var Yd=Object.create;var Go=Object.defineProperty;var Kd=Object.getOwnPropertyDescriptor;var Xd=Object.getOwnPropertyNames;var Gd=Object.getPrototypeOf,Zd=Object.prototype.hasOwnProperty;var Qd=(e,r)=>{for(var t in r)Go(e,t,{get:r[t],enumerable:!0})},rc=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Xd(r))!Zd.call(e,s)&&s!==t&&Go(e,s,{get:()=>r[s],enumerable:!(n=Kd(r,s))||n.enumerable});return e};var oc=(e,r,t)=>(t=e!=null?Yd(Gd(e)):{},rc(r||!e||!e.__esModule?Go(t,"default",{value:e,enumerable:!0}):t,e)),ep=e=>rc(Go({},"__esModule",{value:!0}),e);var Yu={};Qd(Yu,{AgentWidgetClient:()=>Rr,AgentWidgetSession:()=>to,AttachmentManager:()=>Fr,DEFAULT_COMPONENTS:()=>qs,DEFAULT_PALETTE:()=>zs,DEFAULT_SEMANTIC:()=>Vs,DEFAULT_WIDGET_CONFIG:()=>wt,PRESETS:()=>Ta,PRESET_FULLSCREEN:()=>Ea,PRESET_MINIMAL:()=>Aa,PRESET_SHOP:()=>Sa,THEME_ZONES:()=>kc,VERSION:()=>_r,accessibilityPlugin:()=>Nd,animationsPlugin:()=>Od,applyThemeVariables:()=>vr,attachHeaderToContainer:()=>Nr,brandPlugin:()=>$d,buildComposer:()=>oo,buildDefaultHeader:()=>Xs,buildHeader:()=>or,buildHeaderWithLayout:()=>ro,buildMinimalHeader:()=>Gs,collectEnrichedPageContext:()=>wd,componentRegistry:()=>sr,createActionManager:()=>jo,createAgentExperience:()=>Is,createBestAvailableVoiceProvider:()=>cs,createBubbleWithLayout:()=>_c,createCSATFeedback:()=>ks,createComboButton:()=>bs,createComponentMiddleware:()=>sd,createComponentStreamParser:()=>As,createDefaultSanitizer:()=>$s,createDemoCarousel:()=>Fd,createDirectivePostprocessor:()=>cc,createDropdownMenu:()=>Sr,createFlexibleJsonStreamParser:()=>mc,createIconButton:()=>At,createImagePart:()=>vc,createJsonStreamParser:()=>ns,createLabelButton:()=>Do,createLocalStorageAdapter:()=>Ss,createMarkdownProcessor:()=>Ao,createMarkdownProcessorFromConfig:()=>Wr,createMessageActions:()=>ea,createNPSFeedback:()=>Ls,createPlainTextParser:()=>es,createPlugin:()=>zd,createRegexJsonParser:()=>ts,createStandardBubble:()=>so,createTextPart:()=>ss,createTheme:()=>no,createThemeObserver:()=>gs,createToggleGroup:()=>Fo,createTypingIndicator:()=>Or,createVoiceProvider:()=>Dr,createWidgetHostLayout:()=>zo,createXmlParser:()=>rs,default:()=>Ju,defaultActionHandlers:()=>$r,defaultJsonActionParser:()=>_o,defaultParseRules:()=>xa,detectColorScheme:()=>Io,directivePostprocessor:()=>dc,escapeHtml:()=>Zr,extractComponentDirectiveFromMessage:()=>Ms,fileToImagePart:()=>Cc,formatEnrichedContext:()=>Sd,generateAssistantMessageId:()=>Hr,generateCodeSnippet:()=>Id,generateMessageId:()=>fc,generateStableSelector:()=>va,generateUserMessageId:()=>eo,getActiveTheme:()=>Po,getColorScheme:()=>Js,getDisplayText:()=>yc,getHeaderLayout:()=>Zs,getImageParts:()=>xc,getPreset:()=>qd,hasComponentDirective:()=>Ts,hasImages:()=>bc,headerLayouts:()=>xs,highContrastPlugin:()=>jd,initAgentWidget:()=>fa,isComponentDirectiveType:()=>od,isDockedMountMode:()=>Jt,isVoiceSupported:()=>Mo,markdownPostprocessor:()=>Os,mergeWithDefaults:()=>ws,normalizeContent:()=>hc,pluginRegistry:()=>$o,reducedMotionPlugin:()=>_d,renderComponentDirective:()=>Es,renderLoadingIndicatorWithFallback:()=>Qs,resolveDockConfig:()=>Pn,resolveSanitizer:()=>Qr,resolveTokens:()=>ps,themeToCssVariables:()=>us,validateImageFile:()=>wc,validateTheme:()=>Us});module.exports=ep(Yu);var ac=require("marked"),tp=e=>{if(e)return e},Ao=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new ac.Marked({gfm:(s=r==null?void 0:r.gfm)!=null?s:!0,breaks:(o=r==null?void 0:r.breaks)!=null?o:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=tp(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},Wr=e=>e?Ao({markedOptions:e.options,renderer:e.renderer}):Ao(),np=Ao(),Os=e=>np(e),Zr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ic=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),sc=e=>`%%FORM_PLACEHOLDER_${e}%%`,lc=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=sc(r.length);return r.push({token:a,type:String(o.type)}),a}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,s)=>{let o=sc(r.length);return r.push({token:o,type:s}),o}),t},cc=e=>{let r=Wr(e);return t=>{let n=[],s=lc(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${ic(i)}"></div>`;o=o.replace(d,p)}),o}},dc=e=>{let r=[],t=lc(e,r),n=Os(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ic(o)}"></div>`;n=n.replace(a,d)}),n};var pc=oc(require("dompurify"),1),rp={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"]},op=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,$s=()=>{let e=(0,pc.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!op.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,rp)},Qr=e=>e===!1?null:typeof e=="function"?e:$s();var nr=require("partial-json"),Zo=e=>e.replace(/\\n/g,`
|
|
2
2
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Eo=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)}},sp=e=>{var a,i;let r=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:r,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},uc=e=>e.status==="complete"?sp(e):e.status==="pending"?"Waiting":"",ap=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 gc=e=>e.status==="complete"?ap(e):"Using tool...",ip=()=>{let e=null,r=0,t=n=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=n.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Qo=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},es=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ts=()=>{var r;let e=ip();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},ns=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,nr.parse)(t,nr.STR|nr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Zo(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Zo(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},mc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Zo(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Zo(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=(0,nr.parse)(o,nr.STR|nr.OBJ),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},rs=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var lp="https://api.runtype.com/v1/dispatch",_s="https://api.runtype.com",js=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 cp(e){switch(e){case"json":return ns;case"regex-json":return ts;case"xml":return rs;default:return es}}var Rr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:lp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:cp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_s;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_s}/v1/client/feedback`}async sendFeedback(r){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let 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 m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,u={sessionId:d.sessionId,messages:r.messages.filter(js).map(m=>{var C,M,b;return{id:m.id,role:m.role,content:(b=(M=(C=m.contentParts)!=null?C:m.llmContent)!=null?M:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let h=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:n.signal});if(!h.ok){let m=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(h.status===429){let M=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!h.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(h.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let 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:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let 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:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_s}/v1/agents/${r.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(js).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(js).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=u,s(u),u},c=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var Ie,Re,ot,Et,j,U,re,_,z,Q,lt,K,X,St,st,Pt,Yt,Be,ie,ke,Tt,Mt,Qe,et,en,Zt,tn,O,Ee,le,dt,He,G,he,Pe,mt,Nt,at,Ot,pt,Je,ut,Ne,$t,_n,Yn,Rn,Xe,Er,jn,Tr,zn,jr,ir,Kn,tt,xn,Hn,un,lr,vn,bt,an,Mn,cr,Xn,dr,Vn,Cn,qn,xt,Wt,Rt,wn,pr,Bn,Sn,H,Dn,Fn,ur,gn,An,ee,Nn,zr,uo,Vr,Ye,go,kn,mn,Vo,qo,mo,Gn,Uo,qr,Ur,Zn,fo,gr,mr,Jo,Yo,Ns,Mr,kr,kt,Jr,Yr,ho,yo,bo,xo,ln,En,Qn,Oe;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=Z=>{let qe=Z.reasoning?{...Z.reasoning,chunks:[...Z.reasoning.chunks]}:void 0,nt=Z.toolCall?{...Z.toolCall,chunks:Z.toolCall.chunks?[...Z.toolCall.chunks]:void 0}:void 0,_t=Z.tools?Z.tools.map(jt=>({...jt,chunks:jt.chunks?[...jt.chunks]:void 0})):void 0;return{...Z,reasoning:qe,toolCall:nt,tools:_t}},u=Z=>{t({type:"message",message:p(Z)})},h=null,m={current:null},C={current:null},M=new Map,b=new Map,x={lastId:null,byStep:new Map},S={lastId:null,byCall:new Map},F=Z=>{if(Z==null)return null;try{return String(Z)}catch{return null}},w=Z=>{var qe,nt,_t,jt,Kt;return F((Kt=(jt=(_t=(nt=(qe=Z.stepId)!=null?qe:Z.step_id)!=null?nt:Z.step)!=null?_t:Z.parentId)!=null?jt:Z.flowStepId)!=null?Kt:Z.flow_step_id)},k=Z=>{var qe,nt,_t,jt,Kt,Lt,v;return F((v=(Lt=(Kt=(jt=(_t=(nt=(qe=Z.callId)!=null?qe:Z.call_id)!=null?nt:Z.requestId)!=null?_t:Z.request_id)!=null?jt:Z.toolCallId)!=null?Kt:Z.tool_call_id)!=null?Lt:Z.stepId)!=null?v:Z.step_id)},R=()=>h||(h={id:n!=null?n:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(h),h),T=(Z,qe)=>{x.lastId=qe,Z&&x.byStep.set(Z,qe)},Y=(Z,qe)=>{var Kt;let nt=(Kt=Z.reasoningId)!=null?Kt:Z.id,_t=w(Z);if(nt){let Lt=String(nt);return T(_t,Lt),Lt}if(_t){let Lt=x.byStep.get(_t);if(Lt)return x.lastId=Lt,Lt}if(x.lastId&&!qe)return x.lastId;if(!qe)return null;let jt=`reason-${c()}`;return T(_t,jt),jt},ue=Z=>{let qe=M.get(Z);if(qe)return qe;let nt={id:`reason-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Z,status:"streaming",chunks:[]}};return M.set(Z,nt),u(nt),nt},se=(Z,qe)=>{S.lastId=qe,Z&&S.byCall.set(Z,qe)},$=new Set,te=new Map,Ae=new Set,ne=new Map,Ce=Z=>{if(!Z)return!1;let qe=Z.replace(/_+/g,"_").replace(/^_|_$/g,"");return qe==="emit_artifact_markdown"||qe==="emit_artifact_component"},Me=(Z,qe)=>{var Kt;let nt=(Kt=Z.toolId)!=null?Kt:Z.id,_t=k(Z);if(nt){let Lt=String(nt);return se(_t,Lt),Lt}if(_t){let Lt=S.byCall.get(_t);if(Lt)return S.lastId=Lt,Lt}if(S.lastId&&!qe)return S.lastId;if(!qe)return null;let jt=`tool-${c()}`;return se(_t,jt),jt},de=Z=>{let qe=b.get(Z);if(qe)return qe;let nt={id:`tool-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Z,status:"pending"}};return b.set(Z,nt),u(nt),nt},fe=Z=>{if(typeof Z=="number"&&Number.isFinite(Z))return Z;if(typeof Z=="string"){let qe=Number(Z);if(!Number.isNaN(qe)&&Number.isFinite(qe))return qe;let nt=Date.parse(Z);if(!Number.isNaN(nt))return nt}return Date.now()},Se=Z=>{if(typeof Z=="string")return Z;if(Z==null)return"";try{return JSON.stringify(Z)}catch{return String(Z)}},J=new Map,ae=new Map,ge=null,De=new Map,Le=(Ie=this.config.iterationDisplay)!=null?Ie:"separate";for(;;){let{done:Z,value:qe}=await s.read();if(Z)break;a+=o.decode(qe,{stream:!0});let nt=a.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Qo=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},es=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ts=()=>{var r;let e=ip();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},ns=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,nr.parse)(t,nr.STR|nr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Zo(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Zo(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},mc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Zo(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Zo(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=(0,nr.parse)(o,nr.STR|nr.OBJ),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},rs=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var lp="https://api.runtype.com/v1/dispatch",_s="https://api.runtype.com",js=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 cp(e){switch(e){case"json":return ns;case"regex-json":return ts;case"xml":return rs;default:return es}}var Rr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:lp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:cp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_s;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_s}/v1/client/feedback`}async sendFeedback(r){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let 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 m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,u={sessionId:d.sessionId,messages:r.messages.filter(js).map(m=>{var C,M,b;return{id:m.id,role:m.role,content:(b=(M=(C=m.contentParts)!=null?C:m.llmContent)!=null?M:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let h=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:n.signal});if(!h.ok){let m=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(h.status===429){let M=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!h.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(h.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let 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:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let 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:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_s}/v1/agents/${r.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(js).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(js).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=u,s(u),u},c=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var Ie,Re,ot,Et,j,U,re,_,z,Q,lt,K,X,St,st,Pt,Yt,Be,ie,ke,Tt,Mt,Qe,et,en,Zt,tn,O,Ee,le,dt,He,G,he,Pe,mt,Nt,at,Ot,pt,Je,ut,Ne,$t,_n,Yn,Rn,Xe,Er,jn,Tr,zn,jr,ir,Kn,tt,xn,Hn,an,lr,vn,bt,ln,Mn,cr,Xn,dr,Vn,Cn,qn,xt,Wt,Rt,wn,pr,Bn,Sn,H,Dn,Fn,ur,gn,An,ee,Nn,zr,uo,Vr,Ye,go,kn,mn,Vo,qo,mo,Gn,Uo,qr,Ur,Zn,fo,gr,mr,Jo,Yo,Ns,Mr,kr,kt,Jr,Yr,ho,yo,bo,xo,cn,En,Qn,Oe;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=Z=>{let qe=Z.reasoning?{...Z.reasoning,chunks:[...Z.reasoning.chunks]}:void 0,nt=Z.toolCall?{...Z.toolCall,chunks:Z.toolCall.chunks?[...Z.toolCall.chunks]:void 0}:void 0,_t=Z.tools?Z.tools.map(jt=>({...jt,chunks:jt.chunks?[...jt.chunks]:void 0})):void 0;return{...Z,reasoning:qe,toolCall:nt,tools:_t}},u=Z=>{t({type:"message",message:p(Z)})},h=null,m={current:null},C={current:null},M=new Map,b=new Map,x={lastId:null,byStep:new Map},S={lastId:null,byCall:new Map},F=Z=>{if(Z==null)return null;try{return String(Z)}catch{return null}},w=Z=>{var qe,nt,_t,jt,Kt;return F((Kt=(jt=(_t=(nt=(qe=Z.stepId)!=null?qe:Z.step_id)!=null?nt:Z.step)!=null?_t:Z.parentId)!=null?jt:Z.flowStepId)!=null?Kt:Z.flow_step_id)},k=Z=>{var qe,nt,_t,jt,Kt,Lt,v;return F((v=(Lt=(Kt=(jt=(_t=(nt=(qe=Z.callId)!=null?qe:Z.call_id)!=null?nt:Z.requestId)!=null?_t:Z.request_id)!=null?jt:Z.toolCallId)!=null?Kt:Z.tool_call_id)!=null?Lt:Z.stepId)!=null?v:Z.step_id)},R=()=>h||(h={id:n!=null?n:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(h),h),T=(Z,qe)=>{x.lastId=qe,Z&&x.byStep.set(Z,qe)},Y=(Z,qe)=>{var Kt;let nt=(Kt=Z.reasoningId)!=null?Kt:Z.id,_t=w(Z);if(nt){let Lt=String(nt);return T(_t,Lt),Lt}if(_t){let Lt=x.byStep.get(_t);if(Lt)return x.lastId=Lt,Lt}if(x.lastId&&!qe)return x.lastId;if(!qe)return null;let jt=`reason-${c()}`;return T(_t,jt),jt},ue=Z=>{let qe=M.get(Z);if(qe)return qe;let nt={id:`reason-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Z,status:"streaming",chunks:[]}};return M.set(Z,nt),u(nt),nt},se=(Z,qe)=>{S.lastId=qe,Z&&S.byCall.set(Z,qe)},$=new Set,te=new Map,Ae=new Set,ne=new Map,Ce=Z=>{if(!Z)return!1;let qe=Z.replace(/_+/g,"_").replace(/^_|_$/g,"");return qe==="emit_artifact_markdown"||qe==="emit_artifact_component"},Me=(Z,qe)=>{var Kt;let nt=(Kt=Z.toolId)!=null?Kt:Z.id,_t=k(Z);if(nt){let Lt=String(nt);return se(_t,Lt),Lt}if(_t){let Lt=S.byCall.get(_t);if(Lt)return S.lastId=Lt,Lt}if(S.lastId&&!qe)return S.lastId;if(!qe)return null;let jt=`tool-${c()}`;return se(_t,jt),jt},de=Z=>{let qe=b.get(Z);if(qe)return qe;let nt={id:`tool-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Z,status:"pending"}};return b.set(Z,nt),u(nt),nt},fe=Z=>{if(typeof Z=="number"&&Number.isFinite(Z))return Z;if(typeof Z=="string"){let qe=Number(Z);if(!Number.isNaN(qe)&&Number.isFinite(qe))return qe;let nt=Date.parse(Z);if(!Number.isNaN(nt))return nt}return Date.now()},Se=Z=>{if(typeof Z=="string")return Z;if(Z==null)return"";try{return JSON.stringify(Z)}catch{return String(Z)}},J=new Map,ae=new Map,ge=null,De=new Map,Le=(Ie=this.config.iterationDisplay)!=null?Ie:"separate";for(;;){let{done:Z,value:qe}=await s.read();if(Z)break;a+=o.decode(qe,{stream:!0});let nt=a.split(`
|
|
5
5
|
|
|
6
6
|
`);a=(Re=nt.pop())!=null?Re:"";for(let _t of nt){let jt=_t.split(`
|
|
7
|
-
`),Kt="message",Lt="";for(let D of jt)D.startsWith("event:")?Kt=D.replace("event:","").trim():D.startsWith("data:")&&(Lt+=D.replace("data:","").trim());if(!Lt)continue;let v;try{v=JSON.parse(Lt)}catch(D){t({type:"error",error:D instanceof Error?D:new Error("Failed to parse chat stream payload")});continue}let _e=Kt!=="message"?Kt:(ot=v.type)!=null?ot:"message";if((Et=this.onSSEEvent)==null||Et.call(this,_e,v),this.parseSSEEvent){m.current=h;let D=await this.handleCustomSSEEvent(v,t,m,u,c,C);if(m.current&&m.current!==h&&(h=m.current),D)continue}if(_e==="reason_start"){let D=(j=Y(v,!0))!=null?j:`reason-${c()}`,A=ue(D);A.reasoning=(U=A.reasoning)!=null?U:{id:D,status:"streaming",chunks:[]},A.reasoning.startedAt=(_=A.reasoning.startedAt)!=null?_:fe((re=v.startedAt)!=null?re:v.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",u(A)}else if(_e==="reason_delta"||_e==="reason_chunk"){let D=(Q=(z=Y(v,!1))!=null?z:Y(v,!0))!=null?Q:`reason-${c()}`,A=ue(D);A.reasoning=(lt=A.reasoning)!=null?lt:{id:D,status:"streaming",chunks:[]},A.reasoning.startedAt=(X=A.reasoning.startedAt)!=null?X:fe((K=v.startedAt)!=null?K:v.timestamp);let N=(Pt=(st=(St=v.reasoningText)!=null?St:v.text)!=null?st:v.delta)!=null?Pt:"";if(N&&v.hidden!==!0&&A.reasoning.chunks.push(String(N)),A.reasoning.status=v.done?"complete":"streaming",v.done){A.reasoning.completedAt=fe((Yt=v.completedAt)!=null?Yt:v.timestamp);let ce=(Be=A.reasoning.startedAt)!=null?Be:Date.now();A.reasoning.durationMs=Math.max(0,((ie=A.reasoning.completedAt)!=null?ie:Date.now())-ce)}A.streaming=A.reasoning.status!=="complete",u(A)}else if(_e==="reason_complete"){let D=(Tt=(ke=Y(v,!1))!=null?ke:Y(v,!0))!=null?Tt:`reason-${c()}`,A=M.get(D);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=fe((Mt=v.completedAt)!=null?Mt:v.timestamp);let ce=(Qe=A.reasoning.startedAt)!=null?Qe:Date.now();A.reasoning.durationMs=Math.max(0,((et=A.reasoning.completedAt)!=null?et:Date.now())-ce),A.streaming=!1,u(A)}let N=w(v);N&&x.byStep.delete(N)}else if(_e==="tool_start"){let D=(en=Me(v,!0))!=null?en:`tool-${c()}`,A=(Zt=v.toolName)!=null?Zt:v.name;if(Ce(A)){$.add(D);continue}let N=de(D),ce=(tn=N.toolCall)!=null?tn:{id:D,status:"pending"};ce.name=A!=null?A:ce.name,ce.status="running",v.args!==void 0?ce.args=v.args:v.parameters!==void 0&&(ce.args=v.parameters),ce.startedAt=(Ee=ce.startedAt)!=null?Ee:fe((O=v.startedAt)!=null?O:v.timestamp),ce.completedAt=void 0,ce.durationMs=void 0,N.toolCall=ce,N.streaming=!0;let Te=v.agentContext;(Te||v.executionId)&&(N.agentMetadata={executionId:(le=Te==null?void 0:Te.executionId)!=null?le:v.executionId,iteration:(dt=Te==null?void 0:Te.iteration)!=null?dt:v.iteration}),u(N)}else if(_e==="tool_chunk"||_e==="tool_delta"){let D=(G=(He=Me(v,!1))!=null?He:Me(v,!0))!=null?G:`tool-${c()}`;if($.has(D))continue;let A=de(D),N=(he=A.toolCall)!=null?he:{id:D,status:"running"};N.startedAt=(mt=N.startedAt)!=null?mt:fe((Pe=v.startedAt)!=null?Pe:v.timestamp);let ce=(Ot=(at=(Nt=v.text)!=null?Nt:v.delta)!=null?at:v.message)!=null?Ot:"";ce&&(N.chunks=(pt=N.chunks)!=null?pt:[],N.chunks.push(String(ce))),N.status="running",A.toolCall=N,A.streaming=!0;let Te=v.agentContext;(Te||v.executionId)&&(A.agentMetadata=(Ne=A.agentMetadata)!=null?Ne:{executionId:(Je=Te==null?void 0:Te.executionId)!=null?Je:v.executionId,iteration:(ut=Te==null?void 0:Te.iteration)!=null?ut:v.iteration}),u(A)}else if(_e==="tool_complete"){let D=(_n=($t=Me(v,!1))!=null?$t:Me(v,!0))!=null?_n:`tool-${c()}`;if($.has(D)){$.delete(D);continue}let A=de(D),N=(Yn=A.toolCall)!=null?Yn:{id:D,status:"running"};N.status="complete",v.result!==void 0&&(N.result=v.result),typeof v.duration=="number"&&(N.duration=v.duration),N.completedAt=fe((Rn=v.completedAt)!=null?Rn:v.timestamp);let ce=(Xe=v.duration)!=null?Xe:v.executionTime;if(typeof ce=="number")N.durationMs=ce;else{let Ue=(Er=N.startedAt)!=null?Er:Date.now();N.durationMs=Math.max(0,((jn=N.completedAt)!=null?jn:Date.now())-Ue)}A.toolCall=N,A.streaming=!1;let Te=v.agentContext;(Te||v.executionId)&&(A.agentMetadata=(jr=A.agentMetadata)!=null?jr:{executionId:(Tr=Te==null?void 0:Te.executionId)!=null?Tr:v.executionId,iteration:(zn=Te==null?void 0:Te.iteration)!=null?zn:v.iteration}),u(A);let rt=k(v);rt&&S.byCall.delete(rt)}else if(_e==="step_chunk"||_e==="step_delta"){let D=v.stepType,A=v.executionType;if(D==="tool"||A==="context")continue;let N=R(),ce=(xn=(tt=(Kn=(ir=v.text)!=null?ir:v.delta)!=null?Kn:v.content)!=null?tt:v.chunk)!=null?xn:"";if(ce){let rt=((Hn=ae.get(N.id))!=null?Hn:"")+ce;N.rawContent=rt,J.has(N.id)||J.set(N.id,this.createStreamParser());let Ue=J.get(N.id),$e=rt.trim().startsWith("{")||rt.trim().startsWith("[");if($e&&ae.set(N.id,rt),Ue.__isPlainTextParser===!0){N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N);continue}let qt=Ue.processChunk(rt);if(qt instanceof Promise)qt.then(ft=>{var zt;let vt=typeof ft=="string"?ft:(zt=ft==null?void 0:ft.text)!=null?zt:null;if(vt!==null&&vt.trim()!==""){let Ct=h;Ct&&Ct.id===N.id&&(Ct.content=vt,u(Ct))}else if(!$e&&!rt.trim().startsWith("<")){let Ct=h;Ct&&Ct.id===N.id&&(Ct.content+=ce,ae.delete(Ct.id),J.delete(Ct.id),Ct.rawContent=void 0,u(Ct))}}).catch(()=>{N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N)});else{let ft=typeof qt=="string"?qt:(un=qt==null?void 0:qt.text)!=null?un:null;ft!==null&&ft.trim()!==""?(N.content=ft,u(N)):!$e&&!rt.trim().startsWith("<")&&(N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N))}}if(v.isComplete){let Te=(vn=(lr=v.result)==null?void 0:lr.response)!=null?vn:N.content;if(Te){let rt=ae.get(N.id),Ue=rt!=null?rt:Se(Te);N.rawContent=Ue;let $e=J.get(N.id),Ht=null,qt=!1;if($e&&(Ht=$e.getExtractedText(),Ht===null&&(Ht=Qo(Ue)),Ht===null)){let ft=$e.processChunk(Ue);ft instanceof Promise?(qt=!0,ft.then(vt=>{var Ct;let zt=typeof vt=="string"?vt:(Ct=vt==null?void 0:vt.text)!=null?Ct:null;if(zt!==null){let Ze=h;Ze&&Ze.id===N.id&&(Ze.content=zt,Ze.streaming=!1,J.delete(Ze.id),ae.delete(Ze.id),u(Ze))}})):Ht=typeof ft=="string"?ft:(bt=ft==null?void 0:ft.text)!=null?bt:null}if(!qt){Ht!==null&&Ht.trim()!==""?N.content=Ht:ae.has(N.id)||(N.content=Se(Te));let ft=J.get(N.id);if(ft){let vt=(an=ft.close)==null?void 0:an.call(ft);vt instanceof Promise&&vt.catch(()=>{}),J.delete(N.id)}ae.delete(N.id),N.streaming=!1,u(N)}}}}else if(_e==="step_complete"){let D=v.stepType,A=v.executionType;if(D==="tool"||A==="context")continue;let N=(Mn=v.result)==null?void 0:Mn.response,ce=R();if(N!=null){let Te=J.get(ce.id),rt=!1,Ue=!1;if(Te){let $e=Te.getExtractedText(),Ht=ae.get(ce.id),qt=Ht!=null?Ht:Se(N);if(ce.rawContent=qt,$e!==null&&$e.trim()!=="")ce.content=$e,rt=!0;else{let ft=Qo(qt);if(ft!==null)ce.content=ft,rt=!0;else{let vt=Te.processChunk(qt);if(vt instanceof Promise)Ue=!0,vt.then(zt=>{var Ze;let Ct=typeof zt=="string"?zt:(Ze=zt==null?void 0:zt.text)!=null?Ze:null;if(Ct!==null&&Ct.trim()!==""){let Ln=h;Ln&&Ln.id===ce.id&&(Ln.content=Ct,Ln.streaming=!1,J.delete(Ln.id),ae.delete(Ln.id),u(Ln))}else{let Ln=Te.getExtractedText(),Bt=h;Bt&&Bt.id===ce.id&&(Ln!==null&&Ln.trim()!==""?Bt.content=Ln:ae.has(Bt.id)||(Bt.content=Se(N)),Bt.streaming=!1,J.delete(Bt.id),ae.delete(Bt.id),u(Bt))}});else{let zt=typeof vt=="string"?vt:(cr=vt==null?void 0:vt.text)!=null?cr:null;if(zt!==null&&zt.trim()!=="")ce.content=zt,rt=!0;else{let Ct=Te.getExtractedText();Ct!==null&&Ct.trim()!==""&&(ce.content=Ct,rt=!0)}}}}}if(!Ue){if(!ce.rawContent){let $e=ae.get(ce.id);ce.rawContent=$e!=null?$e:Se(N)}if(!rt&&!ae.has(ce.id)&&(ce.content=Se(N)),Te){let $e=(Xn=Te.close)==null?void 0:Xn.call(Te);$e instanceof Promise&&$e.catch(()=>{})}J.delete(ce.id),ae.delete(ce.id),ce.streaming=!1,u(ce)}}else J.delete(ce.id),ae.delete(ce.id),ce.streaming=!1,u(ce)}else if(_e==="flow_complete"){let D=(dr=v.result)==null?void 0:dr.response;if(D!=null){let A=R(),N=ae.get(A.id),ce=N!=null?N:Se(D);A.rawContent=ce;let Te=Se(D),rt=J.get(A.id);if(rt){let Ht=Qo(ce);if(Ht!==null)Te=Ht;else{let qt=rt.processChunk(ce);qt instanceof Promise&&qt.then(vt=>{var Ct;let zt=typeof vt=="string"?vt:(Ct=vt==null?void 0:vt.text)!=null?Ct:null;if(zt!==null){let Ze=h;Ze&&Ze.id===A.id&&(Ze.content=zt,Ze.streaming=!1,u(Ze))}});let ft=rt.getExtractedText();ft!==null&&(Te=ft)}}J.delete(A.id),ae.delete(A.id);let Ue=Te!==A.content,$e=A.streaming!==!1;Ue&&(A.content=Te),A.streaming=!1,(Ue||$e)&&u(A)}else if(h!==null){let A=h;J.delete(A.id),ae.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}t({type:"status",status:"idle"})}else if(_e==="agent_start")ge={executionId:v.executionId,agentId:(Vn=v.agentId)!=null?Vn:"virtual",agentName:(Cn=v.agentName)!=null?Cn:"",status:"running",currentIteration:0,maxTurns:(qn=v.maxTurns)!=null?qn:1,startedAt:fe(v.startedAt)};else if(_e==="agent_iteration_start"){if(ge&&(ge.currentIteration=v.iteration),Le==="separate"&&v.iteration>1){let D=h;D&&(D.streaming=!1,u(D),De.set(v.iteration-1,D),h=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(v.contentType==="text"){let D=R();D.content+=(xt=v.delta)!=null?xt:"",D.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId,agentName:ge==null?void 0:ge.agentName},u(D)}else if(v.contentType==="thinking"){let D=(Wt=v.turnId)!=null?Wt:`agent-think-${v.iteration}`,A=ue(D);A.reasoning=(Rt=A.reasoning)!=null?Rt:{id:D,status:"streaming",chunks:[]},A.reasoning.chunks.push((wn=v.delta)!=null?wn:""),A.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId},u(A)}else if(v.contentType==="tool_input"){let D=(pr=v.toolCallId)!=null?pr:S.lastId;if(D){let A=b.get(D);A!=null&&A.toolCall&&(A.toolCall.chunks=(Bn=A.toolCall.chunks)!=null?Bn:[],A.toolCall.chunks.push((Sn=v.delta)!=null?Sn:""),u(A))}}}else if(_e==="agent_turn_complete"){let D=v.turnId;if(D){let A=M.get(D);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=fe(v.completedAt);let N=(H=A.reasoning.startedAt)!=null?H:Date.now();A.reasoning.durationMs=Math.max(0,((Dn=A.reasoning.completedAt)!=null?Dn:Date.now())-N),A.streaming=!1,u(A)}}}else if(_e==="agent_tool_start"){let D=(Fn=v.toolCallId)!=null?Fn:`agent-tool-${c()}`;se(k(v),D);let A=de(D),N=(ur=A.toolCall)!=null?ur:{id:D,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};N.name=(An=(gn=v.toolName)!=null?gn:v.name)!=null?An:N.name,N.status="running",v.parameters!==void 0&&(N.args=v.parameters),N.startedAt=fe((ee=v.startedAt)!=null?ee:v.timestamp),A.toolCall=N,A.streaming=!0,A.agentMetadata={executionId:v.executionId,iteration:v.iteration},u(A)}else if(_e==="agent_tool_delta"){let D=(Nn=v.toolCallId)!=null?Nn:S.lastId;if(D){let A=(zr=b.get(D))!=null?zr:de(D);A.toolCall&&(A.toolCall.chunks=(uo=A.toolCall.chunks)!=null?uo:[],A.toolCall.chunks.push((Vr=v.delta)!=null?Vr:""),A.toolCall.status="running",A.streaming=!0,u(A))}}else if(_e==="agent_tool_complete"){let D=(Ye=v.toolCallId)!=null?Ye:S.lastId;if(D){let A=(go=b.get(D))!=null?go:de(D);if(A.toolCall){A.toolCall.status="complete",v.result!==void 0&&(A.toolCall.result=v.result),typeof v.executionTime=="number"&&(A.toolCall.durationMs=v.executionTime),A.toolCall.completedAt=fe((kn=v.completedAt)!=null?kn:v.timestamp),A.streaming=!1,u(A);let N=k(v);N&&S.byCall.delete(N)}}}else if(_e!=="agent_iteration_complete"){if(_e==="agent_reflection"||_e==="agent_reflect"){let D=`agent-reflection-${v.executionId}-${v.iteration}`,A={id:D,role:"assistant",content:(mn=v.reflection)!=null?mn:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:D,status:"complete",chunks:[(Vo=v.reflection)!=null?Vo:""]},agentMetadata:{executionId:v.executionId,iteration:v.iteration}};u(A)}else if(_e==="agent_complete"){ge&&(ge.status=v.success?"complete":"error",ge.completedAt=fe(v.completedAt),ge.stopReason=v.stopReason);let D=h;D&&(D.streaming=!1,u(D)),t({type:"status",status:"idle"})}else if(_e==="agent_error"){let D=typeof v.error=="string"?v.error:(mo=(qo=v.error)==null?void 0:qo.message)!=null?mo:"Agent execution error";v.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",D):t({type:"error",error:new Error(D)})}else if(_e!=="agent_ping")if(_e==="agent_approval_start"){let D=(Gn=v.approvalId)!=null?Gn:`approval-${c()}`,A={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:(Uo=ge==null?void 0:ge.agentId)!=null?Uo:"virtual",executionId:(Ur=(qr=v.executionId)!=null?qr:ge==null?void 0:ge.executionId)!=null?Ur:"",toolName:(Zn=v.toolName)!=null?Zn:"",toolType:v.toolType,description:(gr=v.description)!=null?gr:`Execute ${(fo=v.toolName)!=null?fo:"tool"}`,parameters:v.parameters}};u(A)}else if(_e==="step_await"&&v.awaitReason==="approval_required"){let D=(mr=v.approvalId)!=null?mr:`approval-${c()}`,A={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:(Jo=ge==null?void 0:ge.agentId)!=null?Jo:"virtual",executionId:(Ns=(Yo=v.executionId)!=null?Yo:ge==null?void 0:ge.executionId)!=null?Ns:"",toolName:(Mr=v.toolName)!=null?Mr:"",toolType:v.toolType,description:(kt=v.description)!=null?kt:`Execute ${(kr=v.toolName)!=null?kr:"tool"}`,parameters:v.parameters}};u(A)}else if(_e==="agent_approval_complete"){let D=v.approvalId;if(D){let N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:(Jr=v.decision)!=null?Jr:"approved",agentId:(Yr=ge==null?void 0:ge.agentId)!=null?Yr:"virtual",executionId:(yo=(ho=v.executionId)!=null?ho:ge==null?void 0:ge.executionId)!=null?yo:"",toolName:(bo=v.toolName)!=null?bo:"",description:(xo=v.description)!=null?xo:"",resolvedAt:Date.now()}};u(N)}}else if(_e==="artifact_start"||_e==="artifact_delta"||_e==="artifact_update"||_e==="artifact_complete"){if(_e==="artifact_start"){let D=v.artifactType,A=String(v.id),N=typeof v.title=="string"?v.title:void 0;if(t({type:"artifact_start",id:A,artifactType:D,title:N,component:typeof v.component=="string"?v.component:void 0}),ne.set(A,{markdown:"",title:N}),!Ae.has(A)){Ae.add(A);let ce={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:N,artifactType:D,status:"streaming"}})};te.set(A,ce),u(ce)}}else if(_e==="artifact_delta"){let D=String(v.id),A=typeof v.delta=="string"?v.delta:String((ln=v.delta)!=null?ln:"");t({type:"artifact_delta",id:D,artDelta:A});let N=ne.get(D);N&&(N.markdown+=A)}else if(_e==="artifact_update"){let D=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};t({type:"artifact_update",id:String(v.id),props:D,component:typeof v.component=="string"?v.component:void 0})}else if(_e==="artifact_complete"){let D=String(v.id);t({type:"artifact_complete",id:D});let A=te.get(D);if(A){A.streaming=!1;try{let N=JSON.parse((En=A.rawContent)!=null?En:"{}");if(N.props){N.props.status="complete";let ce=ne.get(D);ce!=null&&ce.markdown&&(N.props.markdown=ce.markdown)}A.rawContent=JSON.stringify(N)}catch{}ne.delete(D),u(A),te.delete(D)}}}else if(_e==="transcript_insert"){let D=v.message;if(!D||typeof D!="object")continue;let A=String((Qn=D.id)!=null?Qn:`msg-${c()}`),N=D.role,Te={id:A,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof D.content=="string"?D.content:"",rawContent:typeof D.rawContent=="string"?D.rawContent:void 0,createdAt:typeof D.createdAt=="string"?D.createdAt:new Date().toISOString(),streaming:D.streaming===!0,...typeof D.variant=="string"?{variant:D.variant}:{},sequence:c()};if(u(Te),Te.rawContent)try{let rt=JSON.parse(Te.rawContent),Ue=(Oe=rt==null?void 0:rt.props)==null?void 0:Oe.artifactId;typeof Ue=="string"&&Ae.add(Ue)}catch{}h=null,m.current=null,J.delete(A),ae.delete(A)}else _e==="error"&&v.error&&t({type:"error",error:v.error instanceof Error?v.error:new Error(String(v.error))})}}}}}};function fc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function eo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Hr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var os="[Image]";function hc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function yc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function bc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function xc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function ss(e){return{type:"text",text:e}}function vc(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Cc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function wc(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var Sc=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],dp=["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"],rr=[...Sc,...dp];function pp(e){return Sc.includes(e)||e.startsWith("image/")}function as(e){return pp(e.type)}async function Ac(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;as(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Ec(e,r=rr,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function up(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Tc(e,r){let t=up(r).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var is=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,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 n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let 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 r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var ls=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="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 To=class{constructor(r){this.config=r;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new ls;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.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 c=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((h,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,M=x=>{C||(C=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>M("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(b),h())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let S=x.code!==1006?` (code ${x.code})`:"";M("WebSocket connection failed"+S+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new is(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(s=(n=this.config)==null?void 0:n.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=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(h=>h("processing")),this.processingStartCallbacks.forEach(h=>h());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),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(c=>c("idle")))},await d.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Br=class{constructor(r={}){this.config=r;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(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(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Dr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new To(e.runtype);case"browser":if(!Br.isSupported())throw new Error("Browser speech recognition not supported");return new Br(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function cs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Dr({type:"runtype",runtype:e.runtype});if(Br.isSupported())return Dr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Mo(e){try{return cs(e),!0}catch{return!1}}var to=class e{constructor(r={},t){this.config=r;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Rr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Mo((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Dr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,u,h,m,C,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=c.transcript)!=null&&u.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((h=c.text)!=null&&h.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let b=(M=this.pendingVoiceAssistantMessageId)!=null?M:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;b&&this.ttsSpokenMessageIds.add(b)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,u;this.voiceStatus=c,this.voiceActive=c==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,d,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Rr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p}=r,h={id:a!=null?a:t==="user"?eo():t==="assistant"?Hr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(h),h}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1}=n,m={id:d!=null?d:s==="user"?eo():s==="assistant"?Hr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(m)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,u,h,m;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=eo(),o=Hr(),a={id:s,role:"user",content:n||os,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(C){let M=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!M){let b={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(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(C instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,C):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(C))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Hr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):u=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),u){let h=null;if(u instanceof Response){if(!u.ok){let m=await u.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${u.status}`)}h=u.body}else u instanceof ReadableStream&&(h=u);h?await this.connectStream(h):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(u){(p=(c=this.callbacks).onError)==null||p.call(c,u instanceof Error?u:new Error(String(u)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var d,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var f=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Un=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var gp=oc(require("lucide"),1),pe=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=gp[s];return o?mp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function mp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}}}),s}var ds={allowedTypes:rr,maxFileSize:10*1024*1024,maxFiles:4};function fp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function hp(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Fr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:ds.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:ds.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:ds.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:ds.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,d;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Ec(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,u);continue}try{let u=await Ac(c),h=as(c)?URL.createObjectURL(c):null,m={id:fp(),file:c,previewUrl:h,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(d=>d.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=as(r.file),n=f("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=f("img");a.src=r.previewUrl,a.alt=r.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=f("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=hp(r.file.type),d=pe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=f("span");c.textContent=Tc(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.appendChild(a)}let s=f("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=pe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var zs={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"}},Vs={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"}},qs={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:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ko(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?ko(e,n):n}function ps(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ko(e,a);d!==void 0&&(r[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"),r}function Us(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function Mc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=Mc(o,s):t[n]=s}return t}function yp(e,r){return r?Mc(e,r):e}function no(e,r={}){var s,o,a,i,d,c,p,u,h,m,C,M,b;let t={palette:zs,semantic:Vs,components:qs},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(h=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:yp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=Us(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(S=>S.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function us(e){var C,M,b,x,S,F,w,k,R,T,Y,ue,se,$,te,Ae,ne,Ce,Me,de,fe,Se,J,ae,ge,De,Le,Ie,Re,ot,Et,j,U,re,_,z,Q,lt,K,X,St,st,Pt,Yt,Be,ie,ke,Tt,Mt,Qe,et,en,Zt,tn,O,Ee,le,dt,He,G,he,Pe,mt,Nt,at,Ot,pt,Je,ut,Ne,$t,_n,Yn,Rn,Xe,Er,jn,Tr,zn,jr,ir,Kn,tt,xn,Hn,un,lr,vn,bt,an,Mn,cr,Xn,dr,Vn,Cn,qn,xt,Wt,Rt,wn,pr,Bn,Sn,H,Dn,Fn,ur,gn,An;let r=ps(e),t={};for(let[ee,Nn]of Object.entries(r)){let zr=ee.replace(/\./g,"-");t[`--persona-${zr}`]=Nn.value}t["--persona-primary"]=(C=t["--persona-semantic-colors-primary"])!=null?C:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(x=t["--persona-semantic-colors-surface"])!=null?x:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(S=t["--persona-semantic-colors-background"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(F=t["--persona-semantic-colors-container"])!=null?F:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(k=t["--persona-semantic-colors-text-muted"])!=null?k:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(R=t["--persona-semantic-colors-text-inverse"])!=null?R:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(T=t["--persona-semantic-colors-border"])!=null?T:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ue=t["--persona-components-voice-recording-indicator"])!=null?ue:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(se=t["--persona-components-voice-recording-background"])!=null?se:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=($=t["--persona-components-voice-processing-icon"])!=null?$:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ae=t["--persona-components-approval-requested-background"])!=null?Ae:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ne=t["--persona-components-approval-requested-border"])!=null?ne:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ce=t["--persona-components-approval-requested-text"])!=null?Ce:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(Me=t["--persona-components-approval-approve-background"])!=null?Me:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(de=t["--persona-components-approval-deny-background"])!=null?de:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(fe=t["--persona-components-attachment-image-background"])!=null?fe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Se=t["--persona-components-attachment-image-border"])!=null?Se:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(J=t["--persona-semantic-typography-fontFamily"])!=null?J:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ae=t["--persona-semantic-typography-fontSize"])!=null?ae:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ge=t["--persona-semantic-typography-fontWeight"])!=null?ge:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(De=t["--persona-semantic-typography-lineHeight"])!=null?De:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(Le=t["--persona-palette-radius-sm"])!=null?Le:"0.125rem",t["--persona-radius-md"]=(Ie=t["--persona-palette-radius-md"])!=null?Ie:"0.375rem",t["--persona-radius-lg"]=(Re=t["--persona-palette-radius-lg"])!=null?Re:"0.5rem",t["--persona-radius-xl"]=(ot=t["--persona-palette-radius-xl"])!=null?ot:"0.75rem",t["--persona-radius-full"]=(Et=t["--persona-palette-radius-full"])!=null?Et:"9999px",t["--persona-launcher-radius"]=(U=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?U:"9999px",t["--persona-launcher-bg"]=(re=t["--persona-components-launcher-background"])!=null?re:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(z=t["--persona-components-launcher-border"])!=null?z:t["--persona-border"],t["--persona-button-primary-bg"]=(Q=t["--persona-components-button-primary-background"])!=null?Q:t["--persona-primary"],t["--persona-button-primary-fg"]=(lt=t["--persona-components-button-primary-foreground"])!=null?lt:t["--persona-text-inverse"],t["--persona-button-radius"]=(X=(K=t["--persona-components-button-primary-borderRadius"])!=null?K:t["--persona-palette-radius-full"])!=null?X:"9999px",t["--persona-panel-radius"]=(st=(St=t["--persona-components-panel-borderRadius"])!=null?St:t["--persona-radius-xl"])!=null?st:"0.75rem",t["--persona-panel-border"]=(Pt=t["--persona-components-panel-border"])!=null?Pt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Be=(Yt=t["--persona-components-panel-shadow"])!=null?Yt:t["--persona-palette-shadows-xl"])!=null?Be:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ke=(ie=t["--persona-components-input-borderRadius"])!=null?ie:t["--persona-radius-lg"])!=null?ke:"0.5rem",t["--persona-message-user-radius"]=(Mt=(Tt=t["--persona-components-message-user-borderRadius"])!=null?Tt:t["--persona-radius-lg"])!=null?Mt:"0.5rem",t["--persona-message-assistant-radius"]=(et=(Qe=t["--persona-components-message-assistant-borderRadius"])!=null?Qe:t["--persona-radius-lg"])!=null?et:"0.5rem",t["--persona-header-bg"]=(en=t["--persona-components-header-background"])!=null?en:t["--persona-surface"],t["--persona-header-border"]=(Zt=t["--persona-components-header-border"])!=null?Zt:t["--persona-divider"],t["--persona-header-icon-bg"]=(tn=t["--persona-components-header-iconBackground"])!=null?tn:t["--persona-primary"],t["--persona-header-icon-fg"]=(O=t["--persona-components-header-iconForeground"])!=null?O:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ee=t["--persona-components-header-titleForeground"])!=null?Ee:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(le=t["--persona-components-header-subtitleForeground"])!=null?le:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(dt=t["--persona-components-header-actionIconForeground"])!=null?dt:t["--persona-muted"];let n=(He=e.components)==null?void 0:He.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(G=t["--persona-components-input-background"])!=null?G:t["--persona-surface"],t["--persona-input-placeholder"]=(he=t["--persona-components-input-placeholder"])!=null?he:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Pe=t["--persona-components-message-user-background"])!=null?Pe:t["--persona-accent"],t["--persona-message-user-text"]=(mt=t["--persona-components-message-user-text"])!=null?mt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Nt=t["--persona-components-message-user-shadow"])!=null?Nt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(at=t["--persona-components-message-assistant-background"])!=null?at:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ot=t["--persona-components-message-assistant-text"])!=null?Ot:t["--persona-text"],t["--persona-message-assistant-border"]=(pt=t["--persona-components-message-assistant-border"])!=null?pt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Je=t["--persona-components-message-assistant-shadow"])!=null?Je:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Ne=(ut=t["--persona-components-scrollToBottom-background"])!=null?ut:t["--persona-button-primary-bg"])!=null?Ne:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(_n=($t=t["--persona-components-scrollToBottom-foreground"])!=null?$t:t["--persona-button-primary-fg"])!=null?_n:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Yn=t["--persona-components-scrollToBottom-border"])!=null?Yn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Rn=t["--persona-components-scrollToBottom-size"])!=null?Rn:"40px",t["--persona-scroll-to-bottom-radius"]=(jn=(Er=(Xe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Xe:t["--persona-button-radius"])!=null?Er:t["--persona-radius-full"])!=null?jn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(zn=(Tr=t["--persona-components-scrollToBottom-shadow"])!=null?Tr:t["--persona-palette-shadows-sm"])!=null?zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(jr=t["--persona-components-scrollToBottom-padding"])!=null?jr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(ir=t["--persona-components-scrollToBottom-gap"])!=null?ir:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(tt=(Kn=t["--persona-components-scrollToBottom-fontSize"])!=null?Kn:t["--persona-palette-typography-fontSize-sm"])!=null?tt:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(xn=t["--persona-components-scrollToBottom-iconSize"])!=null?xn:"14px",t["--persona-tool-bubble-shadow"]=(Hn=t["--persona-components-toolBubble-shadow"])!=null?Hn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(un=t["--persona-components-reasoningBubble-shadow"])!=null?un:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(lr=t["--persona-components-composer-shadow"])!=null?lr:"none",t["--persona-md-inline-code-bg"]=(vn=t["--persona-components-markdown-inlineCode-background"])!=null?vn:t["--persona-container"],t["--persona-md-inline-code-color"]=(bt=t["--persona-components-markdown-inlineCode-foreground"])!=null?bt:t["--persona-text"],t["--persona-md-link-color"]=(Mn=(an=t["--persona-components-markdown-link-foreground"])!=null?an:t["--persona-accent"])!=null?Mn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d),t["--persona-md-code-block-bg"]=(cr=t["--persona-components-markdown-codeBlock-background"])!=null?cr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Xn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Xn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(dr=t["--persona-components-markdown-codeBlock-textColor"])!=null?dr:"inherit",t["--persona-md-table-header-bg"]=(Vn=t["--persona-components-markdown-table-headerBackground"])!=null?Vn:t["--persona-container"],t["--persona-md-table-border-color"]=(Cn=t["--persona-components-markdown-table-borderColor"])!=null?Cn:t["--persona-border"],t["--persona-md-hr-color"]=(qn=t["--persona-components-markdown-hr-color"])!=null?qn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(xt=t["--persona-components-markdown-blockquote-borderColor"])!=null?xt:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Wt=t["--persona-components-markdown-blockquote-background"])!=null?Wt:"transparent",t["--persona-md-blockquote-text-color"]=(Rt=t["--persona-components-markdown-blockquote-textColor"])!=null?Rt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(wn=t["--persona-components-collapsibleWidget-container"])!=null?wn:t["--persona-surface"],t["--cw-surface"]=(pr=t["--persona-components-collapsibleWidget-surface"])!=null?pr:t["--persona-surface"],t["--cw-border"]=(Bn=t["--persona-components-collapsibleWidget-border"])!=null?Bn:t["--persona-border"],t["--persona-message-border"]=(Sn=t["--persona-components-message-border"])!=null?Sn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let u=c==null?void 0:c.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let h=c==null?void 0:c.toggleGroup;h&&(h.gap&&(t["--persona-toggle-group-gap"]=h.gap),h.borderRadius&&(t["--persona-toggle-group-radius"]=h.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let ee=m.toolbar;ee.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ee.iconHoverColor),ee.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ee.iconHoverBackground),ee.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ee.iconPadding),ee.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ee.iconBorderRadius),ee.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ee.iconBorder),ee.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ee.toggleGroupGap),ee.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ee.toggleBorderRadius),ee.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ee.copyBackground),ee.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ee.copyBorder),ee.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ee.copyColor),ee.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ee.copyBorderRadius),ee.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ee.copyPadding),ee.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ee.copyMenuBackground,t["--persona-dropdown-bg"]=(H=t["--persona-dropdown-bg"])!=null?H:ee.copyMenuBackground),ee.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ee.copyMenuBorder,t["--persona-dropdown-border"]=(Dn=t["--persona-dropdown-border"])!=null?Dn:ee.copyMenuBorder),ee.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ee.copyMenuShadow,t["--persona-dropdown-shadow"]=(Fn=t["--persona-dropdown-shadow"])!=null?Fn:ee.copyMenuShadow),ee.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ee.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(ur=t["--persona-dropdown-radius"])!=null?ur:ee.copyMenuBorderRadius),ee.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ee.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:ee.copyMenuItemHoverBackground),ee.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ee.iconBackground),ee.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ee.toolbarBorder)}if(m!=null&&m.tab){let ee=m.tab;ee.background&&(t["--persona-artifact-tab-bg"]=ee.background),ee.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ee.activeBackground),ee.activeBorder&&(t["--persona-artifact-tab-active-border"]=ee.activeBorder),ee.borderRadius&&(t["--persona-artifact-tab-radius"]=ee.borderRadius),ee.textColor&&(t["--persona-artifact-tab-color"]=ee.textColor),ee.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ee.hoverBackground),ee.listBackground&&(t["--persona-artifact-tab-list-bg"]=ee.listBackground),ee.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ee.listBorderColor),ee.listPadding&&(t["--persona-artifact-tab-list-padding"]=ee.listPadding)}if(m!=null&&m.pane){let ee=m.pane;if(ee.toolbarBackground){let Nn=(An=ko(e,ee.toolbarBackground))!=null?An:ee.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Nn}}return t}var kc={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 Lc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Lo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Lc(o)&&Lc(s)?t[n]=Lo(o,s):t[n]=s}return t}var bp={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"}}},Ic=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Io=()=>{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"},xp=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Io()},Js=e=>xp(e),vp=e=>no(e),Cp=e=>{var t;let r=no(void 0,{validate:!1});return no({...e,palette:{...r.palette,colors:{...bp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Po=e=>{let r=Js(e),t=Ic(e==null?void 0:e.theme),n=Ic(e==null?void 0:e.darkTheme);return r==="dark"?Cp(Lo(t!=null?t:{},n!=null?n:{})):vp(t)},wp=e=>us(e),vr=(e,r)=>{var o;let t=Po(r),n=wp(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},gs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Io())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Io());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var Pc=require("idiomorph"),Wc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Pc.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function Rc(e,r){var t,n,s,o,a,i,d,c,p,u,h,m,C,M,b,x,S,F;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(h=(u=e.approval)==null?void 0:u.status)!=null?h:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(b=(M=e.reasoning)==null?void 0:M.chunks)==null?void 0:b.length)!=null?x:0,(F=(S=e.contentParts)==null?void 0:S.length)!=null?F:0,r].join("\0")}function Hc(){return new Map}function Bc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Dc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Fc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function ms(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Wo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ro(e,r){return Wo(e)-e.scrollTop<=r}function fs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function hs(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var sn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,Cr=yn+1;function Ys(e,r=yn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Ho=0,wr=null;function Ks(e=document){var t;if(Ho++,Ho===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;wr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Ho=Math.max(0,Ho-1),Ho===0&&wr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=wr.originalOverflow,s.style.position=wr.originalPosition,s.style.top=wr.originalTop,s.style.width=wr.originalWidth,o.scrollTo(0,wr.scrollY),wr=null}}}var ys={side:"right",width:"420px",animate:!0,reveal:"resize"},Jt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Pn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:ys.side,width:(s=r==null?void 0:r.width)!=null?s:ys.width,animate:(o=r==null?void 0:r.animate)!=null?o:ys.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:ys.reveal}};var $n={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Bo=(e,r)=>{let t=f("button");t.type="button",t.innerHTML=`
|
|
7
|
+
`),Kt="message",Lt="";for(let D of jt)D.startsWith("event:")?Kt=D.replace("event:","").trim():D.startsWith("data:")&&(Lt+=D.replace("data:","").trim());if(!Lt)continue;let v;try{v=JSON.parse(Lt)}catch(D){t({type:"error",error:D instanceof Error?D:new Error("Failed to parse chat stream payload")});continue}let _e=Kt!=="message"?Kt:(ot=v.type)!=null?ot:"message";if((Et=this.onSSEEvent)==null||Et.call(this,_e,v),this.parseSSEEvent){m.current=h;let D=await this.handleCustomSSEEvent(v,t,m,u,c,C);if(m.current&&m.current!==h&&(h=m.current),D)continue}if(_e==="reason_start"){let D=(j=Y(v,!0))!=null?j:`reason-${c()}`,A=ue(D);A.reasoning=(U=A.reasoning)!=null?U:{id:D,status:"streaming",chunks:[]},A.reasoning.startedAt=(_=A.reasoning.startedAt)!=null?_:fe((re=v.startedAt)!=null?re:v.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",u(A)}else if(_e==="reason_delta"||_e==="reason_chunk"){let D=(Q=(z=Y(v,!1))!=null?z:Y(v,!0))!=null?Q:`reason-${c()}`,A=ue(D);A.reasoning=(lt=A.reasoning)!=null?lt:{id:D,status:"streaming",chunks:[]},A.reasoning.startedAt=(X=A.reasoning.startedAt)!=null?X:fe((K=v.startedAt)!=null?K:v.timestamp);let N=(Pt=(st=(St=v.reasoningText)!=null?St:v.text)!=null?st:v.delta)!=null?Pt:"";if(N&&v.hidden!==!0&&A.reasoning.chunks.push(String(N)),A.reasoning.status=v.done?"complete":"streaming",v.done){A.reasoning.completedAt=fe((Yt=v.completedAt)!=null?Yt:v.timestamp);let ce=(Be=A.reasoning.startedAt)!=null?Be:Date.now();A.reasoning.durationMs=Math.max(0,((ie=A.reasoning.completedAt)!=null?ie:Date.now())-ce)}A.streaming=A.reasoning.status!=="complete",u(A)}else if(_e==="reason_complete"){let D=(Tt=(ke=Y(v,!1))!=null?ke:Y(v,!0))!=null?Tt:`reason-${c()}`,A=M.get(D);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=fe((Mt=v.completedAt)!=null?Mt:v.timestamp);let ce=(Qe=A.reasoning.startedAt)!=null?Qe:Date.now();A.reasoning.durationMs=Math.max(0,((et=A.reasoning.completedAt)!=null?et:Date.now())-ce),A.streaming=!1,u(A)}let N=w(v);N&&x.byStep.delete(N)}else if(_e==="tool_start"){let D=(en=Me(v,!0))!=null?en:`tool-${c()}`,A=(Zt=v.toolName)!=null?Zt:v.name;if(Ce(A)){$.add(D);continue}let N=de(D),ce=(tn=N.toolCall)!=null?tn:{id:D,status:"pending"};ce.name=A!=null?A:ce.name,ce.status="running",v.args!==void 0?ce.args=v.args:v.parameters!==void 0&&(ce.args=v.parameters),ce.startedAt=(Ee=ce.startedAt)!=null?Ee:fe((O=v.startedAt)!=null?O:v.timestamp),ce.completedAt=void 0,ce.durationMs=void 0,N.toolCall=ce,N.streaming=!0;let Te=v.agentContext;(Te||v.executionId)&&(N.agentMetadata={executionId:(le=Te==null?void 0:Te.executionId)!=null?le:v.executionId,iteration:(dt=Te==null?void 0:Te.iteration)!=null?dt:v.iteration}),u(N)}else if(_e==="tool_chunk"||_e==="tool_delta"){let D=(G=(He=Me(v,!1))!=null?He:Me(v,!0))!=null?G:`tool-${c()}`;if($.has(D))continue;let A=de(D),N=(he=A.toolCall)!=null?he:{id:D,status:"running"};N.startedAt=(mt=N.startedAt)!=null?mt:fe((Pe=v.startedAt)!=null?Pe:v.timestamp);let ce=(Ot=(at=(Nt=v.text)!=null?Nt:v.delta)!=null?at:v.message)!=null?Ot:"";ce&&(N.chunks=(pt=N.chunks)!=null?pt:[],N.chunks.push(String(ce))),N.status="running",A.toolCall=N,A.streaming=!0;let Te=v.agentContext;(Te||v.executionId)&&(A.agentMetadata=(Ne=A.agentMetadata)!=null?Ne:{executionId:(Je=Te==null?void 0:Te.executionId)!=null?Je:v.executionId,iteration:(ut=Te==null?void 0:Te.iteration)!=null?ut:v.iteration}),u(A)}else if(_e==="tool_complete"){let D=(_n=($t=Me(v,!1))!=null?$t:Me(v,!0))!=null?_n:`tool-${c()}`;if($.has(D)){$.delete(D);continue}let A=de(D),N=(Yn=A.toolCall)!=null?Yn:{id:D,status:"running"};N.status="complete",v.result!==void 0&&(N.result=v.result),typeof v.duration=="number"&&(N.duration=v.duration),N.completedAt=fe((Rn=v.completedAt)!=null?Rn:v.timestamp);let ce=(Xe=v.duration)!=null?Xe:v.executionTime;if(typeof ce=="number")N.durationMs=ce;else{let Ue=(Er=N.startedAt)!=null?Er:Date.now();N.durationMs=Math.max(0,((jn=N.completedAt)!=null?jn:Date.now())-Ue)}A.toolCall=N,A.streaming=!1;let Te=v.agentContext;(Te||v.executionId)&&(A.agentMetadata=(jr=A.agentMetadata)!=null?jr:{executionId:(Tr=Te==null?void 0:Te.executionId)!=null?Tr:v.executionId,iteration:(zn=Te==null?void 0:Te.iteration)!=null?zn:v.iteration}),u(A);let rt=k(v);rt&&S.byCall.delete(rt)}else if(_e==="step_chunk"||_e==="step_delta"){let D=v.stepType,A=v.executionType;if(D==="tool"||A==="context")continue;let N=R(),ce=(xn=(tt=(Kn=(ir=v.text)!=null?ir:v.delta)!=null?Kn:v.content)!=null?tt:v.chunk)!=null?xn:"";if(ce){let rt=((Hn=ae.get(N.id))!=null?Hn:"")+ce;N.rawContent=rt,J.has(N.id)||J.set(N.id,this.createStreamParser());let Ue=J.get(N.id),$e=rt.trim().startsWith("{")||rt.trim().startsWith("[");if($e&&ae.set(N.id,rt),Ue.__isPlainTextParser===!0){N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N);continue}let qt=Ue.processChunk(rt);if(qt instanceof Promise)qt.then(ft=>{var zt;let vt=typeof ft=="string"?ft:(zt=ft==null?void 0:ft.text)!=null?zt:null;if(vt!==null&&vt.trim()!==""){let Ct=h;Ct&&Ct.id===N.id&&(Ct.content=vt,u(Ct))}else if(!$e&&!rt.trim().startsWith("<")){let Ct=h;Ct&&Ct.id===N.id&&(Ct.content+=ce,ae.delete(Ct.id),J.delete(Ct.id),Ct.rawContent=void 0,u(Ct))}}).catch(()=>{N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N)});else{let ft=typeof qt=="string"?qt:(an=qt==null?void 0:qt.text)!=null?an:null;ft!==null&&ft.trim()!==""?(N.content=ft,u(N)):!$e&&!rt.trim().startsWith("<")&&(N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N))}}if(v.isComplete){let Te=(vn=(lr=v.result)==null?void 0:lr.response)!=null?vn:N.content;if(Te){let rt=ae.get(N.id),Ue=rt!=null?rt:Se(Te);N.rawContent=Ue;let $e=J.get(N.id),Ht=null,qt=!1;if($e&&(Ht=$e.getExtractedText(),Ht===null&&(Ht=Qo(Ue)),Ht===null)){let ft=$e.processChunk(Ue);ft instanceof Promise?(qt=!0,ft.then(vt=>{var Ct;let zt=typeof vt=="string"?vt:(Ct=vt==null?void 0:vt.text)!=null?Ct:null;if(zt!==null){let Ze=h;Ze&&Ze.id===N.id&&(Ze.content=zt,Ze.streaming=!1,J.delete(Ze.id),ae.delete(Ze.id),u(Ze))}})):Ht=typeof ft=="string"?ft:(bt=ft==null?void 0:ft.text)!=null?bt:null}if(!qt){Ht!==null&&Ht.trim()!==""?N.content=Ht:ae.has(N.id)||(N.content=Se(Te));let ft=J.get(N.id);if(ft){let vt=(ln=ft.close)==null?void 0:ln.call(ft);vt instanceof Promise&&vt.catch(()=>{}),J.delete(N.id)}ae.delete(N.id),N.streaming=!1,u(N)}}}}else if(_e==="step_complete"){let D=v.stepType,A=v.executionType;if(D==="tool"||A==="context")continue;let N=(Mn=v.result)==null?void 0:Mn.response,ce=R();if(N!=null){let Te=J.get(ce.id),rt=!1,Ue=!1;if(Te){let $e=Te.getExtractedText(),Ht=ae.get(ce.id),qt=Ht!=null?Ht:Se(N);if(ce.rawContent=qt,$e!==null&&$e.trim()!=="")ce.content=$e,rt=!0;else{let ft=Qo(qt);if(ft!==null)ce.content=ft,rt=!0;else{let vt=Te.processChunk(qt);if(vt instanceof Promise)Ue=!0,vt.then(zt=>{var Ze;let Ct=typeof zt=="string"?zt:(Ze=zt==null?void 0:zt.text)!=null?Ze:null;if(Ct!==null&&Ct.trim()!==""){let Ln=h;Ln&&Ln.id===ce.id&&(Ln.content=Ct,Ln.streaming=!1,J.delete(Ln.id),ae.delete(Ln.id),u(Ln))}else{let Ln=Te.getExtractedText(),Bt=h;Bt&&Bt.id===ce.id&&(Ln!==null&&Ln.trim()!==""?Bt.content=Ln:ae.has(Bt.id)||(Bt.content=Se(N)),Bt.streaming=!1,J.delete(Bt.id),ae.delete(Bt.id),u(Bt))}});else{let zt=typeof vt=="string"?vt:(cr=vt==null?void 0:vt.text)!=null?cr:null;if(zt!==null&&zt.trim()!=="")ce.content=zt,rt=!0;else{let Ct=Te.getExtractedText();Ct!==null&&Ct.trim()!==""&&(ce.content=Ct,rt=!0)}}}}}if(!Ue){if(!ce.rawContent){let $e=ae.get(ce.id);ce.rawContent=$e!=null?$e:Se(N)}if(!rt&&!ae.has(ce.id)&&(ce.content=Se(N)),Te){let $e=(Xn=Te.close)==null?void 0:Xn.call(Te);$e instanceof Promise&&$e.catch(()=>{})}J.delete(ce.id),ae.delete(ce.id),ce.streaming=!1,u(ce)}}else J.delete(ce.id),ae.delete(ce.id),ce.streaming=!1,u(ce)}else if(_e==="flow_complete"){let D=(dr=v.result)==null?void 0:dr.response;if(D!=null){let A=R(),N=ae.get(A.id),ce=N!=null?N:Se(D);A.rawContent=ce;let Te=Se(D),rt=J.get(A.id);if(rt){let Ht=Qo(ce);if(Ht!==null)Te=Ht;else{let qt=rt.processChunk(ce);qt instanceof Promise&&qt.then(vt=>{var Ct;let zt=typeof vt=="string"?vt:(Ct=vt==null?void 0:vt.text)!=null?Ct:null;if(zt!==null){let Ze=h;Ze&&Ze.id===A.id&&(Ze.content=zt,Ze.streaming=!1,u(Ze))}});let ft=rt.getExtractedText();ft!==null&&(Te=ft)}}J.delete(A.id),ae.delete(A.id);let Ue=Te!==A.content,$e=A.streaming!==!1;Ue&&(A.content=Te),A.streaming=!1,(Ue||$e)&&u(A)}else if(h!==null){let A=h;J.delete(A.id),ae.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}t({type:"status",status:"idle"})}else if(_e==="agent_start")ge={executionId:v.executionId,agentId:(Vn=v.agentId)!=null?Vn:"virtual",agentName:(Cn=v.agentName)!=null?Cn:"",status:"running",currentIteration:0,maxTurns:(qn=v.maxTurns)!=null?qn:1,startedAt:fe(v.startedAt)};else if(_e==="agent_iteration_start"){if(ge&&(ge.currentIteration=v.iteration),Le==="separate"&&v.iteration>1){let D=h;D&&(D.streaming=!1,u(D),De.set(v.iteration-1,D),h=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(v.contentType==="text"){let D=R();D.content+=(xt=v.delta)!=null?xt:"",D.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId,agentName:ge==null?void 0:ge.agentName},u(D)}else if(v.contentType==="thinking"){let D=(Wt=v.turnId)!=null?Wt:`agent-think-${v.iteration}`,A=ue(D);A.reasoning=(Rt=A.reasoning)!=null?Rt:{id:D,status:"streaming",chunks:[]},A.reasoning.chunks.push((wn=v.delta)!=null?wn:""),A.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId},u(A)}else if(v.contentType==="tool_input"){let D=(pr=v.toolCallId)!=null?pr:S.lastId;if(D){let A=b.get(D);A!=null&&A.toolCall&&(A.toolCall.chunks=(Bn=A.toolCall.chunks)!=null?Bn:[],A.toolCall.chunks.push((Sn=v.delta)!=null?Sn:""),u(A))}}}else if(_e==="agent_turn_complete"){let D=v.turnId;if(D){let A=M.get(D);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=fe(v.completedAt);let N=(H=A.reasoning.startedAt)!=null?H:Date.now();A.reasoning.durationMs=Math.max(0,((Dn=A.reasoning.completedAt)!=null?Dn:Date.now())-N),A.streaming=!1,u(A)}}}else if(_e==="agent_tool_start"){let D=(Fn=v.toolCallId)!=null?Fn:`agent-tool-${c()}`;se(k(v),D);let A=de(D),N=(ur=A.toolCall)!=null?ur:{id:D,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};N.name=(An=(gn=v.toolName)!=null?gn:v.name)!=null?An:N.name,N.status="running",v.parameters!==void 0&&(N.args=v.parameters),N.startedAt=fe((ee=v.startedAt)!=null?ee:v.timestamp),A.toolCall=N,A.streaming=!0,A.agentMetadata={executionId:v.executionId,iteration:v.iteration},u(A)}else if(_e==="agent_tool_delta"){let D=(Nn=v.toolCallId)!=null?Nn:S.lastId;if(D){let A=(zr=b.get(D))!=null?zr:de(D);A.toolCall&&(A.toolCall.chunks=(uo=A.toolCall.chunks)!=null?uo:[],A.toolCall.chunks.push((Vr=v.delta)!=null?Vr:""),A.toolCall.status="running",A.streaming=!0,u(A))}}else if(_e==="agent_tool_complete"){let D=(Ye=v.toolCallId)!=null?Ye:S.lastId;if(D){let A=(go=b.get(D))!=null?go:de(D);if(A.toolCall){A.toolCall.status="complete",v.result!==void 0&&(A.toolCall.result=v.result),typeof v.executionTime=="number"&&(A.toolCall.durationMs=v.executionTime),A.toolCall.completedAt=fe((kn=v.completedAt)!=null?kn:v.timestamp),A.streaming=!1,u(A);let N=k(v);N&&S.byCall.delete(N)}}}else if(_e!=="agent_iteration_complete"){if(_e==="agent_reflection"||_e==="agent_reflect"){let D=`agent-reflection-${v.executionId}-${v.iteration}`,A={id:D,role:"assistant",content:(mn=v.reflection)!=null?mn:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:D,status:"complete",chunks:[(Vo=v.reflection)!=null?Vo:""]},agentMetadata:{executionId:v.executionId,iteration:v.iteration}};u(A)}else if(_e==="agent_complete"){ge&&(ge.status=v.success?"complete":"error",ge.completedAt=fe(v.completedAt),ge.stopReason=v.stopReason);let D=h;D&&(D.streaming=!1,u(D)),t({type:"status",status:"idle"})}else if(_e==="agent_error"){let D=typeof v.error=="string"?v.error:(mo=(qo=v.error)==null?void 0:qo.message)!=null?mo:"Agent execution error";v.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",D):t({type:"error",error:new Error(D)})}else if(_e!=="agent_ping")if(_e==="agent_approval_start"){let D=(Gn=v.approvalId)!=null?Gn:`approval-${c()}`,A={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:(Uo=ge==null?void 0:ge.agentId)!=null?Uo:"virtual",executionId:(Ur=(qr=v.executionId)!=null?qr:ge==null?void 0:ge.executionId)!=null?Ur:"",toolName:(Zn=v.toolName)!=null?Zn:"",toolType:v.toolType,description:(gr=v.description)!=null?gr:`Execute ${(fo=v.toolName)!=null?fo:"tool"}`,parameters:v.parameters}};u(A)}else if(_e==="step_await"&&v.awaitReason==="approval_required"){let D=(mr=v.approvalId)!=null?mr:`approval-${c()}`,A={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:(Jo=ge==null?void 0:ge.agentId)!=null?Jo:"virtual",executionId:(Ns=(Yo=v.executionId)!=null?Yo:ge==null?void 0:ge.executionId)!=null?Ns:"",toolName:(Mr=v.toolName)!=null?Mr:"",toolType:v.toolType,description:(kt=v.description)!=null?kt:`Execute ${(kr=v.toolName)!=null?kr:"tool"}`,parameters:v.parameters}};u(A)}else if(_e==="agent_approval_complete"){let D=v.approvalId;if(D){let N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:(Jr=v.decision)!=null?Jr:"approved",agentId:(Yr=ge==null?void 0:ge.agentId)!=null?Yr:"virtual",executionId:(yo=(ho=v.executionId)!=null?ho:ge==null?void 0:ge.executionId)!=null?yo:"",toolName:(bo=v.toolName)!=null?bo:"",description:(xo=v.description)!=null?xo:"",resolvedAt:Date.now()}};u(N)}}else if(_e==="artifact_start"||_e==="artifact_delta"||_e==="artifact_update"||_e==="artifact_complete"){if(_e==="artifact_start"){let D=v.artifactType,A=String(v.id),N=typeof v.title=="string"?v.title:void 0;if(t({type:"artifact_start",id:A,artifactType:D,title:N,component:typeof v.component=="string"?v.component:void 0}),ne.set(A,{markdown:"",title:N}),!Ae.has(A)){Ae.add(A);let ce={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:N,artifactType:D,status:"streaming"}})};te.set(A,ce),u(ce)}}else if(_e==="artifact_delta"){let D=String(v.id),A=typeof v.delta=="string"?v.delta:String((cn=v.delta)!=null?cn:"");t({type:"artifact_delta",id:D,artDelta:A});let N=ne.get(D);N&&(N.markdown+=A)}else if(_e==="artifact_update"){let D=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};t({type:"artifact_update",id:String(v.id),props:D,component:typeof v.component=="string"?v.component:void 0})}else if(_e==="artifact_complete"){let D=String(v.id);t({type:"artifact_complete",id:D});let A=te.get(D);if(A){A.streaming=!1;try{let N=JSON.parse((En=A.rawContent)!=null?En:"{}");if(N.props){N.props.status="complete";let ce=ne.get(D);ce!=null&&ce.markdown&&(N.props.markdown=ce.markdown)}A.rawContent=JSON.stringify(N)}catch{}ne.delete(D),u(A),te.delete(D)}}}else if(_e==="transcript_insert"){let D=v.message;if(!D||typeof D!="object")continue;let A=String((Qn=D.id)!=null?Qn:`msg-${c()}`),N=D.role,Te={id:A,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof D.content=="string"?D.content:"",rawContent:typeof D.rawContent=="string"?D.rawContent:void 0,createdAt:typeof D.createdAt=="string"?D.createdAt:new Date().toISOString(),streaming:D.streaming===!0,...typeof D.variant=="string"?{variant:D.variant}:{},sequence:c()};if(u(Te),Te.rawContent)try{let rt=JSON.parse(Te.rawContent),Ue=(Oe=rt==null?void 0:rt.props)==null?void 0:Oe.artifactId;typeof Ue=="string"&&Ae.add(Ue)}catch{}h=null,m.current=null,J.delete(A),ae.delete(A)}else _e==="error"&&v.error&&t({type:"error",error:v.error instanceof Error?v.error:new Error(String(v.error))})}}}}}};function fc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function eo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Hr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var os="[Image]";function hc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function yc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function bc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function xc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function ss(e){return{type:"text",text:e}}function vc(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Cc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function wc(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var Sc=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],dp=["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"],rr=[...Sc,...dp];function pp(e){return Sc.includes(e)||e.startsWith("image/")}function as(e){return pp(e.type)}async function Ac(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;as(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Ec(e,r=rr,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function up(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Tc(e,r){let t=up(r).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var is=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,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 n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let 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 r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var ls=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="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 To=class{constructor(r){this.config=r;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new ls;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.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 c=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((h,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,M=x=>{C||(C=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>M("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(b),h())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let S=x.code!==1006?` (code ${x.code})`:"";M("WebSocket connection failed"+S+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new is(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(s=(n=this.config)==null?void 0:n.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=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(h=>h("processing")),this.processingStartCallbacks.forEach(h=>h());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),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(c=>c("idle")))},await d.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Br=class{constructor(r={}){this.config=r;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(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(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Dr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new To(e.runtype);case"browser":if(!Br.isSupported())throw new Error("Browser speech recognition not supported");return new Br(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function cs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Dr({type:"runtype",runtype:e.runtype});if(Br.isSupported())return Dr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Mo(e){try{return cs(e),!0}catch{return!1}}var to=class e{constructor(r={},t){this.config=r;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Rr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Mo((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Dr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,u,h,m,C,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=c.transcript)!=null&&u.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((h=c.text)!=null&&h.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let b=(M=this.pendingVoiceAssistantMessageId)!=null?M:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;b&&this.ttsSpokenMessageIds.add(b)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,u;this.voiceStatus=c,this.voiceActive=c==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,d,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Rr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p}=r,h={id:a!=null?a:t==="user"?eo():t==="assistant"?Hr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(h),h}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1}=n,m={id:d!=null?d:s==="user"?eo():s==="assistant"?Hr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(m)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,u,h,m;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=eo(),o=Hr(),a={id:s,role:"user",content:n||os,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(C){let M=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!M){let b={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(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(C instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,C):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(C))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Hr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):u=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),u){let h=null;if(u instanceof Response){if(!u.ok){let m=await u.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${u.status}`)}h=u.body}else u instanceof ReadableStream&&(h=u);h?await this.connectStream(h):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(u){(p=(c=this.callbacks).onError)==null||p.call(c,u instanceof Error?u:new Error(String(u)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var d,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var f=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Un=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var gp=oc(require("lucide"),1),pe=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=gp[s];return o?mp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function mp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}}}),s}var ds={allowedTypes:rr,maxFileSize:10*1024*1024,maxFiles:4};function fp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function hp(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Fr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:ds.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:ds.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:ds.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:ds.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,d;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Ec(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,u);continue}try{let u=await Ac(c),h=as(c)?URL.createObjectURL(c):null,m={id:fp(),file:c,previewUrl:h,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(d=>d.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=as(r.file),n=f("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=f("img");a.src=r.previewUrl,a.alt=r.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",n.appendChild(a)}else{let a=f("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=hp(r.file.type),d=pe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=f("span");c.textContent=Tc(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.appendChild(a)}let s=f("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=pe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var zs={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"}},Vs={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"}},qs={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:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ko(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?ko(e,n):n}function ps(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ko(e,a);d!==void 0&&(r[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"),r}function Us(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function Mc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=Mc(o,s):t[n]=s}return t}function yp(e,r){return r?Mc(e,r):e}function no(e,r={}){var s,o,a,i,d,c,p,u,h,m,C,M,b;let t={palette:zs,semantic:Vs,components:qs},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(h=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:yp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=Us(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(S=>S.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function us(e){var C,M,b,x,S,F,w,k,R,T,Y,ue,se,$,te,Ae,ne,Ce,Me,de,fe,Se,J,ae,ge,De,Le,Ie,Re,ot,Et,j,U,re,_,z,Q,lt,K,X,St,st,Pt,Yt,Be,ie,ke,Tt,Mt,Qe,et,en,Zt,tn,O,Ee,le,dt,He,G,he,Pe,mt,Nt,at,Ot,pt,Je,ut,Ne,$t,_n,Yn,Rn,Xe,Er,jn,Tr,zn,jr,ir,Kn,tt,xn,Hn,an,lr,vn,bt,ln,Mn,cr,Xn,dr,Vn,Cn,qn,xt,Wt,Rt,wn,pr,Bn,Sn,H,Dn,Fn,ur,gn,An;let r=ps(e),t={};for(let[ee,Nn]of Object.entries(r)){let zr=ee.replace(/\./g,"-");t[`--persona-${zr}`]=Nn.value}t["--persona-primary"]=(C=t["--persona-semantic-colors-primary"])!=null?C:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(x=t["--persona-semantic-colors-surface"])!=null?x:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(S=t["--persona-semantic-colors-background"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(F=t["--persona-semantic-colors-container"])!=null?F:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(k=t["--persona-semantic-colors-text-muted"])!=null?k:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(R=t["--persona-semantic-colors-text-inverse"])!=null?R:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(T=t["--persona-semantic-colors-border"])!=null?T:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ue=t["--persona-components-voice-recording-indicator"])!=null?ue:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(se=t["--persona-components-voice-recording-background"])!=null?se:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=($=t["--persona-components-voice-processing-icon"])!=null?$:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ae=t["--persona-components-approval-requested-background"])!=null?Ae:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ne=t["--persona-components-approval-requested-border"])!=null?ne:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ce=t["--persona-components-approval-requested-text"])!=null?Ce:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(Me=t["--persona-components-approval-approve-background"])!=null?Me:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(de=t["--persona-components-approval-deny-background"])!=null?de:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(fe=t["--persona-components-attachment-image-background"])!=null?fe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Se=t["--persona-components-attachment-image-border"])!=null?Se:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(J=t["--persona-semantic-typography-fontFamily"])!=null?J:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ae=t["--persona-semantic-typography-fontSize"])!=null?ae:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ge=t["--persona-semantic-typography-fontWeight"])!=null?ge:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(De=t["--persona-semantic-typography-lineHeight"])!=null?De:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(Le=t["--persona-palette-radius-sm"])!=null?Le:"0.125rem",t["--persona-radius-md"]=(Ie=t["--persona-palette-radius-md"])!=null?Ie:"0.375rem",t["--persona-radius-lg"]=(Re=t["--persona-palette-radius-lg"])!=null?Re:"0.5rem",t["--persona-radius-xl"]=(ot=t["--persona-palette-radius-xl"])!=null?ot:"0.75rem",t["--persona-radius-full"]=(Et=t["--persona-palette-radius-full"])!=null?Et:"9999px",t["--persona-launcher-radius"]=(U=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?U:"9999px",t["--persona-launcher-bg"]=(re=t["--persona-components-launcher-background"])!=null?re:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(z=t["--persona-components-launcher-border"])!=null?z:t["--persona-border"],t["--persona-button-primary-bg"]=(Q=t["--persona-components-button-primary-background"])!=null?Q:t["--persona-primary"],t["--persona-button-primary-fg"]=(lt=t["--persona-components-button-primary-foreground"])!=null?lt:t["--persona-text-inverse"],t["--persona-button-radius"]=(X=(K=t["--persona-components-button-primary-borderRadius"])!=null?K:t["--persona-palette-radius-full"])!=null?X:"9999px",t["--persona-panel-radius"]=(st=(St=t["--persona-components-panel-borderRadius"])!=null?St:t["--persona-radius-xl"])!=null?st:"0.75rem",t["--persona-panel-border"]=(Pt=t["--persona-components-panel-border"])!=null?Pt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Be=(Yt=t["--persona-components-panel-shadow"])!=null?Yt:t["--persona-palette-shadows-xl"])!=null?Be:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ke=(ie=t["--persona-components-input-borderRadius"])!=null?ie:t["--persona-radius-lg"])!=null?ke:"0.5rem",t["--persona-message-user-radius"]=(Mt=(Tt=t["--persona-components-message-user-borderRadius"])!=null?Tt:t["--persona-radius-lg"])!=null?Mt:"0.5rem",t["--persona-message-assistant-radius"]=(et=(Qe=t["--persona-components-message-assistant-borderRadius"])!=null?Qe:t["--persona-radius-lg"])!=null?et:"0.5rem",t["--persona-header-bg"]=(en=t["--persona-components-header-background"])!=null?en:t["--persona-surface"],t["--persona-header-border"]=(Zt=t["--persona-components-header-border"])!=null?Zt:t["--persona-divider"],t["--persona-header-icon-bg"]=(tn=t["--persona-components-header-iconBackground"])!=null?tn:t["--persona-primary"],t["--persona-header-icon-fg"]=(O=t["--persona-components-header-iconForeground"])!=null?O:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ee=t["--persona-components-header-titleForeground"])!=null?Ee:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(le=t["--persona-components-header-subtitleForeground"])!=null?le:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(dt=t["--persona-components-header-actionIconForeground"])!=null?dt:t["--persona-muted"];let n=(He=e.components)==null?void 0:He.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(G=t["--persona-components-input-background"])!=null?G:t["--persona-surface"],t["--persona-input-placeholder"]=(he=t["--persona-components-input-placeholder"])!=null?he:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Pe=t["--persona-components-message-user-background"])!=null?Pe:t["--persona-accent"],t["--persona-message-user-text"]=(mt=t["--persona-components-message-user-text"])!=null?mt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Nt=t["--persona-components-message-user-shadow"])!=null?Nt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(at=t["--persona-components-message-assistant-background"])!=null?at:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ot=t["--persona-components-message-assistant-text"])!=null?Ot:t["--persona-text"],t["--persona-message-assistant-border"]=(pt=t["--persona-components-message-assistant-border"])!=null?pt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Je=t["--persona-components-message-assistant-shadow"])!=null?Je:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Ne=(ut=t["--persona-components-scrollToBottom-background"])!=null?ut:t["--persona-button-primary-bg"])!=null?Ne:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(_n=($t=t["--persona-components-scrollToBottom-foreground"])!=null?$t:t["--persona-button-primary-fg"])!=null?_n:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Yn=t["--persona-components-scrollToBottom-border"])!=null?Yn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Rn=t["--persona-components-scrollToBottom-size"])!=null?Rn:"40px",t["--persona-scroll-to-bottom-radius"]=(jn=(Er=(Xe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Xe:t["--persona-button-radius"])!=null?Er:t["--persona-radius-full"])!=null?jn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(zn=(Tr=t["--persona-components-scrollToBottom-shadow"])!=null?Tr:t["--persona-palette-shadows-sm"])!=null?zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(jr=t["--persona-components-scrollToBottom-padding"])!=null?jr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(ir=t["--persona-components-scrollToBottom-gap"])!=null?ir:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(tt=(Kn=t["--persona-components-scrollToBottom-fontSize"])!=null?Kn:t["--persona-palette-typography-fontSize-sm"])!=null?tt:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(xn=t["--persona-components-scrollToBottom-iconSize"])!=null?xn:"14px",t["--persona-tool-bubble-shadow"]=(Hn=t["--persona-components-toolBubble-shadow"])!=null?Hn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(an=t["--persona-components-reasoningBubble-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(lr=t["--persona-components-composer-shadow"])!=null?lr:"none",t["--persona-md-inline-code-bg"]=(vn=t["--persona-components-markdown-inlineCode-background"])!=null?vn:t["--persona-container"],t["--persona-md-inline-code-color"]=(bt=t["--persona-components-markdown-inlineCode-foreground"])!=null?bt:t["--persona-text"],t["--persona-md-link-color"]=(Mn=(ln=t["--persona-components-markdown-link-foreground"])!=null?ln:t["--persona-accent"])!=null?Mn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d),t["--persona-md-code-block-bg"]=(cr=t["--persona-components-markdown-codeBlock-background"])!=null?cr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Xn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Xn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(dr=t["--persona-components-markdown-codeBlock-textColor"])!=null?dr:"inherit",t["--persona-md-table-header-bg"]=(Vn=t["--persona-components-markdown-table-headerBackground"])!=null?Vn:t["--persona-container"],t["--persona-md-table-border-color"]=(Cn=t["--persona-components-markdown-table-borderColor"])!=null?Cn:t["--persona-border"],t["--persona-md-hr-color"]=(qn=t["--persona-components-markdown-hr-color"])!=null?qn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(xt=t["--persona-components-markdown-blockquote-borderColor"])!=null?xt:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Wt=t["--persona-components-markdown-blockquote-background"])!=null?Wt:"transparent",t["--persona-md-blockquote-text-color"]=(Rt=t["--persona-components-markdown-blockquote-textColor"])!=null?Rt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(wn=t["--persona-components-collapsibleWidget-container"])!=null?wn:t["--persona-surface"],t["--cw-surface"]=(pr=t["--persona-components-collapsibleWidget-surface"])!=null?pr:t["--persona-surface"],t["--cw-border"]=(Bn=t["--persona-components-collapsibleWidget-border"])!=null?Bn:t["--persona-border"],t["--persona-message-border"]=(Sn=t["--persona-components-message-border"])!=null?Sn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let u=c==null?void 0:c.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let h=c==null?void 0:c.toggleGroup;h&&(h.gap&&(t["--persona-toggle-group-gap"]=h.gap),h.borderRadius&&(t["--persona-toggle-group-radius"]=h.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let ee=m.toolbar;ee.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ee.iconHoverColor),ee.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ee.iconHoverBackground),ee.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ee.iconPadding),ee.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ee.iconBorderRadius),ee.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ee.iconBorder),ee.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ee.toggleGroupGap),ee.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ee.toggleBorderRadius),ee.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ee.copyBackground),ee.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ee.copyBorder),ee.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ee.copyColor),ee.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ee.copyBorderRadius),ee.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ee.copyPadding),ee.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ee.copyMenuBackground,t["--persona-dropdown-bg"]=(H=t["--persona-dropdown-bg"])!=null?H:ee.copyMenuBackground),ee.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ee.copyMenuBorder,t["--persona-dropdown-border"]=(Dn=t["--persona-dropdown-border"])!=null?Dn:ee.copyMenuBorder),ee.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ee.copyMenuShadow,t["--persona-dropdown-shadow"]=(Fn=t["--persona-dropdown-shadow"])!=null?Fn:ee.copyMenuShadow),ee.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ee.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(ur=t["--persona-dropdown-radius"])!=null?ur:ee.copyMenuBorderRadius),ee.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ee.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:ee.copyMenuItemHoverBackground),ee.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ee.iconBackground),ee.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ee.toolbarBorder)}if(m!=null&&m.tab){let ee=m.tab;ee.background&&(t["--persona-artifact-tab-bg"]=ee.background),ee.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ee.activeBackground),ee.activeBorder&&(t["--persona-artifact-tab-active-border"]=ee.activeBorder),ee.borderRadius&&(t["--persona-artifact-tab-radius"]=ee.borderRadius),ee.textColor&&(t["--persona-artifact-tab-color"]=ee.textColor),ee.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ee.hoverBackground),ee.listBackground&&(t["--persona-artifact-tab-list-bg"]=ee.listBackground),ee.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ee.listBorderColor),ee.listPadding&&(t["--persona-artifact-tab-list-padding"]=ee.listPadding)}if(m!=null&&m.pane){let ee=m.pane;if(ee.toolbarBackground){let Nn=(An=ko(e,ee.toolbarBackground))!=null?An:ee.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Nn}}return t}var kc={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 Lc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Lo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Lc(o)&&Lc(s)?t[n]=Lo(o,s):t[n]=s}return t}var bp={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"}}},Ic=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Io=()=>{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"},xp=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Io()},Js=e=>xp(e),vp=e=>no(e),Cp=e=>{var t;let r=no(void 0,{validate:!1});return no({...e,palette:{...r.palette,colors:{...bp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Po=e=>{let r=Js(e),t=Ic(e==null?void 0:e.theme),n=Ic(e==null?void 0:e.darkTheme);return r==="dark"?Cp(Lo(t!=null?t:{},n!=null?n:{})):vp(t)},wp=e=>us(e),vr=(e,r)=>{var o;let t=Po(r),n=wp(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},gs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Io())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Io());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var Pc=require("idiomorph"),Wc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Pc.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function Rc(e,r){var t,n,s,o,a,i,d,c,p,u,h,m,C,M,b,x,S,F;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(h=(u=e.approval)==null?void 0:u.status)!=null?h:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(b=(M=e.reasoning)==null?void 0:M.chunks)==null?void 0:b.length)!=null?x:0,(F=(S=e.contentParts)==null?void 0:S.length)!=null?F:0,r].join("\0")}function Hc(){return new Map}function Bc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Dc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Fc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function ms(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Wo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ro(e,r){return Wo(e)-e.scrollTop<=r}function fs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function hs(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var sn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,Cr=yn+1;function Ys(e,r=yn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Ho=0,wr=null;function Ks(e=document){var t;if(Ho++,Ho===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;wr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Ho=Math.max(0,Ho-1),Ho===0&&wr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=wr.originalOverflow,s.style.position=wr.originalPosition,s.style.top=wr.originalTop,s.style.width=wr.originalWidth,o.scrollTo(0,wr.scrollY),wr=null}}}var ys={side:"right",width:"420px",animate:!0,reveal:"resize"},Jt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Pn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:ys.side,width:(s=r==null?void 0:r.width)!=null?s:ys.width,animate:(o=r==null?void 0:r.animate)!=null?o:ys.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:ys.reveal}};var $n={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Bo=(e,r)=>{let t=f("button");t.type="button",t.innerHTML=`
|
|
8
8
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
9
9
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
18
18
|
<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>
|
|
19
19
|
</svg>
|
|
20
|
-
`,T.addEventListener("click",()=>{u=R,x.forEach((Y,ue)=>{let se=ue<R;Y.classList.toggle("selected",se),Y.setAttribute("aria-checked",ue===R-1?"true":"false")})}),x.push(T),b.appendChild(T)}h.appendChild(b);let S=null;if(d){let R=document.createElement("div");R.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),R.appendChild(S),h.appendChild(R)}let F=document.createElement("div");F.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(u===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let R=(S==null?void 0:S.value.trim())||void 0;await r(u,R),p.remove()}catch(R){k.disabled=!1,k.textContent=a,console.error("[CSAT Feedback] Failed to submit:",R)}}),F.appendChild(w),F.appendChild(k),h.appendChild(F),p.appendChild(h),p}function Ls(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let h=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,C.appendChild(M);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,C.appendChild(b),m.appendChild(C);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,S.appendChild(F),S.appendChild(w);let k=document.createElement("div");k.className="persona-feedback-numbers";let R=[];for(let $=0;$<=10;$++){let te=document.createElement("button");te.type="button",te.className="persona-feedback-rating-btn persona-feedback-number-btn",te.setAttribute("role","radio"),te.setAttribute("aria-checked","false"),te.setAttribute("aria-label",`Rating ${$} out of 10`),te.textContent=String($),te.dataset.rating=String($),$<=6?te.classList.add("persona-feedback-detractor"):$<=8?te.classList.add("persona-feedback-passive"):te.classList.add("persona-feedback-promoter"),te.addEventListener("click",()=>{h=$,R.forEach((Ae,ne)=>{Ae.classList.toggle("selected",ne===$),Ae.setAttribute("aria-checked",ne===$?"true":"false")})}),R.push(te),k.appendChild(te)}x.appendChild(S),x.appendChild(k),m.appendChild(x);let T=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=o,T.rows=3,T.setAttribute("aria-label","Additional comments"),$.appendChild(T),m.appendChild($)}let Y=document.createElement("div");Y.className="persona-feedback-actions";let ue=document.createElement("button");ue.type="button",ue.className="persona-feedback-btn persona-feedback-btn-skip",ue.textContent=i,ue.addEventListener("click",()=>{t==null||t(),u.remove()});let se=document.createElement("button");return se.type="button",se.className="persona-feedback-btn persona-feedback-btn-submit",se.textContent=a,se.addEventListener("click",async()=>{if(h===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}se.disabled=!0,se.textContent="Submitting...";try{let $=(T==null?void 0:T.value.trim())||void 0;await r(h,$),u.remove()}catch($){se.disabled=!1,se.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),Y.appendChild(ue),Y.appendChild(se),m.appendChild(Y),u.appendChild(m),u}var po="persona-chat-history",tu=30*1e3,nu={"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 ru(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let d=(s=nu[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function ou(e){var r,t,n,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function su(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var ca=e=>!e||typeof e!="object"?{}:{...e},ad=e=>e.map(r=>({...r,streaming:!1})),id=(e,r,t)=>{let n=e!=null&&e.markdown?Wr(e.markdown):null,s=Qr(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,u;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let h=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});h!==null&&(a=h.text,h.persist||(o.message.__skipPersist=!0),h.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(u=i!=null?i:o.text)!=null?u:""}):n?d=n(a):d=Zr(a),s?s(d):d}},Is=(e,r,t)=>{var Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Fa,Na,Oa,$a,_a,ja,za,Va,qa,Ua,Ja,Ya,Ka,Xa,Ga,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui;e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=ws(r),s=$o.getForInstance(n.plugins);n.components&&sr.registerAll(n.components);let o=nd(),a=(Ma=n.storageAdapter)!=null?Ma:Ss(),i={},d=null,c=!1,p=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:E}=g;return E&&(c=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return p(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=p(g);y.metadata&&(i=ca(y.metadata)),(ka=y.messages)!=null&&ka.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(La=l.messages)!=null&&La.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>i,h=l=>{var y;i=(y=l({...i}))!=null?y:{},mo()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[_o],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[$r.message,$r.messageAndClick],M=jo({parsers:m,handlers:C,getSessionMetadata:u,updateSessionMetadata:h,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let b=(Pa=(Ia=n.launcher)==null?void 0:Ia.enabled)!=null?Pa:!0,x=(Ra=(Wa=n.launcher)==null?void 0:Wa.autoExpand)!=null?Ra:!1,S=(Ha=n.autoFocusInput)!=null?Ha:!1,F=x,w=b,k=(Da=(Ba=n.layout)==null?void 0:Ba.header)==null?void 0:Da.layout,R=!1,T=b?x:!0,Y=!1,ue=null,se=()=>{Y=!0,ue&&clearTimeout(ue),ue=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},$=id(n,M,se),te=(Na=(Fa=n.features)==null?void 0:Fa.showReasoning)!=null?Na:!0,Ae=($a=(Oa=n.features)==null?void 0:Oa.showToolCalls)!=null?$a:!0,ne=(ja=(_a=n.features)==null?void 0:_a.showEventStreamToggle)!=null?ja:!1,Ce=(Va=(za=n.features)==null?void 0:za.scrollToBottom)!=null?Va:{},de=`${(Ua=typeof n.persistState=="object"?(qa=n.persistState)==null?void 0:qa.keyPrefix:void 0)!=null?Ua:"persona-"}event-stream`,fe=ne?new Oo(de):null,Se=(Ka=(Ya=(Ja=n.features)==null?void 0:Ja.eventStream)==null?void 0:Ya.maxEvents)!=null?Ka:2e3,J=ne?new No(Se,fe):null,ae=null,ge=!1,De=null,Le=0;fe==null||fe.open().then(()=>J==null?void 0:J.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Ie={onCopy:l=>{var g,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,l)},onFeedback:l=>{var g,y;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},Re=(Xa=n.statusIndicator)!=null?Xa:{},ot=l=>{var g,y,E,L;return l==="idle"?(g=Re.idleText)!=null?g:sn.idle:l==="connecting"?(y=Re.connectingText)!=null?y:sn.connecting:l==="connected"?(E=Re.connectedText)!=null?E:sn.connected:l==="error"?(L=Re.errorText)!=null?L:sn.error:sn[l]};function Et(l,g,y,E){if(E==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=g}let{wrapper:j,panel:U}=Nc(n),re=Oc(n,b),{container:_,body:z,messagesWrapper:Q,suggestions:lt,textarea:K,sendButton:X,sendButtonWrapper:St,composerForm:st,statusText:Pt,introTitle:Yt,introSubtitle:Be,closeButton:ie,iconHolder:ke,headerTitle:Tt,headerSubtitle:Mt,header:Qe,footer:et,actionsRow:en,leftActions:Zt,rightActions:tn}=re,O=re.micButton,Ee=re.micButtonWrapper,le=re.attachmentButton,dt=re.attachmentButtonWrapper,He=re.attachmentInput,G=re.attachmentPreviewsContainer;_.classList.add("persona-relative"),z.classList.add("persona-relative");let he=12,Pe=()=>{var l;return(l=Ce.label)!=null?l:""},mt=()=>{var l;return(l=Ce.iconName)!=null?l:"arrow-down"},Nt=()=>Ce.enabled!==!1,at=f("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");at.type="button",at.style.display="none",at.setAttribute("data-persona-scroll-to-bottom","true");let Ot=f("span","persona-flex persona-items-center"),pt=f("span","");at.append(Ot,pt),_.appendChild(at);let Je=()=>{let g=et.style.display==="none"?0:et.offsetHeight;at.style.bottom=`${g+he}px`};Je();let ut=()=>{let l=!!Pe();at.setAttribute("aria-label",Pe()||"Jump to latest"),at.title=Pe(),at.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Ot.innerHTML="";let g=pe(mt(),"14px","currentColor",2);g?(Ot.appendChild(g),Ot.style.display=""):Ot.style.display="none",pt.textContent=Pe(),pt.style.display=l?"":"none"};ut();let Ne=null,$t=null,_n=s.find(l=>l.renderHeader);if(_n!=null&&_n.renderHeader){let l=_n.renderHeader({config:n,defaultRenderer:()=>{let g=or({config:n,showClose:b});return Nr(_,g,n),g.header},onClose:()=>kt(!1,"user")});if(l){let g=_.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Qe=l)}}let Yn=()=>{var g,y,E,L;if(!J)return;if(ge=!0,!ae&&J&&(ae=qc({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>Rn(),config:n,plugins:s})),ae&&(z.style.display="none",(g=et.parentNode)==null||g.insertBefore(ae.element,et),ae.update()),Xe){Xe.style.boxShadow=`inset 0 0 0 1.5px ${bn.actionIconColor}`;let I=(L=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:L.toggleButtonActive;I&&I.split(/\s+/).forEach(P=>P&&Xe.classList.add(P))}let l=()=>{if(!ge)return;let I=Date.now();I-Le>=200&&(ae==null||ae.update(),Le=I),De=requestAnimationFrame(l)};Le=0,De=requestAnimationFrame(l),Zn(),o.emit("eventStream:opened",{timestamp:Date.now()})},Rn=()=>{var l,g,y;if(ge){if(ge=!1,ae&&ae.element.remove(),z.style.display="",Xe){Xe.style.boxShadow="";let E=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;E&&E.split(/\s+/).forEach(L=>L&&Xe.classList.remove(L))}De!==null&&(cancelAnimationFrame(De),De=null),Zn(),o.emit("eventStream:closed",{timestamp:Date.now()})}},Xe=null;if(ne){let l=(Za=(Ga=n.features)==null?void 0:Ga.eventStream)==null?void 0:Za.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Xe=f("button",g),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let y=pe("activity","18px","currentColor",1.5);y&&Xe.appendChild(y);let E=re.clearChatButtonWrapper,L=re.closeButtonWrapper,I=E||L;I&&I.parentNode===Qe?Qe.insertBefore(Xe,I):Qe.appendChild(Xe),Xe.addEventListener("click",()=>{ge?Rn():Yn()})}let Er=l=>{var E,L,I;let g=n.attachments;if(!(g!=null&&g.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let P=l.querySelector("[data-persona-composer-form]");P!=null&&P.parentNode?P.parentNode.insertBefore(y,P):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let P=f("input");P.type="file",P.accept=((E=g.allowedTypes)!=null?E:rr).join(","),P.multiple=((L=g.maxFiles)!=null?L:4)>1,P.style.display="none",P.setAttribute("aria-label",(I=g.buttonTooltipText)!=null?I:"Attach files"),l.appendChild(P)}},jn=s.find(l=>l.renderComposer);if(jn!=null&&jn.renderComposer){let l=n.composer,g=jn.renderComposer({config:n,defaultRenderer:()=>oo({config:n}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{He==null||He.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((Qa=n.voiceRecognition)==null?void 0:Qa.enabled)===!0?()=>{$t==null||$t()}:void 0});g&&(et.replaceWith(g),et=g)}let Tr=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),I=l.querySelector("[data-persona-composer-status]");g&&(st=g),y&&(K=y),E&&(X=E),L&&(O=L,Ee=L.parentElement),I&&(Pt=I);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(lt=P);let q=l.querySelector(".persona-attachment-button");q&&(le=q,dt=q.parentElement),He=l.querySelector('input[type="file"]'),G=l.querySelector(".persona-attachment-previews");let B=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(en=B)};Er(et),Tr(et);let zn=(ei=n.layout)==null?void 0:ei.contentMaxWidth;zn&&st&&(st.style.maxWidth=zn,st.style.marginLeft="auto",st.style.marginRight="auto"),zn&&G&&(G.style.maxWidth=zn,G.style.marginLeft="auto",G.style.marginRight="auto"),(ti=n.attachments)!=null&&ti.enabled&&He&&G&&(Ne=Fr.fromConfig(n.attachments),Ne.setPreviewsContainer(G),He.addEventListener("change",l=>{let g=l.target;Ne==null||Ne.handleFileSelect(g.files),g.value=""})),(()=>{var E,L;let l=(L=(E=n.layout)==null?void 0:E.slots)!=null?L:{},g=I=>{switch(I){case"body-top":return _.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Q;case"footer-top":return lt;case"composer":return st;case"footer-bottom":return Pt;default:return null}},y=(I,P)=>{var q;switch(I){case"header-left":case"header-center":case"header-right":if(I==="header-left")Qe.insertBefore(P,Qe.firstChild);else if(I==="header-right")Qe.appendChild(P);else{let B=Qe.querySelector(".persona-flex-col");B?(q=B.parentNode)==null||q.insertBefore(P,B.nextSibling):Qe.appendChild(P)}break;case"body-top":{let B=z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(P):z.insertBefore(P,z.firstChild);break}case"body-bottom":z.appendChild(P);break;case"footer-top":lt.replaceWith(P);break;case"footer-bottom":Pt.replaceWith(P);break;default:break}};for(let[I,P]of Object.entries(l))if(P)try{let q=P({config:n,defaultContent:()=>g(I)});q&&y(I,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${I}":`,q)}})();let ir=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-bubble-type");I==="reasoning"?(ao.has(L)?ao.delete(L):ao.add(L),jc(L,E)):I==="tool"&&(io.has(L)?io.delete(L):io.add(L),zc(L,E,n))};Q.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ir(l))}),Q.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ir(l))});let Kn=new Map;Q.addEventListener("click",l=>{var P;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest("[data-actions-for]");if(!E)return;let L=E.getAttribute("data-actions-for");if(!L)return;let I=y.getAttribute("data-action");if(I==="copy"){let B=H.getMessages().find(oe=>oe.id===L);if(B&&Ie.onCopy){let oe=B.content||"";navigator.clipboard.writeText(oe).then(()=>{y.classList.add("persona-message-action-success");let be=pe("check",14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ve=pe("copy",14,"currentColor",2);ve&&(y.innerHTML="",y.appendChild(ve))},2e3)}).catch(be=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",be)}),Ie.onCopy(B)}}else if(I==="upvote"||I==="downvote")if(((P=Kn.get(L))!=null?P:null)===I)Kn.delete(L),y.classList.remove("persona-message-action-active");else{let oe=I==="upvote"?"downvote":"upvote",be=E.querySelector(`[data-action="${oe}"]`);be&&be.classList.remove("persona-message-action-active"),Kn.set(L,I),y.classList.add("persona-message-action-active");let ye=H.getMessages().find(je=>je.id===L);ye&&Ie.onFeedback&&Ie.onFeedback({type:I,messageId:ye.id,message:ye})}}),Q.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".vanilla-approval-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-approval-action");if(!I)return;let P=I==="approve"?"approved":"denied",B=H.getMessages().find(be=>be.id===L);if(!(B!=null&&B.approval))return;let oe=E.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(ve=>{ve.disabled=!0,ve.style.opacity="0.5",ve.style.cursor="not-allowed"}),H.resolveApproval(B.approval,P)});let tt=null,xn=null,Hn={artifacts:[],selectedId:null},un=!1,lr={current:null};Q.addEventListener("click",l=>{var ve,ye,je,W,Fe;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((je=(ye=(ve=n.features)==null?void 0:ve.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:je.call(ye,{type:"download",artifactId:E}))===!0)return;let I=H.getArtifactById(E),P=I==null?void 0:I.markdown,q=(I==null?void 0:I.title)||"artifact";if(!P){let we=y.closest("[data-open-artifact]"),me=we==null?void 0:we.closest("[data-message-id]"),We=me==null?void 0:me.getAttribute("data-message-id");if(We){let Ke=H.getMessages().find(xe=>xe.id===We);if(Ke!=null&&Ke.rawContent)try{let xe=JSON.parse(Ke.rawContent);P=(W=xe==null?void 0:xe.props)==null?void 0:W.markdown,q=((Fe=xe==null?void 0:xe.props)==null?void 0:Fe.title)||q}catch{}}}if(!P)return;let B=new Blob([P],{type:"text/markdown"}),oe=URL.createObjectURL(B),be=document.createElement("a");be.href=oe,be.download=`${q}.md`,be.click(),URL.revokeObjectURL(oe)}),Q.addEventListener("click",l=>{var I,P,q;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((q=(P=(I=n.features)==null?void 0:I.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:q.call(P,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(E),Cn())}),Q.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let vn=null,bt=null,an=null,Mn=null,cr=()=>{};function Xn(){Mn==null||Mn(),Mn=null}let dr=()=>{var P;if(!vn||!bt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((P=e.ownerDocument.defaultView)!=null?P:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let E=vn.firstElementChild;if(!E||E===bt)return;let L=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${L}px`,bt.style.zIndex="5";let I=E.offsetWidth-L/2;bt.style.left=`${Math.max(0,I)}px`},Vn=()=>{},Cn=()=>{var y,E,L,I,P;if(!tt||!Wn(n))return;vs(e,n),Cs(e,n),Vn();let l=(I=(L=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:L.narrowHostMaxWidth)!=null?I:520,g=U.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),tt.update(Hn),un?(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),(P=tt.backdrop)==null||P.classList.add("persona-hidden")):Hn.artifacts.length>0&&(tt.element.classList.remove("persona-hidden"),tt.setMobileOpen(!0)),cr()};if(Wn(n)){U.style.position="relative";let l=f("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=f("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(_),tt=Yc(n,{onSelect:y=>{var E;return(E=lr.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{un=!0,Cn()}}),tt.element.classList.add("persona-hidden"),vn=g,g.appendChild(l),g.appendChild(tt.element),tt.backdrop&&U.appendChild(tt.backdrop),U.appendChild(g),cr=()=>{var E,L,I,P;if(!vn||!tt)return;if(!(((I=(L=(E=n.features)==null?void 0:E.artifacts)==null?void 0:L.layout)==null?void 0:I.resizable)===!0)){an==null||an(),an=null,Xn(),bt&&(bt.remove(),bt=null),tt.element.style.removeProperty("width"),tt.element.style.removeProperty("maxWidth");return}if(!bt){let q=f("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let B=e.ownerDocument,oe=(P=B.defaultView)!=null?P:window,be=ve=>{var me,We;if(!tt||ve.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;ve.preventDefault(),Xn();let ye=ve.clientX,je=tt.element.getBoundingClientRect().width,W=(We=(me=n.features)==null?void 0:me.artifacts)==null?void 0:We.layout,Fe=gt=>{let Ke=vn.getBoundingClientRect().width,xe=e.classList.contains("persona-artifact-appearance-seamless"),Qt=xe?0:Zc(vn,oe),ht=xe?0:q.getBoundingClientRect().width||6,cn=je-(gt.clientX-ye),nn=Qc(cn,Ke,Qt,ht,W==null?void 0:W.resizableMinWidth,W==null?void 0:W.resizableMaxWidth);tt.element.style.width=`${nn}px`,tt.element.style.maxWidth="none",dr()},we=()=>{B.removeEventListener("pointermove",Fe),B.removeEventListener("pointerup",we),B.removeEventListener("pointercancel",we),Mn=null;try{q.releasePointerCapture(ve.pointerId)}catch{}};Mn=we,B.addEventListener("pointermove",Fe),B.addEventListener("pointerup",we),B.addEventListener("pointercancel",we);try{q.setPointerCapture(ve.pointerId)}catch{}};q.addEventListener("pointerdown",be),bt=q,vn.insertBefore(q,tt.element),an=()=>{q.removeEventListener("pointerdown",be)}}if(bt){let q=Hn.artifacts.length>0&&!un;bt.classList.toggle("persona-hidden",!q),dr()}},Vn=()=>{var oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke,xe,Qt;if(!b||!tt||((be=(oe=n.launcher)==null?void 0:oe.sidebarMode)!=null?be:!1)||Jt(n)&&Pn(n).reveal==="emerge")return;let E=(ve=e.ownerDocument.defaultView)!=null?ve:window,L=(je=(ye=n.launcher)==null?void 0:ye.mobileFullscreen)!=null?je:!0,I=(Fe=(W=n.launcher)==null?void 0:W.mobileBreakpoint)!=null?Fe:640;if(L&&E.innerWidth<=I||!Gc(n,b))return;let P=(We=(me=(we=n.launcher)==null?void 0:we.width)!=null?me:n.launcherWidth)!=null?We:"min(400px, calc(100vw - 24px))",q=(Qt=(xe=(Ke=(gt=n.features)==null?void 0:gt.artifacts)==null?void 0:Ke.layout)==null?void 0:xe.expandedPanelWidth)!=null?Qt:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!un?(U.style.width=q,U.style.maxWidth=q):(U.style.width=P,U.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(xn=new ResizeObserver(()=>{Cn()}),xn.observe(U))}else U.appendChild(_);e.appendChild(j);let qn=()=>{var ht,cn,nn,rn,Dt,dn,Ve,yt,In,fr,er,hr,tr,Kr,Xr,Vt,Ko,vo,Co,Gr,Xo,yr,Lr;let l=Jt(n),g=(cn=(ht=n.launcher)==null?void 0:ht.sidebarMode)!=null?cn:!1,y=l||g||((rn=(nn=n.launcher)==null?void 0:nn.fullHeight)!=null?rn:!1),E=((Dt=n.launcher)==null?void 0:Dt.enabled)===!1,L=(Ve=(dn=n.theme)==null?void 0:dn.components)==null?void 0:Ve.panel,I=Po(n),P=(Xt,fn)=>{var br;return Xt==null||Xt===""?fn:(br=ko(I,Xt))!=null?br:Xt},q=(yt=e.ownerDocument.defaultView)!=null?yt:window,B=(fr=(In=n.launcher)==null?void 0:In.mobileFullscreen)!=null?fr:!0,oe=(hr=(er=n.launcher)==null?void 0:er.mobileBreakpoint)!=null?hr:640,be=q.innerWidth<=oe,ve=B&&be&&b,ye=(Kr=(tr=n.launcher)==null?void 0:tr.position)!=null?Kr:"bottom-left",je=ye==="bottom-left"||ye==="top-left",W=(Vt=(Xr=n.launcher)==null?void 0:Xr.zIndex)!=null?Vt:yn,Fe=g||ve?"none":"1px solid var(--persona-border)",we=ve?"none":g?je?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!ve&&(we="none",Fe="none");let me=g||ve?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",We=P(L==null?void 0:L.border,Fe),gt=P(L==null?void 0:L.shadow,we),Ke=P(L==null?void 0:L.borderRadius,me);if(e.style.cssText="",j.style.cssText="",U.style.cssText="",_.style.cssText="",z.style.cssText="",et.style.cssText="",ve){j.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"),j.style.cssText=`
|
|
20
|
+
`,T.addEventListener("click",()=>{u=R,x.forEach((Y,ue)=>{let se=ue<R;Y.classList.toggle("selected",se),Y.setAttribute("aria-checked",ue===R-1?"true":"false")})}),x.push(T),b.appendChild(T)}h.appendChild(b);let S=null;if(d){let R=document.createElement("div");R.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),R.appendChild(S),h.appendChild(R)}let F=document.createElement("div");F.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(u===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let R=(S==null?void 0:S.value.trim())||void 0;await r(u,R),p.remove()}catch(R){k.disabled=!1,k.textContent=a,console.error("[CSAT Feedback] Failed to submit:",R)}}),F.appendChild(w),F.appendChild(k),h.appendChild(F),p.appendChild(h),p}function Ls(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let h=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,C.appendChild(M);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,C.appendChild(b),m.appendChild(C);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,S.appendChild(F),S.appendChild(w);let k=document.createElement("div");k.className="persona-feedback-numbers";let R=[];for(let $=0;$<=10;$++){let te=document.createElement("button");te.type="button",te.className="persona-feedback-rating-btn persona-feedback-number-btn",te.setAttribute("role","radio"),te.setAttribute("aria-checked","false"),te.setAttribute("aria-label",`Rating ${$} out of 10`),te.textContent=String($),te.dataset.rating=String($),$<=6?te.classList.add("persona-feedback-detractor"):$<=8?te.classList.add("persona-feedback-passive"):te.classList.add("persona-feedback-promoter"),te.addEventListener("click",()=>{h=$,R.forEach((Ae,ne)=>{Ae.classList.toggle("selected",ne===$),Ae.setAttribute("aria-checked",ne===$?"true":"false")})}),R.push(te),k.appendChild(te)}x.appendChild(S),x.appendChild(k),m.appendChild(x);let T=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=o,T.rows=3,T.setAttribute("aria-label","Additional comments"),$.appendChild(T),m.appendChild($)}let Y=document.createElement("div");Y.className="persona-feedback-actions";let ue=document.createElement("button");ue.type="button",ue.className="persona-feedback-btn persona-feedback-btn-skip",ue.textContent=i,ue.addEventListener("click",()=>{t==null||t(),u.remove()});let se=document.createElement("button");return se.type="button",se.className="persona-feedback-btn persona-feedback-btn-submit",se.textContent=a,se.addEventListener("click",async()=>{if(h===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}se.disabled=!0,se.textContent="Submitting...";try{let $=(T==null?void 0:T.value.trim())||void 0;await r(h,$),u.remove()}catch($){se.disabled=!1,se.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),Y.appendChild(ue),Y.appendChild(se),m.appendChild(Y),u.appendChild(m),u}var po="persona-chat-history",tu=30*1e3,nu={"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 ru(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let d=(s=nu[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function ou(e){var r,t,n,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function su(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var ca=e=>!e||typeof e!="object"?{}:{...e},ad=e=>e.map(r=>({...r,streaming:!1})),id=(e,r,t)=>{let n=e!=null&&e.markdown?Wr(e.markdown):null,s=Qr(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,u;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let h=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});h!==null&&(a=h.text,h.persist||(o.message.__skipPersist=!0),h.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(u=i!=null?i:o.text)!=null?u:""}):n?d=n(a):d=Zr(a),s?s(d):d}},Is=(e,r,t)=>{var Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Fa,Na,Oa,$a,_a,ja,za,Va,qa,Ua,Ja,Ya,Ka,Xa,Ga,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui;e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=ws(r),s=$o.getForInstance(n.plugins);n.components&&sr.registerAll(n.components);let o=nd(),a=(Ma=n.storageAdapter)!=null?Ma:Ss(),i={},d=null,c=!1,p=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:E}=g;return E&&(c=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return p(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=p(g);y.metadata&&(i=ca(y.metadata)),(ka=y.messages)!=null&&ka.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(La=l.messages)!=null&&La.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>i,h=l=>{var y;i=(y=l({...i}))!=null?y:{},mo()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[_o],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[$r.message,$r.messageAndClick],M=jo({parsers:m,handlers:C,getSessionMetadata:u,updateSessionMetadata:h,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let b=(Pa=(Ia=n.launcher)==null?void 0:Ia.enabled)!=null?Pa:!0,x=(Ra=(Wa=n.launcher)==null?void 0:Wa.autoExpand)!=null?Ra:!1,S=(Ha=n.autoFocusInput)!=null?Ha:!1,F=x,w=b,k=(Da=(Ba=n.layout)==null?void 0:Ba.header)==null?void 0:Da.layout,R=!1,T=b?x:!0,Y=!1,ue=null,se=()=>{Y=!0,ue&&clearTimeout(ue),ue=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},$=id(n,M,se),te=(Na=(Fa=n.features)==null?void 0:Fa.showReasoning)!=null?Na:!0,Ae=($a=(Oa=n.features)==null?void 0:Oa.showToolCalls)!=null?$a:!0,ne=(ja=(_a=n.features)==null?void 0:_a.showEventStreamToggle)!=null?ja:!1,Ce=(Va=(za=n.features)==null?void 0:za.scrollToBottom)!=null?Va:{},de=`${(Ua=typeof n.persistState=="object"?(qa=n.persistState)==null?void 0:qa.keyPrefix:void 0)!=null?Ua:"persona-"}event-stream`,fe=ne?new Oo(de):null,Se=(Ka=(Ya=(Ja=n.features)==null?void 0:Ja.eventStream)==null?void 0:Ya.maxEvents)!=null?Ka:2e3,J=ne?new No(Se,fe):null,ae=null,ge=!1,De=null,Le=0;fe==null||fe.open().then(()=>J==null?void 0:J.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Ie={onCopy:l=>{var g,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,l)},onFeedback:l=>{var g,y;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},Re=(Xa=n.statusIndicator)!=null?Xa:{},ot=l=>{var g,y,E,L;return l==="idle"?(g=Re.idleText)!=null?g:sn.idle:l==="connecting"?(y=Re.connectingText)!=null?y:sn.connecting:l==="connected"?(E=Re.connectedText)!=null?E:sn.connected:l==="error"?(L=Re.errorText)!=null?L:sn.error:sn[l]};function Et(l,g,y,E){if(E==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=g}let{wrapper:j,panel:U}=Nc(n),re=Oc(n,b),{container:_,body:z,messagesWrapper:Q,suggestions:lt,textarea:K,sendButton:X,sendButtonWrapper:St,composerForm:st,statusText:Pt,introTitle:Yt,introSubtitle:Be,closeButton:ie,iconHolder:ke,headerTitle:Tt,headerSubtitle:Mt,header:Qe,footer:et,actionsRow:en,leftActions:Zt,rightActions:tn}=re,O=re.micButton,Ee=re.micButtonWrapper,le=re.attachmentButton,dt=re.attachmentButtonWrapper,He=re.attachmentInput,G=re.attachmentPreviewsContainer;_.classList.add("persona-relative"),z.classList.add("persona-relative");let he=12,Pe=()=>{var l;return(l=Ce.label)!=null?l:""},mt=()=>{var l;return(l=Ce.iconName)!=null?l:"arrow-down"},Nt=()=>Ce.enabled!==!1,at=f("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");at.type="button",at.style.display="none",at.setAttribute("data-persona-scroll-to-bottom","true");let Ot=f("span","persona-flex persona-items-center"),pt=f("span","");at.append(Ot,pt),_.appendChild(at);let Je=()=>{let g=et.style.display==="none"?0:et.offsetHeight;at.style.bottom=`${g+he}px`};Je();let ut=()=>{let l=!!Pe();at.setAttribute("aria-label",Pe()||"Jump to latest"),at.title=Pe(),at.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Ot.innerHTML="";let g=pe(mt(),"14px","currentColor",2);g?(Ot.appendChild(g),Ot.style.display=""):Ot.style.display="none",pt.textContent=Pe(),pt.style.display=l?"":"none"};ut();let Ne=null,$t=null,_n=s.find(l=>l.renderHeader);if(_n!=null&&_n.renderHeader){let l=_n.renderHeader({config:n,defaultRenderer:()=>{let g=or({config:n,showClose:b});return Nr(_,g,n),g.header},onClose:()=>kt(!1,"user")});if(l){let g=_.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Qe=l)}}let Yn=()=>{var g,y,E,L;if(!J)return;if(ge=!0,!ae&&J&&(ae=qc({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>Rn(),config:n,plugins:s})),ae&&(z.style.display="none",(g=et.parentNode)==null||g.insertBefore(ae.element,et),ae.update()),Xe){Xe.style.boxShadow=`inset 0 0 0 1.5px ${bn.actionIconColor}`;let I=(L=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:L.toggleButtonActive;I&&I.split(/\s+/).forEach(P=>P&&Xe.classList.add(P))}let l=()=>{if(!ge)return;let I=Date.now();I-Le>=200&&(ae==null||ae.update(),Le=I),De=requestAnimationFrame(l)};Le=0,De=requestAnimationFrame(l),Zn(),o.emit("eventStream:opened",{timestamp:Date.now()})},Rn=()=>{var l,g,y;if(ge){if(ge=!1,ae&&ae.element.remove(),z.style.display="",Xe){Xe.style.boxShadow="";let E=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;E&&E.split(/\s+/).forEach(L=>L&&Xe.classList.remove(L))}De!==null&&(cancelAnimationFrame(De),De=null),Zn(),o.emit("eventStream:closed",{timestamp:Date.now()})}},Xe=null;if(ne){let l=(Za=(Ga=n.features)==null?void 0:Ga.eventStream)==null?void 0:Za.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Xe=f("button",g),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let y=pe("activity","18px","currentColor",1.5);y&&Xe.appendChild(y);let E=re.clearChatButtonWrapper,L=re.closeButtonWrapper,I=E||L;I&&I.parentNode===Qe?Qe.insertBefore(Xe,I):Qe.appendChild(Xe),Xe.addEventListener("click",()=>{ge?Rn():Yn()})}let Er=l=>{var E,L,I;let g=n.attachments;if(!(g!=null&&g.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let P=l.querySelector("[data-persona-composer-form]");P!=null&&P.parentNode?P.parentNode.insertBefore(y,P):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let P=f("input");P.type="file",P.accept=((E=g.allowedTypes)!=null?E:rr).join(","),P.multiple=((L=g.maxFiles)!=null?L:4)>1,P.style.display="none",P.setAttribute("aria-label",(I=g.buttonTooltipText)!=null?I:"Attach files"),l.appendChild(P)}},jn=s.find(l=>l.renderComposer);if(jn!=null&&jn.renderComposer){let l=n.composer,g=jn.renderComposer({config:n,defaultRenderer:()=>oo({config:n}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{He==null||He.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((Qa=n.voiceRecognition)==null?void 0:Qa.enabled)===!0?()=>{$t==null||$t()}:void 0});g&&(et.replaceWith(g),et=g)}let Tr=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),I=l.querySelector("[data-persona-composer-status]");g&&(st=g),y&&(K=y),E&&(X=E),L&&(O=L,Ee=L.parentElement),I&&(Pt=I);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(lt=P);let q=l.querySelector(".persona-attachment-button");q&&(le=q,dt=q.parentElement),He=l.querySelector('input[type="file"]'),G=l.querySelector(".persona-attachment-previews");let B=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(en=B)};Er(et),Tr(et);let zn=(ei=n.layout)==null?void 0:ei.contentMaxWidth;zn&&st&&(st.style.maxWidth=zn,st.style.marginLeft="auto",st.style.marginRight="auto"),zn&&G&&(G.style.maxWidth=zn,G.style.marginLeft="auto",G.style.marginRight="auto"),(ti=n.attachments)!=null&&ti.enabled&&He&&G&&(Ne=Fr.fromConfig(n.attachments),Ne.setPreviewsContainer(G),He.addEventListener("change",l=>{let g=l.target;Ne==null||Ne.handleFileSelect(g.files),g.value=""})),(()=>{var E,L;let l=(L=(E=n.layout)==null?void 0:E.slots)!=null?L:{},g=I=>{switch(I){case"body-top":return _.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Q;case"footer-top":return lt;case"composer":return st;case"footer-bottom":return Pt;default:return null}},y=(I,P)=>{var q;switch(I){case"header-left":case"header-center":case"header-right":if(I==="header-left")Qe.insertBefore(P,Qe.firstChild);else if(I==="header-right")Qe.appendChild(P);else{let B=Qe.querySelector(".persona-flex-col");B?(q=B.parentNode)==null||q.insertBefore(P,B.nextSibling):Qe.appendChild(P)}break;case"body-top":{let B=z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(P):z.insertBefore(P,z.firstChild);break}case"body-bottom":z.appendChild(P);break;case"footer-top":lt.replaceWith(P);break;case"footer-bottom":Pt.replaceWith(P);break;default:break}};for(let[I,P]of Object.entries(l))if(P)try{let q=P({config:n,defaultContent:()=>g(I)});q&&y(I,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${I}":`,q)}})();let ir=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-bubble-type");I==="reasoning"?(ao.has(L)?ao.delete(L):ao.add(L),jc(L,E)):I==="tool"&&(io.has(L)?io.delete(L):io.add(L),zc(L,E,n))};Q.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ir(l))}),Q.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ir(l))});let Kn=new Map;Q.addEventListener("click",l=>{var P;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest("[data-actions-for]");if(!E)return;let L=E.getAttribute("data-actions-for");if(!L)return;let I=y.getAttribute("data-action");if(I==="copy"){let B=H.getMessages().find(oe=>oe.id===L);if(B&&Ie.onCopy){let oe=B.content||"";navigator.clipboard.writeText(oe).then(()=>{y.classList.add("persona-message-action-success");let be=pe("check",14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ve=pe("copy",14,"currentColor",2);ve&&(y.innerHTML="",y.appendChild(ve))},2e3)}).catch(be=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",be)}),Ie.onCopy(B)}}else if(I==="upvote"||I==="downvote")if(((P=Kn.get(L))!=null?P:null)===I)Kn.delete(L),y.classList.remove("persona-message-action-active");else{let oe=I==="upvote"?"downvote":"upvote",be=E.querySelector(`[data-action="${oe}"]`);be&&be.classList.remove("persona-message-action-active"),Kn.set(L,I),y.classList.add("persona-message-action-active");let ye=H.getMessages().find(je=>je.id===L);ye&&Ie.onFeedback&&Ie.onFeedback({type:I,messageId:ye.id,message:ye})}}),Q.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".vanilla-approval-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-approval-action");if(!I)return;let P=I==="approve"?"approved":"denied",B=H.getMessages().find(be=>be.id===L);if(!(B!=null&&B.approval))return;let oe=E.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(ve=>{ve.disabled=!0,ve.style.opacity="0.5",ve.style.cursor="not-allowed"}),H.resolveApproval(B.approval,P)});let tt=null,xn=null,Hn={artifacts:[],selectedId:null},an=!1,lr={current:null};Q.addEventListener("click",l=>{var ve,ye,je,W,Fe;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((je=(ye=(ve=n.features)==null?void 0:ve.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:je.call(ye,{type:"download",artifactId:E}))===!0)return;let I=H.getArtifactById(E),P=I==null?void 0:I.markdown,q=(I==null?void 0:I.title)||"artifact";if(!P){let we=y.closest("[data-open-artifact]"),me=we==null?void 0:we.closest("[data-message-id]"),We=me==null?void 0:me.getAttribute("data-message-id");if(We){let Ke=H.getMessages().find(xe=>xe.id===We);if(Ke!=null&&Ke.rawContent)try{let xe=JSON.parse(Ke.rawContent);P=(W=xe==null?void 0:xe.props)==null?void 0:W.markdown,q=((Fe=xe==null?void 0:xe.props)==null?void 0:Fe.title)||q}catch{}}}if(!P)return;let B=new Blob([P],{type:"text/markdown"}),oe=URL.createObjectURL(B),be=document.createElement("a");be.href=oe,be.download=`${q}.md`,be.click(),URL.revokeObjectURL(oe)}),Q.addEventListener("click",l=>{var I,P,q;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((q=(P=(I=n.features)==null?void 0:I.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:q.call(P,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),an=!1,H.selectArtifact(E),Cn())}),Q.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let vn=null,bt=null,ln=null,Mn=null,cr=()=>{};function Xn(){Mn==null||Mn(),Mn=null}let dr=()=>{var P;if(!vn||!bt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((P=e.ownerDocument.defaultView)!=null?P:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let E=vn.firstElementChild;if(!E||E===bt)return;let L=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${L}px`,bt.style.zIndex="5";let I=E.offsetWidth-L/2;bt.style.left=`${Math.max(0,I)}px`},Vn=()=>{},Cn=()=>{var y,E,L,I,P;if(!tt||!Wn(n))return;vs(e,n),Cs(e,n),Vn();let l=(I=(L=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:L.narrowHostMaxWidth)!=null?I:520,g=U.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),tt.update(Hn),an?(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),(P=tt.backdrop)==null||P.classList.add("persona-hidden")):Hn.artifacts.length>0&&(tt.element.classList.remove("persona-hidden"),tt.setMobileOpen(!0)),cr()};if(Wn(n)){U.style.position="relative";let l=f("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=f("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(_),tt=Yc(n,{onSelect:y=>{var E;return(E=lr.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{an=!0,Cn()}}),tt.element.classList.add("persona-hidden"),vn=g,g.appendChild(l),g.appendChild(tt.element),tt.backdrop&&U.appendChild(tt.backdrop),U.appendChild(g),cr=()=>{var E,L,I,P;if(!vn||!tt)return;if(!(((I=(L=(E=n.features)==null?void 0:E.artifacts)==null?void 0:L.layout)==null?void 0:I.resizable)===!0)){ln==null||ln(),ln=null,Xn(),bt&&(bt.remove(),bt=null),tt.element.style.removeProperty("width"),tt.element.style.removeProperty("maxWidth");return}if(!bt){let q=f("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let B=e.ownerDocument,oe=(P=B.defaultView)!=null?P:window,be=ve=>{var me,We;if(!tt||ve.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;ve.preventDefault(),Xn();let ye=ve.clientX,je=tt.element.getBoundingClientRect().width,W=(We=(me=n.features)==null?void 0:me.artifacts)==null?void 0:We.layout,Fe=gt=>{let Ke=vn.getBoundingClientRect().width,xe=e.classList.contains("persona-artifact-appearance-seamless"),Qt=xe?0:Zc(vn,oe),ht=xe?0:q.getBoundingClientRect().width||6,dn=je-(gt.clientX-ye),nn=Qc(dn,Ke,Qt,ht,W==null?void 0:W.resizableMinWidth,W==null?void 0:W.resizableMaxWidth);tt.element.style.width=`${nn}px`,tt.element.style.maxWidth="none",dr()},we=()=>{B.removeEventListener("pointermove",Fe),B.removeEventListener("pointerup",we),B.removeEventListener("pointercancel",we),Mn=null;try{q.releasePointerCapture(ve.pointerId)}catch{}};Mn=we,B.addEventListener("pointermove",Fe),B.addEventListener("pointerup",we),B.addEventListener("pointercancel",we);try{q.setPointerCapture(ve.pointerId)}catch{}};q.addEventListener("pointerdown",be),bt=q,vn.insertBefore(q,tt.element),ln=()=>{q.removeEventListener("pointerdown",be)}}if(bt){let q=Hn.artifacts.length>0&&!an;bt.classList.toggle("persona-hidden",!q),dr()}},Vn=()=>{var oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke,xe,Qt;if(!b||!tt||((be=(oe=n.launcher)==null?void 0:oe.sidebarMode)!=null?be:!1)||Jt(n)&&Pn(n).reveal==="emerge")return;let E=(ve=e.ownerDocument.defaultView)!=null?ve:window,L=(je=(ye=n.launcher)==null?void 0:ye.mobileFullscreen)!=null?je:!0,I=(Fe=(W=n.launcher)==null?void 0:W.mobileBreakpoint)!=null?Fe:640;if(L&&E.innerWidth<=I||!Gc(n,b))return;let P=(We=(me=(we=n.launcher)==null?void 0:we.width)!=null?me:n.launcherWidth)!=null?We:"min(400px, calc(100vw - 24px))",q=(Qt=(xe=(Ke=(gt=n.features)==null?void 0:gt.artifacts)==null?void 0:Ke.layout)==null?void 0:xe.expandedPanelWidth)!=null?Qt:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!an?(U.style.width=q,U.style.maxWidth=q):(U.style.width=P,U.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(xn=new ResizeObserver(()=>{Cn()}),xn.observe(U))}else U.appendChild(_);e.appendChild(j);let qn=()=>{var ht,dn,nn,rn,Dt,pn,Ve,yt,In,fr,er,hr,tr,Kr,Xr,Vt,Ko,vo,Co,Gr,Xo,yr,Lr;let l=Jt(n),g=(dn=(ht=n.launcher)==null?void 0:ht.sidebarMode)!=null?dn:!1,y=l||g||((rn=(nn=n.launcher)==null?void 0:nn.fullHeight)!=null?rn:!1),E=((Dt=n.launcher)==null?void 0:Dt.enabled)===!1,L=(Ve=(pn=n.theme)==null?void 0:pn.components)==null?void 0:Ve.panel,I=Po(n),P=(Xt,fn)=>{var br;return Xt==null||Xt===""?fn:(br=ko(I,Xt))!=null?br:Xt},q=(yt=e.ownerDocument.defaultView)!=null?yt:window,B=(fr=(In=n.launcher)==null?void 0:In.mobileFullscreen)!=null?fr:!0,oe=(hr=(er=n.launcher)==null?void 0:er.mobileBreakpoint)!=null?hr:640,be=q.innerWidth<=oe,ve=B&&be&&b,ye=(Kr=(tr=n.launcher)==null?void 0:tr.position)!=null?Kr:"bottom-left",je=ye==="bottom-left"||ye==="top-left",W=(Vt=(Xr=n.launcher)==null?void 0:Xr.zIndex)!=null?Vt:yn,Fe=g||ve?"none":"1px solid var(--persona-border)",we=ve?"none":g?je?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!ve&&(we="none",Fe="none");let me=g||ve?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",We=P(L==null?void 0:L.border,Fe),gt=P(L==null?void 0:L.shadow,we),Ke=P(L==null?void 0:L.borderRadius,me);if(e.style.cssText="",j.style.cssText="",U.style.cssText="",_.style.cssText="",z.style.cssText="",et.style.cssText="",ve){j.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"),j.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
inset: 0 !important;
|
|
23
23
|
width: 100% !important;
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
flex-shrink: 0 !important;
|
|
95
95
|
border-top: none !important;
|
|
96
96
|
padding: 8px 16px 12px 16px !important;
|
|
97
|
-
`}if(!E&&!l){let Xt="max-height: -moz-available !important; max-height: stretch !important;",fn=g?"":"padding-top: 1.25em !important;",br=g?"":`z-index: ${(Lr=(yr=n.launcher)==null?void 0:yr.zIndex)!=null?Lr:yn} !important;`;j.style.cssText+=Xt+fn+br}};qn(),vr(e,n),vs(e,n),Cs(e,n);let xt=[],Wt=null,Rt=null;xt.push(()=>{Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null}),xn&&xt.push(()=>{xn==null||xn.disconnect(),xn=null}),xt.push(()=>{an==null||an(),an=null,Xn(),bt&&(bt.remove(),bt=null),tt==null||tt.element.style.removeProperty("width"),tt==null||tt.element.style.removeProperty("maxWidth")}),ne&&xt.push(()=>{De!==null&&(cancelAnimationFrame(De),De=null),ae==null||ae.destroy(),ae=null,J==null||J.destroy(),J=null,fe=null});let wn=null,pr=()=>{wn&&(wn(),wn=null),n.colorScheme==="auto"&&(wn=gs(()=>{vr(e,n)}))};pr(),xt.push(()=>{wn&&(wn(),wn=null)});let Bn=Vc(lt),Sn=null,H,Dn=!1,Fn=Hc(),ur=0,gn=ms(),An=0,ee=null,Nn=!1,zr=1,uo=8,Vr=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},go=(ri=(ni=n.voiceRecognition)==null?void 0:ni.autoResume)!=null?ri:!1,kn=l=>{o.emit("voice:state",{active:Ye.active,source:l,timestamp:Date.now()})},mn=()=>{h(l=>({...l,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},Vo=()=>{var E,L;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=ca(i.voiceState),g=!!l.active,y=Number((L=l.timestamp)!=null?L:0);Ye.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<tu&&setTimeout(()=>{var I,P;Ye.active||(Ye.manuallyDeactivated=!1,((P=(I=n.voiceRecognition)==null?void 0:I.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),kn("restore"),H.isVoiceActive()&&v()}):qe("restore"))},1e3)},qo=()=>H?ad(H.getMessages()).filter(l=>!l.__skipPersist):[];function mo(l){if(!(a!=null&&a.save))return;let y={messages:l?ad(l):H?qo():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let Gn=null,Uo=()=>j.querySelector("#persona-scroll-container")||z,qr=()=>{Gn!==null&&(cancelAnimationFrame(Gn),Gn=null),Nn=!1},Ur=()=>{ee!==null&&(cancelAnimationFrame(ee),ee=null),qr()},Zn=()=>{if(!Nt()||ge){at.parentNode&&at.remove(),at.style.display="none";return}at.parentNode!==_&&_.appendChild(at),Je();let l=Wo(z)>0;at.style.display=gn.isFollowing()||!l?"none":""},fo=()=>{gn.pause()&&(Ur(),Zn())},gr=()=>{gn.resume(),Zn()},mr=(l=!1)=>{gn.isFollowing()&&(!l&&!Dn||(Ur(),ee=requestAnimationFrame(()=>{ee=null,gn.isFollowing()&&Jo(Uo(),l?220:140)})))},Jo=(l,g=500)=>{let y=l.scrollTop,E=Wo(l),L=E-y;if(Math.abs(L)<1){An=l.scrollTop;return}qr();let I=performance.now();Nn=!0;let P=B=>1-Math.pow(1-B,3),q=B=>{if(!gn.isFollowing()){qr();return}let oe=Wo(l);oe!==E&&(E=oe,L=E-y);let be=B-I,ve=Math.min(be/g,1),ye=P(ve),je=y+L*ye;l.scrollTop=je,An=l.scrollTop,ve<1?Gn=requestAnimationFrame(q):(l.scrollTop=E,An=l.scrollTop,Gn=null,Nn=!1)};Gn=requestAnimationFrame(q)},Yo=l=>{let g=new Map;l.forEach(y=>{let E=Vr.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!E&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(E!=null&&E.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(E?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Vr.clear(),g.forEach((y,E)=>{Vr.set(E,y)})},Mr=(l,g,y)=>{var be,ve,ye,je;let E=document.createElement("div"),I=(()=>{var Fe;let W=s.find(we=>we.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Fe=n.loadingIndicator)!=null&&Fe.render)return n.loadingIndicator.render})(),P=new Set;g.forEach(W=>{var xe,Qt;P.add(W.id);let Fe=Rc(W,ur),we=Bc(Fn,W.id,Fe);if(we){E.appendChild(we.cloneNode(!0));return}let me=null,We=s.find(ht=>!!(W.variant==="reasoning"&&ht.renderReasoning||W.variant==="tool"&&ht.renderToolCall||W.variant==="approval"&&ht.renderApproval||!W.variant&&ht.renderMessage)),gt=(xe=n.layout)==null?void 0:xe.messages;if(We)if(W.variant==="reasoning"&&W.reasoning&&We.renderReasoning){if(!te)return;me=We.renderReasoning({message:W,defaultRenderer:()=>ta(W),config:n})}else if(W.variant==="tool"&&W.toolCall&&We.renderToolCall){if(!Ae)return;me=We.renderToolCall({message:W,defaultRenderer:()=>na(W,n),config:n})}else if(W.variant==="approval"&&W.approval&&We.renderApproval){if(n.approval===!1)return;me=We.renderApproval({message:W,defaultRenderer:()=>ra(W,n),config:n})}else We.renderMessage&&(me=We.renderMessage({message:W,defaultRenderer:()=>{let ht=so(W,y,gt,n.messageActions,Ie,{loadingIndicatorRenderer:I,widgetConfig:n});return W.role!=="user"&&aa(ht,W,n,H),ht},config:n}));if(!me&&W.role==="assistant"&&!W.variant&&n.enableComponentStreaming!==!1&&Ts(W)){let cn=Ms(W);if(cn){let nn=Es(cn,{config:n,message:W,transform:y});if(nn)if(n.wrapComponentDirectiveInBubble!==!1){let Dt=document.createElement("div");if(Dt.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Dt.id=`bubble-${W.id}`,Dt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let dn=document.createElement("div");dn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",dn.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Dt.appendChild(dn)}Dt.appendChild(nn),me=Dt}else{let Dt=document.createElement("div");if(Dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Dt.id=`bubble-${W.id}`,Dt.setAttribute("data-message-id",W.id),Dt.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let dn=document.createElement("div");dn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",dn.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Dt.appendChild(dn)}Dt.appendChild(nn),me=Dt}}}if(!me)if(W.variant==="reasoning"&&W.reasoning){if(!te)return;me=ta(W)}else if(W.variant==="tool"&&W.toolCall){if(!Ae)return;me=na(W,n)}else if(W.variant==="approval"&&W.approval){if(n.approval===!1)return;me=ra(W,n)}else{let ht=(Qt=n.layout)==null?void 0:Qt.messages;ht!=null&&ht.renderUserMessage&&W.role==="user"?me=ht.renderUserMessage({message:W,config:n,streaming:!!W.streaming}):ht!=null&&ht.renderAssistantMessage&&W.role==="assistant"?me=ht.renderAssistantMessage({message:W,config:n,streaming:!!W.streaming}):me=so(W,y,ht,n.messageActions,Ie,{loadingIndicatorRenderer:I,widgetConfig:n}),W.role!=="user"&&me&&aa(me,W,n,H)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${W.id}`,Ke.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Ke.classList.add("persona-justify-end"),(me==null?void 0:me.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(me),Dc(Fn,W.id,Fe,Ke),E.appendChild(Ke)}),Fc(Fn,P);let q=g.some(W=>W.role==="assistant"&&W.streaming),B=g[g.length-1],oe=(B==null?void 0:B.role)==="assistant"&&!B.streaming&&B.variant!=="approval";if(Dn&&g.some(W=>W.role==="user")&&!q&&!oe){let W={config:n,streaming:!0,location:"standalone",defaultRenderer:Or},Fe=s.find(me=>me.renderLoadingIndicator),we=null;if(Fe!=null&&Fe.renderLoadingIndicator&&(we=Fe.renderLoadingIndicator(W)),we===null&&((be=n.loadingIndicator)!=null&&be.render)&&(we=n.loadingIndicator.render(W)),we===null&&(we=Or()),we){let me=document.createElement("div"),We=((ve=n.loadingIndicator)==null?void 0:ve.showBubble)!==!1;me.className=We?["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(" "),me.setAttribute("data-typing-indicator","true"),me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",me.appendChild(we);let gt=document.createElement("div");gt.className="persona-flex",gt.id="wrapper-typing-indicator",gt.setAttribute("data-wrapper-id","typing-indicator"),gt.appendChild(me),E.appendChild(gt)}}if(!Dn&&g.length>0){let W=g[g.length-1],Fe={config:n,lastMessage:W,messageCount:g.length},we=s.find(We=>We.renderIdleIndicator),me=null;if(we!=null&&we.renderIdleIndicator&&(me=we.renderIdleIndicator(Fe)),me===null&&((ye=n.loadingIndicator)!=null&&ye.renderIdle)&&(me=n.loadingIndicator.renderIdle(Fe)),me){let We=document.createElement("div"),gt=((je=n.loadingIndicator)==null?void 0:je.showBubble)!==!1;We.className=gt?["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(" "),We.setAttribute("data-idle-indicator","true"),We.appendChild(me);let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id="wrapper-idle-indicator",Ke.setAttribute("data-wrapper-id","idle-indicator"),Ke.appendChild(We),E.appendChild(Ke)}}Wc(l,E)},kr=()=>{var B,oe,be,ve,ye;if(!b)return;let l=Jt(n),g=(B=e.ownerDocument.defaultView)!=null?B:window,y=(be=(oe=n.launcher)==null?void 0:oe.mobileBreakpoint)!=null?be:640,E=(ye=(ve=n.launcher)==null?void 0:ve.mobileFullscreen)!=null?ye:!0,L=g.innerWidth<=y,I=E&&L&&b,P=Pn(n).reveal;T?(j.style.removeProperty("display"),j.style.display=l?"flex":"",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-95","persona-opacity-0"),U.classList.add("persona-scale-100","persona-opacity-100"),Ue?Ue.element.style.display="none":$e&&($e.style.display="none")):(l?l&&(P==="overlay"||P==="push")&&!I?(j.style.removeProperty("display"),j.style.display="flex",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.setProperty("display","none","important"),j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.display="",j.classList.add("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100"),U.classList.add("persona-scale-95","persona-opacity-0")),Ue?Ue.element.style.display=l?"none":"":$e&&($e.style.display=l?"none":""))},kt=(l,g="user")=>{var I,P;if(!b||T===l)return;let y=T;T=l,kr();let E=(()=>{var je,W,Fe,we,me,We,gt;let q=(W=(je=n.launcher)==null?void 0:je.sidebarMode)!=null?W:!1,B=(Fe=e.ownerDocument.defaultView)!=null?Fe:window,oe=(me=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?me:!0,be=(gt=(We=n.launcher)==null?void 0:We.mobileBreakpoint)!=null?gt:640,ve=B.innerWidth<=be,ye=Jt(n)&&oe&&ve;return q||oe&&ve&&b||ye})();if(T&&E){if(!Wt){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(Wt=Ys(B,(P=(I=n.launcher)==null?void 0:I.zIndex)!=null?P:yn))}Rt||(Rt=Ks(e.ownerDocument))}else T||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null);T&&(Ht(),mr(!0));let L={open:T,source:g,timestamp:Date.now()};T&&!y?o.emit("widget:opened",L):!T&&y&&o.emit("widget:closed",L),o.emit("widget:state",{open:T,launcherEnabled:b,voiceActive:Ye.active,streaming:H.isStreaming()})},Jr=l=>{X.disabled=l,O&&(O.disabled=l),Bn.buttons.forEach(g=>{g.disabled=l}),et.dataset.personaComposerStreaming=l?"true":"false",et.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Yr=()=>{Ye.active||K&&K.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Yr(),200)});let ho=()=>{var y,E,L,I,P,q,B,oe,be,ve,ye;Yt.textContent=(E=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?E:"Hello \u{1F44B}",Be.textContent=(I=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",K.placeholder=(q=(P=n.copy)==null?void 0:P.inputPlaceholder)!=null?q:"How can I help...";let l=z.querySelector("[data-persona-intro-card]");if(l){let je=((B=n.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=je?"":"none",je?(z.classList.remove("persona-gap-3"),z.classList.add("persona-gap-6")):(z.classList.remove("persona-gap-6"),z.classList.add("persona-gap-3"))}(be=(oe=n.sendButton)==null?void 0:oe.useIcon)!=null&&be||(X.textContent=(ye=(ve=n.copy)==null?void 0:ve.sendButtonLabel)!=null?ye:"Send"),K.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',K.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};if(n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{h(g=>({...g,sessionId:l}))}}),H=new to(n,{onMessagesChanged(l){Mr(Q,l,$),H&&(l.some(L=>L.role==="user")?Bn.render([],H,K,l):Bn.render(n.suggestionChips,H,K,l,n.suggestionChipsConfig)),mr(!Dn),Yo(l);let g=[...l].reverse().find(E=>E.role==="user"),y=Ye.lastUserMessageId;g&&g.id!==y&&(Ye.lastUserMessageId=g.id,o.emit("user:message",g)),Ye.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),mo(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{};Et(Pt,(L=>{var I,P,q,B;return L==="idle"?(I=g.idleText)!=null?I:sn.idle:L==="connecting"?(P=g.connectingText)!=null?P:sn.connecting:L==="connected"?(q=g.connectedText)!=null?q:sn.connected:L==="error"?(B=g.errorText)!=null?B:sn.error:sn[L]})(l),g,l)},onStreamingChanged(l){Dn=l,Jr(l),H&&Mr(Q,H.getMessages(),$),l||mr(!0)},onVoiceStatusChanged(l){var g,y;if(((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":A(),_e();break;case"speaking":A(),D();break;default:l==="idle"&&H.isBargeInActive()?(A(),v(),O==null||O.setAttribute("aria-label","End voice session")):(Ye.active=!1,A(),kn("system"),mn());break}},onArtifactsState(l){Hn=l,Cn()}}),lr.current=H,((si=(oi=n.voiceRecognition)==null?void 0:oi.provider)==null?void 0:si.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&H.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),J&&H.setSSEEventCallback((l,g)=>{J==null||J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),d&&d.then(l=>{var g;l&&(l.metadata&&(i=ca(l.metadata),M.syncFromMetadata()),(g=l.messages)!=null&&g.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let yo=l=>{var L;l.preventDefault();let g=K.value.trim(),y=(L=Ne==null?void 0:Ne.hasAttachments())!=null?L:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(...Ne.getContentParts()),g&&E.push(ss(g))),K.value="",K.style.height="auto",H.sendMessage(g,{contentParts:E}),y&&Ne.clearAttachments()},bo=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},xo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!Ne)return;let g=ru(l.clipboardData);g.length!==0&&(l.preventDefault(),await Ne.handleFiles(g))},ln=null,En=!1,Qn=null,Oe=null,Z=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qe=(l="user")=>{var I,P,q,B,oe,be,ve;if(En||H.isStreaming())return;let g=Z();if(!g)return;ln=new g;let E=(P=((I=n.voiceRecognition)!=null?I:{}).pauseDuration)!=null?P:2e3;ln.continuous=!0,ln.interimResults=!0,ln.lang="en-US";let L=K.value;ln.onresult=ye=>{let je="",W="";for(let we=0;we<ye.results.length;we++){let me=ye.results[we],We=me[0].transcript;me.isFinal?je+=We+" ":W=We}let Fe=L+je+W;K.value=Fe,Qn&&clearTimeout(Qn),(je||W)&&(Qn=window.setTimeout(()=>{let we=K.value.trim();we&&ln&&En&&(nt(),K.value="",K.style.height="auto",H.sendMessage(we,{viaVoice:!0}))},E))},ln.onerror=ye=>{ye.error!=="no-speech"&&nt()},ln.onend=()=>{if(En){let ye=K.value.trim();ye&&ye!==L.trim()&&(K.value="",K.style.height="auto",H.sendMessage(ye,{viaVoice:!0})),nt()}};try{if(ln.start(),En=!0,Ye.active=!0,l!=="system"&&(Ye.manuallyDeactivated=!1),kn(l),mn(),O){let ye=(q=n.voiceRecognition)!=null?q:{};Oe={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(B=ye.iconName)!=null?B:"mic",iconSize:parseFloat((ve=(be=ye.iconSize)!=null?be:(oe=n.sendButton)==null?void 0:oe.size)!=null?ve:"40")||24};let je=ye.recordingBackgroundColor,W=ye.recordingIconColor,Fe=ye.recordingBorderColor;if(O.classList.add("persona-voice-recording"),O.style.backgroundColor=je!=null?je:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=W!=null?W:"var(--persona-voice-recording-indicator, #ffffff)",W){let we=O.querySelector("svg");we&&we.setAttribute("stroke",W)}Fe&&(O.style.borderColor=Fe),O.setAttribute("aria-label","Stop voice recognition")}}catch{nt("system")}},nt=(l="user")=>{if(En){if(En=!1,Qn&&(clearTimeout(Qn),Qn=null),ln){try{ln.stop()}catch{}ln=null}if(Ye.active=!1,kn(l),mn(),O){if(O.classList.remove("persona-voice-recording"),Oe){O.style.backgroundColor=Oe.backgroundColor,O.style.color=Oe.color,O.style.borderColor=Oe.borderColor;let g=O.querySelector("svg");g&&g.setAttribute("stroke",Oe.color||"currentColor"),Oe=null}O.setAttribute("aria-label","Start voice recognition")}}},_t=(l,g)=>{var me,We,gt,Ke,xe,Qt,ht,cn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((me=l==null?void 0:l.provider)==null?void 0:me.type)==="runtype";if(!(y||E))return null;let I=f("div","persona-send-button-wrapper"),P=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");P.type="button",P.setAttribute("aria-label","Start voice recognition");let q=(We=l==null?void 0:l.iconName)!=null?We:"mic",B=(gt=g==null?void 0:g.size)!=null?gt:"40px",oe=(Ke=l==null?void 0:l.iconSize)!=null?Ke:B,be=parseFloat(oe)||24,ve=(xe=l==null?void 0:l.backgroundColor)!=null?xe:g==null?void 0:g.backgroundColor,ye=(Qt=l==null?void 0:l.iconColor)!=null?Qt:g==null?void 0:g.textColor;P.style.width=oe,P.style.height=oe,P.style.minWidth=oe,P.style.minHeight=oe,P.style.fontSize="18px",P.style.lineHeight="1",ye?P.style.color=ye:P.style.color="var(--persona-text, #111827)";let W=pe(q,be,ye||"currentColor",1.5);W?P.appendChild(W):P.textContent="\u{1F3A4}",ve?P.style.backgroundColor=ve:P.style.backgroundColor="",l!=null&&l.borderWidth&&(P.style.borderWidth=l.borderWidth,P.style.borderStyle="solid"),l!=null&&l.borderColor&&(P.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(P.style.paddingLeft=l.paddingX,P.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(P.style.paddingTop=l.paddingY,P.style.paddingBottom=l.paddingY),I.appendChild(P);let Fe=(ht=l==null?void 0:l.tooltipText)!=null?ht:"Start voice recognition";if(((cn=l==null?void 0:l.showTooltip)!=null?cn:!1)&&Fe){let nn=f("div","persona-send-button-tooltip");nn.textContent=Fe,I.appendChild(nn)}return{micButton:P,micButtonWrapper:I}},jt=()=>{var g,y,E,L,I;if(!O||Oe)return;let l=(g=n.voiceRecognition)!=null?g:{};Oe={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((I=(L=l.iconSize)!=null?L:(E=n.sendButton)==null?void 0:E.size)!=null?I:"40")||24}},Kt=(l,g)=>{var I,P,q,B,oe;if(!O)return;let y=O.querySelector("svg");y&&y.remove();let E=(oe=Oe==null?void 0:Oe.iconSize)!=null?oe:parseFloat((B=(q=(I=n.voiceRecognition)==null?void 0:I.iconSize)!=null?q:(P=n.sendButton)==null?void 0:P.size)!=null?B:"40")||24,L=pe(l,E,g,1.5);L&&O.appendChild(L)},Lt=()=>{O&&O.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},v=()=>{var L;if(!O)return;jt();let l=(L=n.voiceRecognition)!=null?L:{},g=l.recordingBackgroundColor,y=l.recordingIconColor,E=l.recordingBorderColor;if(Lt(),O.classList.add("persona-voice-recording"),O.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let I=O.querySelector("svg");I&&I.setAttribute("stroke",y)}E&&(O.style.borderColor=E),O.setAttribute("aria-label","Stop voice recognition")},_e=()=>{var q,B,oe,be,ve,ye,je,W;if(!O)return;jt();let l=(q=n.voiceRecognition)!=null?q:{},g=H.getVoiceInterruptionMode(),y=(B=l.processingIconName)!=null?B:"loader",E=(be=(oe=l.processingIconColor)!=null?oe:Oe==null?void 0:Oe.color)!=null?be:"",L=(ye=(ve=l.processingBackgroundColor)!=null?ve:Oe==null?void 0:Oe.backgroundColor)!=null?ye:"",I=(W=(je=l.processingBorderColor)!=null?je:Oe==null?void 0:Oe.borderColor)!=null?W:"";Lt(),O.classList.add("persona-voice-processing"),O.style.backgroundColor=L,O.style.borderColor=I;let P=E||"currentColor";O.style.color=P,Kt(y,P),O.setAttribute("aria-label","Processing voice input"),g==="none"&&(O.style.cursor="default")},D=()=>{var oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke;if(!O)return;jt();let l=(oe=n.voiceRecognition)!=null?oe:{},g=H.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(be=l.speakingIconName)!=null?be:y,L=(W=l.speakingIconColor)!=null?W:g==="barge-in"?(ye=(ve=l.recordingIconColor)!=null?ve:Oe==null?void 0:Oe.color)!=null?ye:"":(je=Oe==null?void 0:Oe.color)!=null?je:"",I=(me=l.speakingBackgroundColor)!=null?me:g==="barge-in"?(Fe=l.recordingBackgroundColor)!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)":(we=Oe==null?void 0:Oe.backgroundColor)!=null?we:"",P=(Ke=l.speakingBorderColor)!=null?Ke:g==="barge-in"?(We=l.recordingBorderColor)!=null?We:"":(gt=Oe==null?void 0:Oe.borderColor)!=null?gt:"";Lt(),O.classList.add("persona-voice-speaking"),O.style.backgroundColor=I,O.style.borderColor=P;let q=L||"currentColor";O.style.color=q,Kt(E,q);let B=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";O.setAttribute("aria-label",B),g==="none"&&(O.style.cursor="default"),g==="barge-in"&&O.classList.add("persona-voice-recording")},A=()=>{var l,g,y;O&&(Lt(),Oe&&(O.style.backgroundColor=(l=Oe.backgroundColor)!=null?l:"",O.style.color=(g=Oe.color)!=null?g:"",O.style.borderColor=(y=Oe.borderColor)!=null?y:"",Kt(Oe.iconName,Oe.color||"currentColor"),Oe=null),O.style.cursor="",O.setAttribute("aria-label","Start voice recognition"))},N=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=H.getVoiceStatus(),E=H.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,mn(),kn("user"),A()});return}H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),Ye.manuallyDeactivated=!H.isVoiceActive(),mn(),kn("user"),H.isVoiceActive()?v():A()});return}if(En){let y=K.value.trim();Ye.manuallyDeactivated=!0,mn(),nt("user"),y&&(K.value="",K.style.height="auto",H.sendMessage(y))}else Ye.manuallyDeactivated=!1,mn(),qe("user")};$t=N,O&&(O.addEventListener("click",N),xt.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),A()):nt("system"),O&&O.removeEventListener("click",N)}));let ce=o.on("assistant:complete",()=>{go&&(Ye.active||Ye.manuallyDeactivated||go==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!Ye.active&&!Ye.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),kn("auto"),H.isVoiceActive()&&v()}):qe("auto"))},600))});xt.push(ce);let Te=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});xt.push(Te);let rt=()=>{kt(!T,"user")},Ue=null,$e=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>Bo(n,rt).element,onToggle:rt});g&&($e=g)}$e||(Ue=Bo(n,rt))}Ue?e.appendChild(Ue.element):$e&&e.appendChild($e),kr(),Bn.render(n.suggestionChips,H,K,void 0,n.suggestionChipsConfig),ho(),Jr(H.isStreaming()),mr(!0),Vo(),S&&(b?T&&setTimeout(()=>Yr(),200):setTimeout(()=>Yr(),0));let Ht=()=>{var B,oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke,xe,Qt,ht,cn,nn,rn,Dt,dn,Ve;let l=Jt(n),g=(oe=(B=n.launcher)==null?void 0:B.sidebarMode)!=null?oe:!1,y=l||g||((ve=(be=n.launcher)==null?void 0:be.fullHeight)!=null?ve:!1),E=(ye=e.ownerDocument.defaultView)!=null?ye:window,L=(W=(je=n.launcher)==null?void 0:je.mobileFullscreen)!=null?W:!0,I=(we=(Fe=n.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?we:640,P=E.innerWidth<=I,q=L&&P&&b;try{if(q){qn(),vr(e,n);return}if(R&&(R=!1,qn(),vr(e,n)),!b&&!l){U.style.height="",U.style.width="";return}if(!g&&!l){let yt=(We=(me=n==null?void 0:n.launcher)==null?void 0:me.width)!=null?We:n==null?void 0:n.launcherWidth,In=yt!=null?yt:"min(400px, calc(100vw - 24px))";U.style.width=In,U.style.maxWidth=In}if(Vn(),!y){let yt=E.innerHeight,In=64,fr=(Ke=(gt=n.launcher)==null?void 0:gt.heightOffset)!=null?Ke:0,er=Math.max(200,yt-In),hr=Math.min(640,er),tr=Math.max(200,hr-fr);U.style.height=`${tr}px`}}finally{if(Je(),kr(),T&&b){let In=((xe=e.ownerDocument.defaultView)!=null?xe:window).innerWidth<=((ht=(Qt=n.launcher)==null?void 0:Qt.mobileBreakpoint)!=null?ht:640),fr=(nn=(cn=n.launcher)==null?void 0:cn.sidebarMode)!=null?nn:!1,er=(Dt=(rn=n.launcher)==null?void 0:rn.mobileFullscreen)!=null?Dt:!0,hr=Jt(n)&&er&&In,tr=fr||er&&In&&b||hr;if(tr&&!Rt){let Kr=e.getRootNode(),Xr=Kr instanceof ShadowRoot?Kr.host:e.closest(".persona-host");Xr&&!Wt&&(Wt=Ys(Xr,(Ve=(dn=n.launcher)==null?void 0:dn.zIndex)!=null?Ve:yn)),Rt=Ks(e.ownerDocument)}else tr||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null)}}};Ht();let qt=(ai=e.ownerDocument.defaultView)!=null?ai:window;if(qt.addEventListener("resize",Ht),xt.push(()=>qt.removeEventListener("resize",Ht)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Je()});l.observe(et),xt.push(()=>l.disconnect())}An=z.scrollTop;let ft=()=>{let l=z.scrollTop,{action:g,nextLastScrollTop:y}=fs({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:An,nearBottom:Ro(z,uo),userScrollThreshold:zr,isAutoScrolling:Nn,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=y,g==="resume"){gr();return}g==="pause"&&fo()};z.addEventListener("scroll",ft,{passive:!0}),xt.push(()=>z.removeEventListener("scroll",ft));let vt=l=>{let g=hs({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:Ro(z,uo),resumeWhenNearBottom:!0});g==="pause"?fo():g==="resume"&&gr()};z.addEventListener("wheel",vt,{passive:!0}),xt.push(()=>z.removeEventListener("wheel",vt)),at.addEventListener("click",()=>{z.scrollTop=z.scrollHeight,An=z.scrollTop,gr(),mr(!0)}),xt.push(()=>at.remove()),xt.push(()=>{Ur()});let zt=()=>{ie&&(Sn&&(ie.removeEventListener("click",Sn),Sn=null),b?(ie.style.display="",Sn=()=>{kt(!1,"user")},ie.addEventListener("click",Sn)):ie.style.display="none")};zt(),(()=>{let{clearChatButton:l}=re;l&&l.addEventListener("click",()=>{H.clearMessages(),Fn.clear(),gr();try{localStorage.removeItem(po),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${po}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==po)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},M.syncFromMetadata(),J==null||J.clear(),ae==null||ae.update()})})(),st&&st.addEventListener("submit",yo),K==null||K.addEventListener("keydown",bo),K==null||K.addEventListener("paste",xo),xt.push(()=>{st&&st.removeEventListener("submit",yo),K==null||K.removeEventListener("keydown",bo),K==null||K.removeEventListener("paste",xo)}),xt.push(()=>{H.cancel()}),Ue?xt.push(()=>{Ue==null||Ue.destroy()}):$e&&xt.push(()=>{$e==null||$e.remove()});let Ze={update(l){var gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Fi,Ni,Oi,$i,_i,ji,zi,Vi,qi,Ui,Ji,Yi,Ki,Xi,Gi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,gl,ml,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Fl,Nl,Ol,$l,_l,jl,zl,Vl,ql,Ul,Jl,Yl,Kl,Xl,Gl,Zl,Ql,ec,tc,nc;let g=n.toolCall,y=n.messageActions,E=(gi=n.layout)==null?void 0:gi.messages,L=n.colorScheme,I=n.loadingIndicator,P=n.iterationDisplay;n={...n,...l},qn(),vr(e,n),vs(e,n),Cs(e,n),Cn(),n.colorScheme!==L&&pr();let q=$o.getForInstance(n.plugins);s.length=0,s.push(...q),b=(fi=(mi=n.launcher)==null?void 0:mi.enabled)!=null?fi:!0,x=(yi=(hi=n.launcher)==null?void 0:hi.autoExpand)!=null?yi:!1,te=(xi=(bi=n.features)==null?void 0:bi.showReasoning)!=null?xi:!0,Ae=(Ci=(vi=n.features)==null?void 0:vi.showToolCalls)!=null?Ci:!0,Ce=(Si=(wi=n.features)==null?void 0:wi.scrollToBottom)!=null?Si:{},ut(),Zn();let B=ne;if(ne=(Ei=(Ai=n.features)==null?void 0:Ai.showEventStreamToggle)!=null?Ei:!1,ne&&!B){if(J||(fe=new Oo(de),J=new No(Se,fe),fe.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),H.setSSEEventCallback((V,it)=>{J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:V,timestamp:Date.now(),payload:JSON.stringify(it)})})),!Xe&&Qe){let V=(Mi=(Ti=n.features)==null?void 0:Ti.eventStream)==null?void 0:Mi.classNames,it="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"+(V!=null&&V.toggleButton?" "+V.toggleButton:"");Xe=f("button",it),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let It=pe("activity","18px","currentColor",1.5);It&&Xe.appendChild(It);let ze=re.clearChatButtonWrapper,ct=re.closeButtonWrapper,Ut=ze||ct;Ut&&Ut.parentNode===Qe?Qe.insertBefore(Xe,Ut):Qe.appendChild(Xe),Xe.addEventListener("click",()=>{ge?Rn():Yn()})}}else!ne&&B&&(Rn(),Xe&&(Xe.remove(),Xe=null),J==null||J.clear(),fe==null||fe.destroy(),J=null,fe=null);if(((ki=n.launcher)==null?void 0:ki.enabled)===!1&&Ue&&(Ue.destroy(),Ue=null),((Li=n.launcher)==null?void 0:Li.enabled)===!1&&$e&&($e.remove(),$e=null),((Ii=n.launcher)==null?void 0:Ii.enabled)!==!1&&!Ue&&!$e){let V=s.find(it=>it.renderLauncher);if(V!=null&&V.renderLauncher){let it=V.renderLauncher({config:n,defaultRenderer:()=>Bo(n,rt).element,onToggle:rt});it&&($e=it,e.appendChild($e))}$e||(Ue=Bo(n,rt),e.appendChild(Ue.element))}Ue&&Ue.update(n),Tt&&((Pi=n.launcher)==null?void 0:Pi.title)!==void 0&&(Tt.textContent=n.launcher.title),Mt&&((Wi=n.launcher)==null?void 0:Wi.subtitle)!==void 0&&(Mt.textContent=n.launcher.subtitle);let oe=(Ri=n.layout)==null?void 0:Ri.header;if((oe==null?void 0:oe.layout)!==k&&Qe){let V=oe?ro(n,oe,{showClose:b,onClose:()=>kt(!1,"user")}):or({config:n,showClose:b,onClose:()=>kt(!1,"user")});Qe.replaceWith(V.header),Qe=V.header,ke=V.iconHolder,Tt=V.headerTitle,Mt=V.headerSubtitle,ie=V.closeButton,k=oe==null?void 0:oe.layout}else if(oe&&(ke&&(ke.style.display=oe.showIcon===!1?"none":""),Tt&&(Tt.style.display=oe.showTitle===!1?"none":""),Mt&&(Mt.style.display=oe.showSubtitle===!1?"none":""),ie&&(ie.style.display=oe.showCloseButton===!1?"none":""),re.clearChatButtonWrapper)){let V=oe.showClearChat;if(V!==void 0){re.clearChatButtonWrapper.style.display=V?"":"none";let{closeButtonWrapper:it}=re;it&&!it.classList.contains("persona-absolute")&&(V?it.classList.remove("persona-ml-auto"):it.classList.add("persona-ml-auto"))}}let ve=((Hi=n.layout)==null?void 0:Hi.showHeader)!==!1;Qe&&(Qe.style.display=ve?"":"none");let ye=((Bi=n.layout)==null?void 0:Bi.showFooter)!==!1;et&&(et.style.display=ye?"":"none"),Je(),Zn(),b!==w?b?kt(x,"auto"):(T=!0,kr()):x!==F&&kt(x,"auto"),F=x,w=b,Ht(),zt();let Fe=JSON.stringify(l.toolCall)!==JSON.stringify(g),we=JSON.stringify(n.messageActions)!==JSON.stringify(y),me=JSON.stringify((Di=n.layout)==null?void 0:Di.messages)!==JSON.stringify(E),We=((Fi=n.loadingIndicator)==null?void 0:Fi.render)!==(I==null?void 0:I.render)||((Ni=n.loadingIndicator)==null?void 0:Ni.renderIdle)!==(I==null?void 0:I.renderIdle)||((Oi=n.loadingIndicator)==null?void 0:Oi.showBubble)!==(I==null?void 0:I.showBubble),gt=n.iterationDisplay!==P;(Fe||we||me||We||gt)&&H&&(ur++,Mr(Q,H.getMessages(),$));let xe=($i=n.launcher)!=null?$i:{},Qt=(_i=xe.headerIconHidden)!=null?_i:!1,ht=(zi=(ji=n.layout)==null?void 0:ji.header)==null?void 0:zi.showIcon,cn=Qt||ht===!1,nn=xe.headerIconName,rn=(Vi=xe.headerIconSize)!=null?Vi:"48px";if(ke){let V=_.querySelector(".persona-border-b-persona-divider"),it=V==null?void 0:V.querySelector(".persona-flex-col");if(cn)ke.style.display="none",V&&it&&!V.contains(it)&&V.insertBefore(it,V.firstChild);else{if(ke.style.display="",ke.style.height=rn,ke.style.width=rn,V&&it&&(V.contains(ke)?ke.nextSibling!==it&&(ke.remove(),V.insertBefore(ke,it)):V.insertBefore(ke,it)),nn){let ze=parseFloat(rn)||24,ct=pe(nn,ze*.6,"#ffffff",2);ct?ke.replaceChildren(ct):ke.textContent=(qi=xe.agentIconText)!=null?qi:"\u{1F4AC}"}else if(xe.iconUrl){let ze=ke.querySelector("img");if(ze)ze.src=xe.iconUrl,ze.style.height=rn,ze.style.width=rn;else{let ct=document.createElement("img");ct.src=xe.iconUrl,ct.alt="",ct.className="persona-rounded-xl persona-object-cover",ct.style.height=rn,ct.style.width=rn,ke.replaceChildren(ct)}}else{let ze=ke.querySelector("svg"),ct=ke.querySelector("img");(ze||ct)&&ke.replaceChildren(),ke.textContent=(Ui=xe.agentIconText)!=null?Ui:"\u{1F4AC}"}let It=ke.querySelector("img");It&&(It.style.height=rn,It.style.width=rn)}}let Dt=(Yi=(Ji=n.layout)==null?void 0:Ji.header)==null?void 0:Yi.showTitle,dn=(Xi=(Ki=n.layout)==null?void 0:Ki.header)==null?void 0:Xi.showSubtitle;if(Tt&&(Tt.style.display=Dt===!1?"none":""),Mt&&(Mt.style.display=dn===!1?"none":""),ie){((Zi=(Gi=n.layout)==null?void 0:Gi.header)==null?void 0:Zi.showCloseButton)===!1?ie.style.display="none":ie.style.display="";let it=(Qi=xe.closeButtonSize)!=null?Qi:"32px",It=(el=xe.closeButtonPlacement)!=null?el:"inline";ie.style.height=it,ie.style.width=it;let{closeButtonWrapper:ze}=re,ct=It==="top-right",Ut=ze==null?void 0:ze.classList.contains("persona-absolute");if(ze&&ct!==Ut)if(ze.remove(),ct)ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",_.style.position="relative",_.appendChild(ze);else{let Ge=(nl=(tl=xe.clearChat)==null?void 0:tl.placement)!=null?nl:"inline",Gt=(ol=(rl=xe.clearChat)==null?void 0:rl.enabled)!=null?ol:!0;ze.className=Gt&&Ge==="inline"?"":"persona-ml-auto";let hn=_.querySelector(".persona-border-b-persona-divider");hn&&hn.appendChild(ze)}if(ie.style.color=xe.closeButtonColor||bn.actionIconColor,xe.closeButtonBackgroundColor?(ie.style.backgroundColor=xe.closeButtonBackgroundColor,ie.classList.remove("hover:persona-bg-gray-100")):(ie.style.backgroundColor="",ie.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let Ge=xe.closeButtonBorderWidth||"0px",Gt=xe.closeButtonBorderColor||"transparent";ie.style.border=`${Ge} solid ${Gt}`,ie.classList.remove("persona-border-none")}else ie.style.border="",ie.classList.add("persona-border-none");xe.closeButtonBorderRadius?(ie.style.borderRadius=xe.closeButtonBorderRadius,ie.classList.remove("persona-rounded-full")):(ie.style.borderRadius="",ie.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(ie.style.paddingLeft=xe.closeButtonPaddingX,ie.style.paddingRight=xe.closeButtonPaddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),xe.closeButtonPaddingY?(ie.style.paddingTop=xe.closeButtonPaddingY,ie.style.paddingBottom=xe.closeButtonPaddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let on=(sl=xe.closeButtonIconName)!=null?sl:"x",On=(al=xe.closeButtonIconText)!=null?al:"\xD7";ie.innerHTML="";let pn=pe(on,"20px","currentColor",2);pn?ie.appendChild(pn):ie.textContent=On;let Ft=(il=xe.closeButtonTooltipText)!=null?il:"Close chat",Tn=(ll=xe.closeButtonShowTooltip)!=null?ll:!0;if(ie.setAttribute("aria-label",Ft),ze&&(ze._cleanupTooltip&&(ze._cleanupTooltip(),delete ze._cleanupTooltip),Tn&&Ft)){let Ge=null,Gt=()=>{if(Ge||!ie)return;let Ir=ie.ownerDocument,wo=Ir.body;if(!wo)return;Ge=Un(Ir,"div","persona-clear-chat-tooltip"),Ge.textContent=Ft;let So=Un(Ir,"div");So.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(So);let Pr=ie.getBoundingClientRect();Ge.style.position="fixed",Ge.style.zIndex=String(Cr),Ge.style.left=`${Pr.left+Pr.width/2}px`,Ge.style.top=`${Pr.top-8}px`,Ge.style.transform="translate(-50%, -100%)",wo.appendChild(Ge)},hn=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};ze.addEventListener("mouseenter",Gt),ze.addEventListener("mouseleave",hn),ie.addEventListener("focus",Gt),ie.addEventListener("blur",hn),ze._cleanupTooltip=()=>{hn(),ze&&(ze.removeEventListener("mouseenter",Gt),ze.removeEventListener("mouseleave",hn)),ie&&(ie.removeEventListener("focus",Gt),ie.removeEventListener("blur",hn))}}}let{clearChatButton:Ve,clearChatButtonWrapper:yt}=re;if(Ve){let V=(cl=xe.clearChat)!=null?cl:{},it=(dl=V.enabled)!=null?dl:!0,It=(ul=(pl=n.layout)==null?void 0:pl.header)==null?void 0:ul.showClearChat,ze=It!==void 0?It:it,ct=(gl=V.placement)!=null?gl:"inline";if(yt){yt.style.display=ze?"":"none";let{closeButtonWrapper:Ut}=re;Ut&&!Ut.classList.contains("persona-absolute")&&(ze?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let on=ct==="top-right",On=yt.classList.contains("persona-absolute");if(on!==On&&ze){if(yt.remove(),on)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",_.style.position="relative",_.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Ft=_.querySelector(".persona-border-b-persona-divider"),Tn=re.closeButtonWrapper;Ft&&Tn&&Tn.parentElement===Ft?Ft.insertBefore(yt,Tn):Ft&&Ft.appendChild(yt)}let pn=re.closeButtonWrapper;pn&&!pn.classList.contains("persona-absolute")&&(on?pn.classList.add("persona-ml-auto"):pn.classList.remove("persona-ml-auto"))}}if(ze){let Ut=(ml=V.size)!=null?ml:"32px";Ve.style.height=Ut,Ve.style.width=Ut;let on=(fl=V.iconName)!=null?fl:"refresh-cw",On=(hl=V.iconColor)!=null?hl:"";Ve.style.color=On||bn.actionIconColor,Ve.innerHTML="";let pn=pe(on,"20px","currentColor",2);if(pn&&Ve.appendChild(pn),V.backgroundColor?(Ve.style.backgroundColor=V.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),V.borderWidth||V.borderColor){let Ge=V.borderWidth||"0px",Gt=V.borderColor||"transparent";Ve.style.border=`${Ge} solid ${Gt}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");V.borderRadius?(Ve.style.borderRadius=V.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),V.paddingX?(Ve.style.paddingLeft=V.paddingX,Ve.style.paddingRight=V.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),V.paddingY?(Ve.style.paddingTop=V.paddingY,Ve.style.paddingBottom=V.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Ft=(yl=V.tooltipText)!=null?yl:"Clear chat",Tn=(bl=V.showTooltip)!=null?bl:!0;if(Ve.setAttribute("aria-label",Ft),yt&&(yt._cleanupTooltip&&(yt._cleanupTooltip(),delete yt._cleanupTooltip),Tn&&Ft)){let Ge=null,Gt=()=>{if(Ge||!Ve)return;let Ir=Ve.ownerDocument,wo=Ir.body;if(!wo)return;Ge=Un(Ir,"div","persona-clear-chat-tooltip"),Ge.textContent=Ft;let So=Un(Ir,"div");So.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(So);let Pr=Ve.getBoundingClientRect();Ge.style.position="fixed",Ge.style.zIndex=String(Cr),Ge.style.left=`${Pr.left+Pr.width/2}px`,Ge.style.top=`${Pr.top-8}px`,Ge.style.transform="translate(-50%, -100%)",wo.appendChild(Ge)},hn=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};yt.addEventListener("mouseenter",Gt),yt.addEventListener("mouseleave",hn),Ve.addEventListener("focus",Gt),Ve.addEventListener("blur",hn),yt._cleanupTooltip=()=>{hn(),yt&&(yt.removeEventListener("mouseenter",Gt),yt.removeEventListener("mouseleave",hn)),Ve&&(Ve.removeEventListener("focus",Gt),Ve.removeEventListener("blur",hn))}}}}let In=n.actionParsers&&n.actionParsers.length?n.actionParsers:[_o],fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[$r.message,$r.messageAndClick];M=jo({parsers:In,handlers:fr,getSessionMetadata:u,updateSessionMetadata:h,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),$=id(n,M,se),H.updateConfig(n),Mr(Q,H.getMessages(),$),Bn.render(n.suggestionChips,H,K,void 0,n.suggestionChipsConfig),ho(),Jr(H.isStreaming());let er=((xl=n.voiceRecognition)==null?void 0:xl.enabled)===!0,hr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),tr=((Cl=(vl=n.voiceRecognition)==null?void 0:vl.provider)==null?void 0:Cl.type)==="runtype";if(er&&(hr||tr))if(!O||!Ee){let V=_t(n.voiceRecognition,n.sendButton);V&&(O=V.micButton,Ee=V.micButtonWrapper,tn.insertBefore(Ee,St),O.addEventListener("click",N),O.disabled=H.isStreaming())}else{let V=(wl=n.voiceRecognition)!=null?wl:{},it=(Sl=n.sendButton)!=null?Sl:{},It=(Al=V.iconName)!=null?Al:"mic",ze=(El=it.size)!=null?El:"40px",ct=(Tl=V.iconSize)!=null?Tl:ze,Ut=parseFloat(ct)||24;O.style.width=ct,O.style.height=ct,O.style.minWidth=ct,O.style.minHeight=ct;let on=(kl=(Ml=V.iconColor)!=null?Ml:it.textColor)!=null?kl:"currentColor";O.innerHTML="";let On=pe(It,Ut,on,2);On?O.appendChild(On):O.textContent="\u{1F3A4}";let pn=(Ll=V.backgroundColor)!=null?Ll:it.backgroundColor;pn?O.style.backgroundColor=pn:O.style.backgroundColor="",on?O.style.color=on:O.style.color="var(--persona-text, #111827)",V.borderWidth?(O.style.borderWidth=V.borderWidth,O.style.borderStyle="solid"):(O.style.borderWidth="",O.style.borderStyle=""),V.borderColor?O.style.borderColor=V.borderColor:O.style.borderColor="",V.paddingX?(O.style.paddingLeft=V.paddingX,O.style.paddingRight=V.paddingX):(O.style.paddingLeft="",O.style.paddingRight=""),V.paddingY?(O.style.paddingTop=V.paddingY,O.style.paddingBottom=V.paddingY):(O.style.paddingTop="",O.style.paddingBottom="");let Ft=Ee==null?void 0:Ee.querySelector(".persona-send-button-tooltip"),Tn=(Il=V.tooltipText)!=null?Il:"Start voice recognition";if(((Pl=V.showTooltip)!=null?Pl:!1)&&Tn)if(Ft)Ft.textContent=Tn,Ft.style.display="";else{let Gt=document.createElement("div");Gt.className="persona-send-button-tooltip",Gt.textContent=Tn,Ee==null||Ee.insertBefore(Gt,O)}else Ft&&(Ft.style.display="none");Ee.style.display="",O.disabled=H.isStreaming()}else O&&Ee&&(Ee.style.display="none",((Rl=(Wl=n.voiceRecognition)==null?void 0:Wl.provider)==null?void 0:Rl.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():En&&nt());if(((Hl=n.attachments)==null?void 0:Hl.enabled)===!0)if(!dt||!le){let V=(Bl=n.attachments)!=null?Bl:{},It=(Fl=((Dl=n.sendButton)!=null?Dl:{}).size)!=null?Fl:"40px";G||(G=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),G.style.display="none",st.insertBefore(G,K)),He||(He=document.createElement("input"),He.type="file",He.accept=((Nl=V.allowedTypes)!=null?Nl:rr).join(","),He.multiple=((Ol=V.maxFiles)!=null?Ol:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),st.insertBefore(He,K)),dt=f("div","persona-send-button-wrapper"),le=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",($l=V.buttonTooltipText)!=null?$l:"Attach file");let ze=(_l=V.buttonIconName)!=null?_l:"paperclip",ct=It,Ut=parseFloat(ct)||40,on=Math.round(Ut*.6);le.style.width=ct,le.style.height=ct,le.style.minWidth=ct,le.style.minHeight=ct,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let On=pe(ze,on,"currentColor",1.5);On?le.appendChild(On):le.textContent="\u{1F4CE}",le.addEventListener("click",Tn=>{Tn.preventDefault(),He==null||He.click()}),dt.appendChild(le);let pn=(jl=V.buttonTooltipText)!=null?jl:"Attach file",Ft=f("div","persona-send-button-tooltip");Ft.textContent=pn,dt.appendChild(Ft),Zt.append(dt),!Ne&&He&&G&&(Ne=Fr.fromConfig(V),Ne.setPreviewsContainer(G),He.addEventListener("change",async()=>{Ne&&(He!=null&&He.files)&&(await Ne.handleFileSelect(He.files),He.value="")}))}else{dt.style.display="";let V=(zl=n.attachments)!=null?zl:{};He&&(He.accept=((Vl=V.allowedTypes)!=null?Vl:rr).join(","),He.multiple=((ql=V.maxFiles)!=null?ql:4)>1),Ne&&Ne.updateConfig({allowedTypes:V.allowedTypes,maxFileSize:V.maxFileSize,maxFiles:V.maxFiles})}else dt&&(dt.style.display="none"),Ne&&Ne.clearAttachments();let Vt=(Ul=n.sendButton)!=null?Ul:{},Ko=(Jl=Vt.useIcon)!=null?Jl:!1,vo=(Yl=Vt.iconText)!=null?Yl:"\u2191",Co=Vt.iconName,Gr=(Kl=Vt.tooltipText)!=null?Kl:"Send message",Xo=(Xl=Vt.showTooltip)!=null?Xl:!1,yr=(Gl=Vt.size)!=null?Gl:"40px",Lr=Vt.backgroundColor,Xt=Vt.textColor;if(Ko){if(X.style.width=yr,X.style.height=yr,X.style.minWidth=yr,X.style.minHeight=yr,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Xt?X.style.color=Xt:X.style.color="var(--persona-button-primary-fg, #ffffff)",Co){let V=parseFloat(yr)||24,it=(Xt==null?void 0:Xt.trim())||"currentColor",It=pe(Co,V,it,2);It?X.appendChild(It):X.textContent=vo}else X.textContent=vo;X.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Lr?(X.style.backgroundColor=Lr,X.classList.remove("persona-bg-persona-primary")):(X.style.backgroundColor="",X.classList.add("persona-bg-persona-primary"))}else X.textContent=(Ql=(Zl=n.copy)==null?void 0:Zl.sendButtonLabel)!=null?Ql:"Send",X.style.width="",X.style.height="",X.style.minWidth="",X.style.minHeight="",X.style.fontSize="",X.style.lineHeight="",X.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",Lr?(X.style.backgroundColor=Lr,X.classList.remove("persona-bg-persona-accent")):X.classList.add("persona-bg-persona-accent"),Xt?X.style.color=Xt:X.classList.add("persona-text-white");Vt.borderWidth?(X.style.borderWidth=Vt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),Vt.borderColor?X.style.borderColor=Vt.borderColor:X.style.borderColor="",Vt.paddingX?(X.style.paddingLeft=Vt.paddingX,X.style.paddingRight=Vt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),Vt.paddingY?(X.style.paddingTop=Vt.paddingY,X.style.paddingBottom=Vt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let fn=St==null?void 0:St.querySelector(".persona-send-button-tooltip");if(Xo&&Gr)if(fn)fn.textContent=Gr,fn.style.display="";else{let V=document.createElement("div");V.className="persona-send-button-tooltip",V.textContent=Gr,St==null||St.insertBefore(V,X)}else fn&&(fn.style.display="none");let br=(ec=n.layout)==null?void 0:ec.contentMaxWidth;br?(Q.style.maxWidth=br,Q.style.marginLeft="auto",Q.style.marginRight="auto",Q.style.width="100%",st&&(st.style.maxWidth=br,st.style.marginLeft="auto",st.style.marginRight="auto")):(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight="",Q.style.width="",st&&(st.style.maxWidth="",st.style.marginLeft="",st.style.marginRight=""));let xr=(tc=n.statusIndicator)!=null?tc:{},Ud=(nc=xr.visible)!=null?nc:!0;if(Pt.style.display=Ud?"":"none",H){let V=H.getStatus();Et(Pt,(It=>{var ze,ct,Ut,on;return It==="idle"?(ze=xr.idleText)!=null?ze:sn.idle:It==="connecting"?(ct=xr.connectingText)!=null?ct:sn.connecting:It==="connected"?(Ut=xr.connectedText)!=null?Ut:sn.connected:It==="error"?(on=xr.errorText)!=null?on:sn.error:sn[It]})(V),xr,V)}Pt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Jd=xr.align==="left"?"persona-text-left":xr.align==="center"?"persona-text-center":"persona-text-right";Pt.classList.add(Jd)},open(){b&&kt(!0,"api")},close(){b&&kt(!1,"api")},toggle(){b&&kt(!T,"api")},clearChat(){un=!1,H.clearMessages(),Fn.clear(),gr();try{localStorage.removeItem(po),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${po}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==po)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let g=a.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}i={},M.syncFromMetadata(),J==null||J.clear(),ae==null||ae.update()},setMessage(l){return!K||H.isStreaming()?!1:(!T&&b&&kt(!0,"system"),K.value=l,K.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let g=(l==null?void 0:l.trim())||K.value.trim();return g?(!T&&b&&kt(!0,"system"),K.value="",K.style.height="auto",H.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return H.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!T&&b&&kt(!0,"system"),Ye.manuallyDeactivated=!1,mn(),H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),kn("user"),H.isVoiceActive()&&v()})),!0):En?!0:Z()?(!T&&b&&kt(!0,"system"),Ye.manuallyDeactivated=!1,mn(),qe("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,mn(),kn("user"),A()}),!0):!1:En?(Ye.manuallyDeactivated=!0,mn(),nt("user"),!0):!1},injectMessage(l){return!T&&b&&kt(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!T&&b&&kt(!0,"system");let g=H.injectAssistantMessage(l);return Y&&(Y=!1,ue&&(clearTimeout(ue),ue=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),g},injectUserMessage(l){return!T&&b&&kt(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!T&&b&&kt(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!T&&b&&kt(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!T&&b&&kt(!0,"system"),H.injectTestEvent(l)},async connectStream(l,g){return H.connectStream(l,g)},__pushEventStreamEvent(l){J&&J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ne||!J||Yn()},hideEventStream(){ge&&Rn()},isEventStreamVisible(){return ge},showArtifacts(){Wn(n)&&(un=!1,Cn(),tt==null||tt.setMobileOpen(!0))},hideArtifacts(){Wn(n)&&(un=!0,Cn())},upsertArtifact(l){return Wn(n)?(un=!1,H.upsertArtifact(l)):null},selectArtifact(l){Wn(n)&&H.selectArtifact(l)},clearArtifacts(){Wn(n)&&H.clearArtifacts()},focusInput(){return b&&!T||!K?!1:(K.focus(),!0)},async resolveApproval(l,g){let E=H.getMessages().find(L=>{var I;return L.variant==="approval"&&((I=L.approval)==null?void 0:I.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(E.approval,g)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){h(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&T},isVoiceActive(){return Ye.active},getState(){return{open:b&&T,launcherEnabled:b,voiceActive:Ye.active,streaming:H.isStreaming()}},showCSATFeedback(l){!T&&b&&kt(!0,"system");let g=Q.querySelector(".persona-feedback-container");g&&g.remove();let y=ks({onSubmit:async(E,L)=>{var I;H.isClientTokenMode()&&await H.submitCSATFeedback(E,L),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Q.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&b&&kt(!0,"system");let g=Q.querySelector(".persona-feedback-container");g&&g.remove();let y=Ls({onSubmit:async(E,L)=>{var I;H.isClientTokenMode()&&await H.submitNPSFeedback(E,L),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Q.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return H.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return H.submitNPSFeedback(l,g)},destroy(){xt.forEach(l=>l()),j.remove(),Ue==null||Ue.destroy(),$e==null||$e.remove(),Sn&&ie.removeEventListener("click",Sn)}};if((((ii=t==null?void 0:t.debugTools)!=null?ii:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:Ze,getMessages:Ze.getMessages,getStatus:Ze.getStatus,getMetadata:Ze.getPersistentMetadata,updateMetadata:Ze.updatePersistentMetadata,clearHistory:()=>Ze.clearChat(),setVoiceActive:y=>y?Ze.startVoiceRecognition():Ze.stopVoiceRecognition()};window.AgentWidgetBrowser=g,xt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.focusInput()};if(window.addEventListener("persona:focusInput",g),xt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ne){let q=oe=>{let be=oe.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&Ze.showEventStream()},B=oe=>{let be=oe.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&Ze.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),xt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let y=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.showArtifacts()},E=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.hideArtifacts()},L=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&Ze.upsertArtifact(B.artifact)},I=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&Ze.selectArtifact(B.id)},P=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",P),xt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",P)})}let Bt=ou(n.persistState);if(Bt&&b){let l=su(Bt.storage),g=`${Bt.keyPrefix}widget-open`,y=`${Bt.keyPrefix}widget-voice`,E=`${Bt.keyPrefix}widget-voice-mode`;if(l){let L=((li=Bt.persist)==null?void 0:li.openState)&&l.getItem(g)==="true",I=((ci=Bt.persist)==null?void 0:ci.voiceState)&&l.getItem(y)==="true",P=((di=Bt.persist)==null?void 0:di.voiceState)&&l.getItem(E)==="true";if(L&&setTimeout(()=>{Ze.open(),setTimeout(()=>{var q;if(I||P)Ze.startVoiceRecognition();else if((q=Bt.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(pi=Bt.persist)!=null&&pi.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(ui=Bt.persist)!=null&&ui.voiceState&&(o.on("voice:state",q=>{l.setItem(y,q.active?"true":"false")}),o.on("user:message",q=>{l.setItem(E,q.viaVoice?"true":"false")})),Bt.clearOnChatClear){let q=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},B=()=>q();window.addEventListener("persona:clear-chat",B),xt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return c&&b&&setTimeout(()=>{Ze.open()},0),Ze};var au=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},ld=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},ga=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=""},cd=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",ga(e)},da=e=>{e.style.transition=""},pa=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=""},ua=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ps=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},iu=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},lu=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},dd=(e,r,t,n,s,o,a)=>{var C,M,b,x,S,F;let i=Pn(o),d=i.reveal==="push";iu(e,r,t,n,d),lu(e,r,t,n,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 c=e.ownerDocument.defaultView,p=(M=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileFullscreen)!=null?M:!0,u=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,h=c!=null?c.innerWidth<=u:!1;if(p&&h&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),pa(r),da(n),cd(n),ua(t),Ps(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((F=(S=o==null?void 0:o.launcher)==null?void 0:S.zIndex)!=null?F:yn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),cd(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",pa(r),da(n),ua(t),Ps(s,n);let w=i.animate?"transform 180ms ease":"none",k=i.side==="right"?"translateX(100%)":"translateX(-100%)",R=a?"translateX(0)":k;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=R,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",da(n),ga(n),Ps(s,n);let w=au(i.width,e.clientWidth),k=Math.max(0,e.clientWidth),R=i.animate?"transform 180ms ease":"none",T=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${k+w}px`,r.style.transition=R,r.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${k}px`,t.style.maxWidth=`${k}px`,t.style.minWidth=`${k}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",pa(r),ga(n),ua(t),Ps(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?i.width:"0px",R=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${k}`,n.style.width=k,n.style.maxWidth=k,n.style.minWidth=k,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||T?"hidden":"visible",n.style.transition=R,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},cu=(e,r)=>{let t=e.ownerDocument.createElement("div");return ld(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){ld(t,n)},destroy(){t.remove()}}},du=(e,r)=>{var S,F,w,k;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),u=(F=(S=r==null?void 0:r.launcher)==null?void 0:S.enabled)==null||F?(k=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?k:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),d.appendChild(e);let h=null,m=()=>{h==null||h.disconnect(),h=null},C=()=>{m(),Pn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(h=new ResizeObserver(()=>{dd(a,i,d,c,p,r,u)}),h.observe(a))},M=()=>{dd(a,i,d,c,p,r,u),C()},b=a.ownerDocument.defaultView,x=()=>{M()};return b==null||b.addEventListener("resize",x),Pn(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let T=R.launcherEnabled?R.open:!0;u!==T&&(u=T,M())},updateConfig(R){var T,Y;r=R,((Y=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)!=null?Y:!0)===!1&&(u=!0),M()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},zo=(e,r)=>Jt(r)?du(e,r):cu(e,r);var ma={},pu=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},uu=()=>{try{if(typeof ma!="undefined"&&ma.url)return new URL("../widget.css",ma.url).href}catch{}return null},pd=(e,r)=>{let t=uu(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},fa=e=>{var b;let r=pu(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=zo(r,s),a,i=[],d=(x,S)=>{var R,T;let w=!((T=(R=S==null?void 0:S.launcher)==null?void 0:R.enabled)!=null?T:!0)||Jt(S),k=n.createElement("div");if(k.setAttribute("data-persona-root","true"),w&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),t){let Y=x.attachShadow({mode:"open"});Y.appendChild(k),pd(Y,n)}else x.appendChild(k),pd(x,n);return r.id&&k.setAttribute("data-persona-instance",r.id),k},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let x=d(o.host,s);a=Is(x,s,{debugTools:e.debugTools}),p()},h=()=>{i.forEach(x=>x()),i=[],a.destroy()};u(),(b=e.onReady)==null||b.call(e);let m=x=>{h(),o.destroy(),o=zo(r,x),s=x,u()},C={update(x){var k,R,T,Y,ue,se;let S={...s,...x,launcher:{...(k=s==null?void 0:s.launcher)!=null?k:{},...(R=x==null?void 0:x.launcher)!=null?R:{},dock:{...(Y=(T=s==null?void 0:s.launcher)==null?void 0:T.dock)!=null?Y:{},...(se=(ue=x==null?void 0:x.launcher)==null?void 0:ue.dock)!=null?se:{}}}},F=Jt(s),w=Jt(S);if(F!==w){m(S);return}s=S,o.updateConfig(s),a.update(x),c()},destroy(){h(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},M=new Proxy(C,{get(x,S,F){if(S==="host")return o.host;if(S in x)return Reflect.get(x,S,F);let w=a[S];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=M),M};var hd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),gu=new Set(["button","a","input","select","textarea","details","summary"]),mu=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ha=/\b(product|card|item|listing|result)\b/i,ba=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,fu=3e3,hu=100;function yd(e){let r=typeof e.className=="string"?e.className:"";if(ha.test(r)||e.id&&ha.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&ha.test(n.value))return!0}return!1}function bd(e){var r;return ba.test(((r=e.textContent)!=null?r:"").trim())}function xd(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function yu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ud(e){let r=e.match(ba);return r?r[0]:null}function gd(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function bu(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var xu="commerce-card",vu="result-card";function md(e){return!yd(e)||!bd(e)||!xd(e)&&!yu(e)?0:5200}function fd(e){var n;return!yd(e)||bd(e)||!xd(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xa=[{id:xu,scoreElement(e){return md(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||ba.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,c,p;if(md(e)===0)return null;let{title:t,href:n}=gd(e),s=(p=(c=ud(((d=e.textContent)!=null?d:"").trim()))!=null?c:ud(r.text))!=null?p:"",o=bu(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
97
|
+
`}if(!E&&!l){let Xt="max-height: -moz-available !important; max-height: stretch !important;",fn=g?"":"padding-top: 1.25em !important;",br=g?"":`z-index: ${(Lr=(yr=n.launcher)==null?void 0:yr.zIndex)!=null?Lr:yn} !important;`;j.style.cssText+=Xt+fn+br}};qn(),vr(e,n),vs(e,n),Cs(e,n);let xt=[],Wt=null,Rt=null;xt.push(()=>{Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null}),xn&&xt.push(()=>{xn==null||xn.disconnect(),xn=null}),xt.push(()=>{ln==null||ln(),ln=null,Xn(),bt&&(bt.remove(),bt=null),tt==null||tt.element.style.removeProperty("width"),tt==null||tt.element.style.removeProperty("maxWidth")}),ne&&xt.push(()=>{De!==null&&(cancelAnimationFrame(De),De=null),ae==null||ae.destroy(),ae=null,J==null||J.destroy(),J=null,fe=null});let wn=null,pr=()=>{wn&&(wn(),wn=null),n.colorScheme==="auto"&&(wn=gs(()=>{vr(e,n)}))};pr(),xt.push(()=>{wn&&(wn(),wn=null)});let Bn=Vc(lt),Sn=null,H,Dn=!1,Fn=Hc(),ur=0,gn=ms(),An=0,ee=null,Nn=!1,zr=1,uo=8,Vr=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},go=(ri=(ni=n.voiceRecognition)==null?void 0:ni.autoResume)!=null?ri:!1,kn=l=>{o.emit("voice:state",{active:Ye.active,source:l,timestamp:Date.now()})},mn=()=>{h(l=>({...l,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},Vo=()=>{var E,L;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=ca(i.voiceState),g=!!l.active,y=Number((L=l.timestamp)!=null?L:0);Ye.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<tu&&setTimeout(()=>{var I,P;Ye.active||(Ye.manuallyDeactivated=!1,((P=(I=n.voiceRecognition)==null?void 0:I.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),kn("restore"),H.isVoiceActive()&&v()}):qe("restore"))},1e3)},qo=()=>H?ad(H.getMessages()).filter(l=>!l.__skipPersist):[];function mo(l){if(!(a!=null&&a.save))return;let y={messages:l?ad(l):H?qo():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let Gn=null,Uo=()=>j.querySelector("#persona-scroll-container")||z,qr=()=>{Gn!==null&&(cancelAnimationFrame(Gn),Gn=null),Nn=!1},Ur=()=>{ee!==null&&(cancelAnimationFrame(ee),ee=null),qr()},Zn=()=>{if(!Nt()||ge){at.parentNode&&at.remove(),at.style.display="none";return}at.parentNode!==_&&_.appendChild(at),Je();let l=Wo(z)>0;at.style.display=gn.isFollowing()||!l?"none":""},fo=()=>{gn.pause()&&(Ur(),Zn())},gr=()=>{gn.resume(),Zn()},mr=(l=!1)=>{gn.isFollowing()&&(!l&&!Dn||(Ur(),ee=requestAnimationFrame(()=>{ee=null,gn.isFollowing()&&Jo(Uo(),l?220:140)})))},Jo=(l,g=500)=>{let y=l.scrollTop,E=Wo(l),L=E-y;if(Math.abs(L)<1){An=l.scrollTop;return}qr();let I=performance.now();Nn=!0;let P=B=>1-Math.pow(1-B,3),q=B=>{if(!gn.isFollowing()){qr();return}let oe=Wo(l);oe!==E&&(E=oe,L=E-y);let be=B-I,ve=Math.min(be/g,1),ye=P(ve),je=y+L*ye;l.scrollTop=je,An=l.scrollTop,ve<1?Gn=requestAnimationFrame(q):(l.scrollTop=E,An=l.scrollTop,Gn=null,Nn=!1)};Gn=requestAnimationFrame(q)},Yo=l=>{let g=new Map;l.forEach(y=>{let E=Vr.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!E&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(E!=null&&E.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(E?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Vr.clear(),g.forEach((y,E)=>{Vr.set(E,y)})},Mr=(l,g,y)=>{var be,ve,ye,je;let E=document.createElement("div"),I=(()=>{var Fe;let W=s.find(we=>we.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Fe=n.loadingIndicator)!=null&&Fe.render)return n.loadingIndicator.render})(),P=new Set;g.forEach(W=>{var xe,Qt;P.add(W.id);let Fe=Rc(W,ur),we=Bc(Fn,W.id,Fe);if(we){E.appendChild(we.cloneNode(!0));return}let me=null,We=s.find(ht=>!!(W.variant==="reasoning"&&ht.renderReasoning||W.variant==="tool"&&ht.renderToolCall||W.variant==="approval"&&ht.renderApproval||!W.variant&&ht.renderMessage)),gt=(xe=n.layout)==null?void 0:xe.messages;if(We)if(W.variant==="reasoning"&&W.reasoning&&We.renderReasoning){if(!te)return;me=We.renderReasoning({message:W,defaultRenderer:()=>ta(W),config:n})}else if(W.variant==="tool"&&W.toolCall&&We.renderToolCall){if(!Ae)return;me=We.renderToolCall({message:W,defaultRenderer:()=>na(W,n),config:n})}else if(W.variant==="approval"&&W.approval&&We.renderApproval){if(n.approval===!1)return;me=We.renderApproval({message:W,defaultRenderer:()=>ra(W,n),config:n})}else We.renderMessage&&(me=We.renderMessage({message:W,defaultRenderer:()=>{let ht=so(W,y,gt,n.messageActions,Ie,{loadingIndicatorRenderer:I,widgetConfig:n});return W.role!=="user"&&aa(ht,W,n,H),ht},config:n}));if(!me&&W.role==="assistant"&&!W.variant&&n.enableComponentStreaming!==!1&&Ts(W)){let dn=Ms(W);if(dn){let nn=Es(dn,{config:n,message:W,transform:y});if(nn)if(n.wrapComponentDirectiveInBubble!==!1){let Dt=document.createElement("div");if(Dt.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Dt.id=`bubble-${W.id}`,Dt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Dt.appendChild(pn)}Dt.appendChild(nn),me=Dt}else{let Dt=document.createElement("div");if(Dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Dt.id=`bubble-${W.id}`,Dt.setAttribute("data-message-id",W.id),Dt.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let pn=document.createElement("div");pn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",pn.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Dt.appendChild(pn)}Dt.appendChild(nn),me=Dt}}}if(!me)if(W.variant==="reasoning"&&W.reasoning){if(!te)return;me=ta(W)}else if(W.variant==="tool"&&W.toolCall){if(!Ae)return;me=na(W,n)}else if(W.variant==="approval"&&W.approval){if(n.approval===!1)return;me=ra(W,n)}else{let ht=(Qt=n.layout)==null?void 0:Qt.messages;ht!=null&&ht.renderUserMessage&&W.role==="user"?me=ht.renderUserMessage({message:W,config:n,streaming:!!W.streaming}):ht!=null&&ht.renderAssistantMessage&&W.role==="assistant"?me=ht.renderAssistantMessage({message:W,config:n,streaming:!!W.streaming}):me=so(W,y,ht,n.messageActions,Ie,{loadingIndicatorRenderer:I,widgetConfig:n}),W.role!=="user"&&me&&aa(me,W,n,H)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${W.id}`,Ke.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Ke.classList.add("persona-justify-end"),(me==null?void 0:me.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(me),Dc(Fn,W.id,Fe,Ke),E.appendChild(Ke)}),Fc(Fn,P);let q=g.some(W=>W.role==="assistant"&&W.streaming),B=g[g.length-1],oe=(B==null?void 0:B.role)==="assistant"&&!B.streaming&&B.variant!=="approval";if(Dn&&g.some(W=>W.role==="user")&&!q&&!oe){let W={config:n,streaming:!0,location:"standalone",defaultRenderer:Or},Fe=s.find(me=>me.renderLoadingIndicator),we=null;if(Fe!=null&&Fe.renderLoadingIndicator&&(we=Fe.renderLoadingIndicator(W)),we===null&&((be=n.loadingIndicator)!=null&&be.render)&&(we=n.loadingIndicator.render(W)),we===null&&(we=Or()),we){let me=document.createElement("div"),We=((ve=n.loadingIndicator)==null?void 0:ve.showBubble)!==!1;me.className=We?["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(" "),me.setAttribute("data-typing-indicator","true"),me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",me.appendChild(we);let gt=document.createElement("div");gt.className="persona-flex",gt.id="wrapper-typing-indicator",gt.setAttribute("data-wrapper-id","typing-indicator"),gt.appendChild(me),E.appendChild(gt)}}if(!Dn&&g.length>0){let W=g[g.length-1],Fe={config:n,lastMessage:W,messageCount:g.length},we=s.find(We=>We.renderIdleIndicator),me=null;if(we!=null&&we.renderIdleIndicator&&(me=we.renderIdleIndicator(Fe)),me===null&&((ye=n.loadingIndicator)!=null&&ye.renderIdle)&&(me=n.loadingIndicator.renderIdle(Fe)),me){let We=document.createElement("div"),gt=((je=n.loadingIndicator)==null?void 0:je.showBubble)!==!1;We.className=gt?["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(" "),We.setAttribute("data-idle-indicator","true"),We.appendChild(me);let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id="wrapper-idle-indicator",Ke.setAttribute("data-wrapper-id","idle-indicator"),Ke.appendChild(We),E.appendChild(Ke)}}Wc(l,E)},kr=()=>{var B,oe,be,ve,ye;if(!b)return;let l=Jt(n),g=(B=e.ownerDocument.defaultView)!=null?B:window,y=(be=(oe=n.launcher)==null?void 0:oe.mobileBreakpoint)!=null?be:640,E=(ye=(ve=n.launcher)==null?void 0:ve.mobileFullscreen)!=null?ye:!0,L=g.innerWidth<=y,I=E&&L&&b,P=Pn(n).reveal;T?(j.style.removeProperty("display"),j.style.display=l?"flex":"",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-95","persona-opacity-0"),U.classList.add("persona-scale-100","persona-opacity-100"),Ue?Ue.element.style.display="none":$e&&($e.style.display="none")):(l?l&&(P==="overlay"||P==="push")&&!I?(j.style.removeProperty("display"),j.style.display="flex",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.setProperty("display","none","important"),j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.display="",j.classList.add("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100"),U.classList.add("persona-scale-95","persona-opacity-0")),Ue?Ue.element.style.display=l?"none":"":$e&&($e.style.display=l?"none":""))},kt=(l,g="user")=>{var I,P;if(!b||T===l)return;let y=T;T=l,kr();let E=(()=>{var je,W,Fe,we,me,We,gt;let q=(W=(je=n.launcher)==null?void 0:je.sidebarMode)!=null?W:!1,B=(Fe=e.ownerDocument.defaultView)!=null?Fe:window,oe=(me=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?me:!0,be=(gt=(We=n.launcher)==null?void 0:We.mobileBreakpoint)!=null?gt:640,ve=B.innerWidth<=be,ye=Jt(n)&&oe&&ve;return q||oe&&ve&&b||ye})();if(T&&E){if(!Wt){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(Wt=Ys(B,(P=(I=n.launcher)==null?void 0:I.zIndex)!=null?P:yn))}Rt||(Rt=Ks(e.ownerDocument))}else T||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null);T&&(Ht(),mr(!0));let L={open:T,source:g,timestamp:Date.now()};T&&!y?o.emit("widget:opened",L):!T&&y&&o.emit("widget:closed",L),o.emit("widget:state",{open:T,launcherEnabled:b,voiceActive:Ye.active,streaming:H.isStreaming()})},Jr=l=>{X.disabled=l,O&&(O.disabled=l),Bn.buttons.forEach(g=>{g.disabled=l}),et.dataset.personaComposerStreaming=l?"true":"false",et.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Yr=()=>{Ye.active||K&&K.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Yr(),200)});let ho=()=>{var y,E,L,I,P,q,B,oe,be,ve,ye;Yt.textContent=(E=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?E:"Hello \u{1F44B}",Be.textContent=(I=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",K.placeholder=(q=(P=n.copy)==null?void 0:P.inputPlaceholder)!=null?q:"How can I help...";let l=z.querySelector("[data-persona-intro-card]");if(l){let je=((B=n.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=je?"":"none",je?(z.classList.remove("persona-gap-3"),z.classList.add("persona-gap-6")):(z.classList.remove("persona-gap-6"),z.classList.add("persona-gap-3"))}(be=(oe=n.sendButton)==null?void 0:oe.useIcon)!=null&&be||(X.textContent=(ye=(ve=n.copy)==null?void 0:ve.sendButtonLabel)!=null?ye:"Send"),K.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',K.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};if(n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{h(g=>({...g,sessionId:l}))}}),H=new to(n,{onMessagesChanged(l){Mr(Q,l,$),H&&(l.some(L=>L.role==="user")?Bn.render([],H,K,l):Bn.render(n.suggestionChips,H,K,l,n.suggestionChipsConfig)),mr(!Dn),Yo(l);let g=[...l].reverse().find(E=>E.role==="user"),y=Ye.lastUserMessageId;g&&g.id!==y&&(Ye.lastUserMessageId=g.id,o.emit("user:message",g)),Ye.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),mo(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{};Et(Pt,(L=>{var I,P,q,B;return L==="idle"?(I=g.idleText)!=null?I:sn.idle:L==="connecting"?(P=g.connectingText)!=null?P:sn.connecting:L==="connected"?(q=g.connectedText)!=null?q:sn.connected:L==="error"?(B=g.errorText)!=null?B:sn.error:sn[L]})(l),g,l)},onStreamingChanged(l){Dn=l,Jr(l),H&&Mr(Q,H.getMessages(),$),l||mr(!0)},onVoiceStatusChanged(l){var g,y;if(((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":A(),_e();break;case"speaking":A(),D();break;default:l==="idle"&&H.isBargeInActive()?(A(),v(),O==null||O.setAttribute("aria-label","End voice session")):(Ye.active=!1,A(),kn("system"),mn());break}},onArtifactsState(l){Hn=l,Cn()}}),lr.current=H,((si=(oi=n.voiceRecognition)==null?void 0:oi.provider)==null?void 0:si.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&H.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),J&&H.setSSEEventCallback((l,g)=>{J==null||J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),d&&d.then(l=>{var g;l&&(l.metadata&&(i=ca(l.metadata),M.syncFromMetadata()),(g=l.messages)!=null&&g.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let yo=l=>{var L;l.preventDefault();let g=K.value.trim(),y=(L=Ne==null?void 0:Ne.hasAttachments())!=null?L:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(...Ne.getContentParts()),g&&E.push(ss(g))),K.value="",K.style.height="auto",H.sendMessage(g,{contentParts:E}),y&&Ne.clearAttachments()},bo=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},xo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!Ne)return;let g=ru(l.clipboardData);g.length!==0&&(l.preventDefault(),await Ne.handleFiles(g))},cn=null,En=!1,Qn=null,Oe=null,Z=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qe=(l="user")=>{var I,P,q,B,oe,be,ve;if(En||H.isStreaming())return;let g=Z();if(!g)return;cn=new g;let E=(P=((I=n.voiceRecognition)!=null?I:{}).pauseDuration)!=null?P:2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let L=K.value;cn.onresult=ye=>{let je="",W="";for(let we=0;we<ye.results.length;we++){let me=ye.results[we],We=me[0].transcript;me.isFinal?je+=We+" ":W=We}let Fe=L+je+W;K.value=Fe,Qn&&clearTimeout(Qn),(je||W)&&(Qn=window.setTimeout(()=>{let we=K.value.trim();we&&cn&&En&&(nt(),K.value="",K.style.height="auto",H.sendMessage(we,{viaVoice:!0}))},E))},cn.onerror=ye=>{ye.error!=="no-speech"&&nt()},cn.onend=()=>{if(En){let ye=K.value.trim();ye&&ye!==L.trim()&&(K.value="",K.style.height="auto",H.sendMessage(ye,{viaVoice:!0})),nt()}};try{if(cn.start(),En=!0,Ye.active=!0,l!=="system"&&(Ye.manuallyDeactivated=!1),kn(l),mn(),O){let ye=(q=n.voiceRecognition)!=null?q:{};Oe={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(B=ye.iconName)!=null?B:"mic",iconSize:parseFloat((ve=(be=ye.iconSize)!=null?be:(oe=n.sendButton)==null?void 0:oe.size)!=null?ve:"40")||24};let je=ye.recordingBackgroundColor,W=ye.recordingIconColor,Fe=ye.recordingBorderColor;if(O.classList.add("persona-voice-recording"),O.style.backgroundColor=je!=null?je:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=W!=null?W:"var(--persona-voice-recording-indicator, #ffffff)",W){let we=O.querySelector("svg");we&&we.setAttribute("stroke",W)}Fe&&(O.style.borderColor=Fe),O.setAttribute("aria-label","Stop voice recognition")}}catch{nt("system")}},nt=(l="user")=>{if(En){if(En=!1,Qn&&(clearTimeout(Qn),Qn=null),cn){try{cn.stop()}catch{}cn=null}if(Ye.active=!1,kn(l),mn(),O){if(O.classList.remove("persona-voice-recording"),Oe){O.style.backgroundColor=Oe.backgroundColor,O.style.color=Oe.color,O.style.borderColor=Oe.borderColor;let g=O.querySelector("svg");g&&g.setAttribute("stroke",Oe.color||"currentColor"),Oe=null}O.setAttribute("aria-label","Start voice recognition")}}},_t=(l,g)=>{var me,We,gt,Ke,xe,Qt,ht,dn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((me=l==null?void 0:l.provider)==null?void 0:me.type)==="runtype";if(!(y||E))return null;let I=f("div","persona-send-button-wrapper"),P=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");P.type="button",P.setAttribute("aria-label","Start voice recognition");let q=(We=l==null?void 0:l.iconName)!=null?We:"mic",B=(gt=g==null?void 0:g.size)!=null?gt:"40px",oe=(Ke=l==null?void 0:l.iconSize)!=null?Ke:B,be=parseFloat(oe)||24,ve=(xe=l==null?void 0:l.backgroundColor)!=null?xe:g==null?void 0:g.backgroundColor,ye=(Qt=l==null?void 0:l.iconColor)!=null?Qt:g==null?void 0:g.textColor;P.style.width=oe,P.style.height=oe,P.style.minWidth=oe,P.style.minHeight=oe,P.style.fontSize="18px",P.style.lineHeight="1",ye?P.style.color=ye:P.style.color="var(--persona-text, #111827)";let W=pe(q,be,ye||"currentColor",1.5);W?P.appendChild(W):P.textContent="\u{1F3A4}",ve?P.style.backgroundColor=ve:P.style.backgroundColor="",l!=null&&l.borderWidth&&(P.style.borderWidth=l.borderWidth,P.style.borderStyle="solid"),l!=null&&l.borderColor&&(P.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(P.style.paddingLeft=l.paddingX,P.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(P.style.paddingTop=l.paddingY,P.style.paddingBottom=l.paddingY),I.appendChild(P);let Fe=(ht=l==null?void 0:l.tooltipText)!=null?ht:"Start voice recognition";if(((dn=l==null?void 0:l.showTooltip)!=null?dn:!1)&&Fe){let nn=f("div","persona-send-button-tooltip");nn.textContent=Fe,I.appendChild(nn)}return{micButton:P,micButtonWrapper:I}},jt=()=>{var g,y,E,L,I;if(!O||Oe)return;let l=(g=n.voiceRecognition)!=null?g:{};Oe={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((I=(L=l.iconSize)!=null?L:(E=n.sendButton)==null?void 0:E.size)!=null?I:"40")||24}},Kt=(l,g)=>{var I,P,q,B,oe;if(!O)return;let y=O.querySelector("svg");y&&y.remove();let E=(oe=Oe==null?void 0:Oe.iconSize)!=null?oe:parseFloat((B=(q=(I=n.voiceRecognition)==null?void 0:I.iconSize)!=null?q:(P=n.sendButton)==null?void 0:P.size)!=null?B:"40")||24,L=pe(l,E,g,1.5);L&&O.appendChild(L)},Lt=()=>{O&&O.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},v=()=>{var L;if(!O)return;jt();let l=(L=n.voiceRecognition)!=null?L:{},g=l.recordingBackgroundColor,y=l.recordingIconColor,E=l.recordingBorderColor;if(Lt(),O.classList.add("persona-voice-recording"),O.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let I=O.querySelector("svg");I&&I.setAttribute("stroke",y)}E&&(O.style.borderColor=E),O.setAttribute("aria-label","Stop voice recognition")},_e=()=>{var q,B,oe,be,ve,ye,je,W;if(!O)return;jt();let l=(q=n.voiceRecognition)!=null?q:{},g=H.getVoiceInterruptionMode(),y=(B=l.processingIconName)!=null?B:"loader",E=(be=(oe=l.processingIconColor)!=null?oe:Oe==null?void 0:Oe.color)!=null?be:"",L=(ye=(ve=l.processingBackgroundColor)!=null?ve:Oe==null?void 0:Oe.backgroundColor)!=null?ye:"",I=(W=(je=l.processingBorderColor)!=null?je:Oe==null?void 0:Oe.borderColor)!=null?W:"";Lt(),O.classList.add("persona-voice-processing"),O.style.backgroundColor=L,O.style.borderColor=I;let P=E||"currentColor";O.style.color=P,Kt(y,P),O.setAttribute("aria-label","Processing voice input"),g==="none"&&(O.style.cursor="default")},D=()=>{var oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke;if(!O)return;jt();let l=(oe=n.voiceRecognition)!=null?oe:{},g=H.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(be=l.speakingIconName)!=null?be:y,L=(W=l.speakingIconColor)!=null?W:g==="barge-in"?(ye=(ve=l.recordingIconColor)!=null?ve:Oe==null?void 0:Oe.color)!=null?ye:"":(je=Oe==null?void 0:Oe.color)!=null?je:"",I=(me=l.speakingBackgroundColor)!=null?me:g==="barge-in"?(Fe=l.recordingBackgroundColor)!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)":(we=Oe==null?void 0:Oe.backgroundColor)!=null?we:"",P=(Ke=l.speakingBorderColor)!=null?Ke:g==="barge-in"?(We=l.recordingBorderColor)!=null?We:"":(gt=Oe==null?void 0:Oe.borderColor)!=null?gt:"";Lt(),O.classList.add("persona-voice-speaking"),O.style.backgroundColor=I,O.style.borderColor=P;let q=L||"currentColor";O.style.color=q,Kt(E,q);let B=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";O.setAttribute("aria-label",B),g==="none"&&(O.style.cursor="default"),g==="barge-in"&&O.classList.add("persona-voice-recording")},A=()=>{var l,g,y;O&&(Lt(),Oe&&(O.style.backgroundColor=(l=Oe.backgroundColor)!=null?l:"",O.style.color=(g=Oe.color)!=null?g:"",O.style.borderColor=(y=Oe.borderColor)!=null?y:"",Kt(Oe.iconName,Oe.color||"currentColor"),Oe=null),O.style.cursor="",O.setAttribute("aria-label","Start voice recognition"))},N=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=H.getVoiceStatus(),E=H.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,mn(),kn("user"),A()});return}H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),Ye.manuallyDeactivated=!H.isVoiceActive(),mn(),kn("user"),H.isVoiceActive()?v():A()});return}if(En){let y=K.value.trim();Ye.manuallyDeactivated=!0,mn(),nt("user"),y&&(K.value="",K.style.height="auto",H.sendMessage(y))}else Ye.manuallyDeactivated=!1,mn(),qe("user")};$t=N,O&&(O.addEventListener("click",N),xt.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),A()):nt("system"),O&&O.removeEventListener("click",N)}));let ce=o.on("assistant:complete",()=>{go&&(Ye.active||Ye.manuallyDeactivated||go==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!Ye.active&&!Ye.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),kn("auto"),H.isVoiceActive()&&v()}):qe("auto"))},600))});xt.push(ce);let Te=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});xt.push(Te);let rt=()=>{kt(!T,"user")},Ue=null,$e=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>Bo(n,rt).element,onToggle:rt});g&&($e=g)}$e||(Ue=Bo(n,rt))}Ue?e.appendChild(Ue.element):$e&&e.appendChild($e),kr(),Bn.render(n.suggestionChips,H,K,void 0,n.suggestionChipsConfig),ho(),Jr(H.isStreaming()),mr(!0),Vo(),S&&(b?T&&setTimeout(()=>Yr(),200):setTimeout(()=>Yr(),0));let Ht=()=>{var B,oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke,xe,Qt,ht,dn,nn,rn,Dt,pn,Ve;let l=Jt(n),g=(oe=(B=n.launcher)==null?void 0:B.sidebarMode)!=null?oe:!1,y=l||g||((ve=(be=n.launcher)==null?void 0:be.fullHeight)!=null?ve:!1),E=(ye=e.ownerDocument.defaultView)!=null?ye:window,L=(W=(je=n.launcher)==null?void 0:je.mobileFullscreen)!=null?W:!0,I=(we=(Fe=n.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?we:640,P=E.innerWidth<=I,q=L&&P&&b;try{if(q){qn(),vr(e,n);return}if(R&&(R=!1,qn(),vr(e,n)),!b&&!l){U.style.height="",U.style.width="";return}if(!g&&!l){let yt=(We=(me=n==null?void 0:n.launcher)==null?void 0:me.width)!=null?We:n==null?void 0:n.launcherWidth,In=yt!=null?yt:"min(400px, calc(100vw - 24px))";U.style.width=In,U.style.maxWidth=In}if(Vn(),!y){let yt=E.innerHeight,In=64,fr=(Ke=(gt=n.launcher)==null?void 0:gt.heightOffset)!=null?Ke:0,er=Math.max(200,yt-In),hr=Math.min(640,er),tr=Math.max(200,hr-fr);U.style.height=`${tr}px`}}finally{if(Je(),kr(),T&&b){let In=((xe=e.ownerDocument.defaultView)!=null?xe:window).innerWidth<=((ht=(Qt=n.launcher)==null?void 0:Qt.mobileBreakpoint)!=null?ht:640),fr=(nn=(dn=n.launcher)==null?void 0:dn.sidebarMode)!=null?nn:!1,er=(Dt=(rn=n.launcher)==null?void 0:rn.mobileFullscreen)!=null?Dt:!0,hr=Jt(n)&&er&&In,tr=fr||er&&In&&b||hr;if(tr&&!Rt){let Kr=e.getRootNode(),Xr=Kr instanceof ShadowRoot?Kr.host:e.closest(".persona-host");Xr&&!Wt&&(Wt=Ys(Xr,(Ve=(pn=n.launcher)==null?void 0:pn.zIndex)!=null?Ve:yn)),Rt=Ks(e.ownerDocument)}else tr||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null)}}};Ht();let qt=(ai=e.ownerDocument.defaultView)!=null?ai:window;if(qt.addEventListener("resize",Ht),xt.push(()=>qt.removeEventListener("resize",Ht)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Je()});l.observe(et),xt.push(()=>l.disconnect())}An=z.scrollTop;let ft=()=>{let l=z.scrollTop,{action:g,nextLastScrollTop:y}=fs({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:An,nearBottom:Ro(z,uo),userScrollThreshold:zr,isAutoScrolling:Nn,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=y,g==="resume"){gr();return}g==="pause"&&fo()};z.addEventListener("scroll",ft,{passive:!0}),xt.push(()=>z.removeEventListener("scroll",ft));let vt=l=>{let g=hs({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:Ro(z,uo),resumeWhenNearBottom:!0});g==="pause"?fo():g==="resume"&&gr()};z.addEventListener("wheel",vt,{passive:!0}),xt.push(()=>z.removeEventListener("wheel",vt)),at.addEventListener("click",()=>{z.scrollTop=z.scrollHeight,An=z.scrollTop,gr(),mr(!0)}),xt.push(()=>at.remove()),xt.push(()=>{Ur()});let zt=()=>{ie&&(Sn&&(ie.removeEventListener("click",Sn),Sn=null),b?(ie.style.display="",Sn=()=>{kt(!1,"user")},ie.addEventListener("click",Sn)):ie.style.display="none")};zt(),(()=>{let{clearChatButton:l}=re;l&&l.addEventListener("click",()=>{H.clearMessages(),Fn.clear(),gr();try{localStorage.removeItem(po),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${po}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==po)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},M.syncFromMetadata(),J==null||J.clear(),ae==null||ae.update()})})(),st&&st.addEventListener("submit",yo),K==null||K.addEventListener("keydown",bo),K==null||K.addEventListener("paste",xo),xt.push(()=>{st&&st.removeEventListener("submit",yo),K==null||K.removeEventListener("keydown",bo),K==null||K.removeEventListener("paste",xo)}),xt.push(()=>{H.cancel()}),Ue?xt.push(()=>{Ue==null||Ue.destroy()}):$e&&xt.push(()=>{$e==null||$e.remove()});let Ze={update(l){var gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Fi,Ni,Oi,$i,_i,ji,zi,Vi,qi,Ui,Ji,Yi,Ki,Xi,Gi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,gl,ml,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Fl,Nl,Ol,$l,_l,jl,zl,Vl,ql,Ul,Jl,Yl,Kl,Xl,Gl,Zl,Ql,ec,tc,nc;let g=n.toolCall,y=n.messageActions,E=(gi=n.layout)==null?void 0:gi.messages,L=n.colorScheme,I=n.loadingIndicator,P=n.iterationDisplay;n={...n,...l},qn(),vr(e,n),vs(e,n),Cs(e,n),Cn(),n.colorScheme!==L&&pr();let q=$o.getForInstance(n.plugins);s.length=0,s.push(...q),b=(fi=(mi=n.launcher)==null?void 0:mi.enabled)!=null?fi:!0,x=(yi=(hi=n.launcher)==null?void 0:hi.autoExpand)!=null?yi:!1,te=(xi=(bi=n.features)==null?void 0:bi.showReasoning)!=null?xi:!0,Ae=(Ci=(vi=n.features)==null?void 0:vi.showToolCalls)!=null?Ci:!0,Ce=(Si=(wi=n.features)==null?void 0:wi.scrollToBottom)!=null?Si:{},ut(),Zn();let B=ne;if(ne=(Ei=(Ai=n.features)==null?void 0:Ai.showEventStreamToggle)!=null?Ei:!1,ne&&!B){if(J||(fe=new Oo(de),J=new No(Se,fe),fe.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),H.setSSEEventCallback((V,it)=>{J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:V,timestamp:Date.now(),payload:JSON.stringify(it)})})),!Xe&&Qe){let V=(Mi=(Ti=n.features)==null?void 0:Ti.eventStream)==null?void 0:Mi.classNames,it="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"+(V!=null&&V.toggleButton?" "+V.toggleButton:"");Xe=f("button",it),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let It=pe("activity","18px","currentColor",1.5);It&&Xe.appendChild(It);let ze=re.clearChatButtonWrapper,ct=re.closeButtonWrapper,Ut=ze||ct;Ut&&Ut.parentNode===Qe?Qe.insertBefore(Xe,Ut):Qe.appendChild(Xe),Xe.addEventListener("click",()=>{ge?Rn():Yn()})}}else!ne&&B&&(Rn(),Xe&&(Xe.remove(),Xe=null),J==null||J.clear(),fe==null||fe.destroy(),J=null,fe=null);if(((ki=n.launcher)==null?void 0:ki.enabled)===!1&&Ue&&(Ue.destroy(),Ue=null),((Li=n.launcher)==null?void 0:Li.enabled)===!1&&$e&&($e.remove(),$e=null),((Ii=n.launcher)==null?void 0:Ii.enabled)!==!1&&!Ue&&!$e){let V=s.find(it=>it.renderLauncher);if(V!=null&&V.renderLauncher){let it=V.renderLauncher({config:n,defaultRenderer:()=>Bo(n,rt).element,onToggle:rt});it&&($e=it,e.appendChild($e))}$e||(Ue=Bo(n,rt),e.appendChild(Ue.element))}Ue&&Ue.update(n),Tt&&((Pi=n.launcher)==null?void 0:Pi.title)!==void 0&&(Tt.textContent=n.launcher.title),Mt&&((Wi=n.launcher)==null?void 0:Wi.subtitle)!==void 0&&(Mt.textContent=n.launcher.subtitle);let oe=(Ri=n.layout)==null?void 0:Ri.header;if((oe==null?void 0:oe.layout)!==k&&Qe){let V=oe?ro(n,oe,{showClose:b,onClose:()=>kt(!1,"user")}):or({config:n,showClose:b,onClose:()=>kt(!1,"user")});Qe.replaceWith(V.header),Qe=V.header,ke=V.iconHolder,Tt=V.headerTitle,Mt=V.headerSubtitle,ie=V.closeButton,k=oe==null?void 0:oe.layout}else if(oe&&(ke&&(ke.style.display=oe.showIcon===!1?"none":""),Tt&&(Tt.style.display=oe.showTitle===!1?"none":""),Mt&&(Mt.style.display=oe.showSubtitle===!1?"none":""),ie&&(ie.style.display=oe.showCloseButton===!1?"none":""),re.clearChatButtonWrapper)){let V=oe.showClearChat;if(V!==void 0){re.clearChatButtonWrapper.style.display=V?"":"none";let{closeButtonWrapper:it}=re;it&&!it.classList.contains("persona-absolute")&&(V?it.classList.remove("persona-ml-auto"):it.classList.add("persona-ml-auto"))}}let ve=((Hi=n.layout)==null?void 0:Hi.showHeader)!==!1;Qe&&(Qe.style.display=ve?"":"none");let ye=((Bi=n.layout)==null?void 0:Bi.showFooter)!==!1;et&&(et.style.display=ye?"":"none"),Je(),Zn(),b!==w?b?kt(x,"auto"):(T=!0,kr()):x!==F&&kt(x,"auto"),F=x,w=b,Ht(),zt();let Fe=JSON.stringify(l.toolCall)!==JSON.stringify(g),we=JSON.stringify(n.messageActions)!==JSON.stringify(y),me=JSON.stringify((Di=n.layout)==null?void 0:Di.messages)!==JSON.stringify(E),We=((Fi=n.loadingIndicator)==null?void 0:Fi.render)!==(I==null?void 0:I.render)||((Ni=n.loadingIndicator)==null?void 0:Ni.renderIdle)!==(I==null?void 0:I.renderIdle)||((Oi=n.loadingIndicator)==null?void 0:Oi.showBubble)!==(I==null?void 0:I.showBubble),gt=n.iterationDisplay!==P;(Fe||we||me||We||gt)&&H&&(ur++,Mr(Q,H.getMessages(),$));let xe=($i=n.launcher)!=null?$i:{},Qt=(_i=xe.headerIconHidden)!=null?_i:!1,ht=(zi=(ji=n.layout)==null?void 0:ji.header)==null?void 0:zi.showIcon,dn=Qt||ht===!1,nn=xe.headerIconName,rn=(Vi=xe.headerIconSize)!=null?Vi:"48px";if(ke){let V=_.querySelector(".persona-border-b-persona-divider"),it=V==null?void 0:V.querySelector(".persona-flex-col");if(dn)ke.style.display="none",V&&it&&!V.contains(it)&&V.insertBefore(it,V.firstChild);else{if(ke.style.display="",ke.style.height=rn,ke.style.width=rn,V&&it&&(V.contains(ke)?ke.nextSibling!==it&&(ke.remove(),V.insertBefore(ke,it)):V.insertBefore(ke,it)),nn){let ze=parseFloat(rn)||24,ct=pe(nn,ze*.6,"#ffffff",2);ct?ke.replaceChildren(ct):ke.textContent=(qi=xe.agentIconText)!=null?qi:"\u{1F4AC}"}else if(xe.iconUrl){let ze=ke.querySelector("img");if(ze)ze.src=xe.iconUrl,ze.style.height=rn,ze.style.width=rn;else{let ct=document.createElement("img");ct.src=xe.iconUrl,ct.alt="",ct.className="persona-rounded-xl persona-object-cover",ct.style.height=rn,ct.style.width=rn,ke.replaceChildren(ct)}}else{let ze=ke.querySelector("svg"),ct=ke.querySelector("img");(ze||ct)&&ke.replaceChildren(),ke.textContent=(Ui=xe.agentIconText)!=null?Ui:"\u{1F4AC}"}let It=ke.querySelector("img");It&&(It.style.height=rn,It.style.width=rn)}}let Dt=(Yi=(Ji=n.layout)==null?void 0:Ji.header)==null?void 0:Yi.showTitle,pn=(Xi=(Ki=n.layout)==null?void 0:Ki.header)==null?void 0:Xi.showSubtitle;if(Tt&&(Tt.style.display=Dt===!1?"none":""),Mt&&(Mt.style.display=pn===!1?"none":""),ie){((Zi=(Gi=n.layout)==null?void 0:Gi.header)==null?void 0:Zi.showCloseButton)===!1?ie.style.display="none":ie.style.display="";let it=(Qi=xe.closeButtonSize)!=null?Qi:"32px",It=(el=xe.closeButtonPlacement)!=null?el:"inline";ie.style.height=it,ie.style.width=it;let{closeButtonWrapper:ze}=re,ct=It==="top-right",Ut=ze==null?void 0:ze.classList.contains("persona-absolute");if(ze&&ct!==Ut)if(ze.remove(),ct)ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",_.style.position="relative",_.appendChild(ze);else{let Ge=(nl=(tl=xe.clearChat)==null?void 0:tl.placement)!=null?nl:"inline",Gt=(ol=(rl=xe.clearChat)==null?void 0:rl.enabled)!=null?ol:!0;ze.className=Gt&&Ge==="inline"?"":"persona-ml-auto";let hn=_.querySelector(".persona-border-b-persona-divider");hn&&hn.appendChild(ze)}if(ie.style.color=xe.closeButtonColor||bn.actionIconColor,xe.closeButtonBackgroundColor?(ie.style.backgroundColor=xe.closeButtonBackgroundColor,ie.classList.remove("hover:persona-bg-gray-100")):(ie.style.backgroundColor="",ie.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let Ge=xe.closeButtonBorderWidth||"0px",Gt=xe.closeButtonBorderColor||"transparent";ie.style.border=`${Ge} solid ${Gt}`,ie.classList.remove("persona-border-none")}else ie.style.border="",ie.classList.add("persona-border-none");xe.closeButtonBorderRadius?(ie.style.borderRadius=xe.closeButtonBorderRadius,ie.classList.remove("persona-rounded-full")):(ie.style.borderRadius="",ie.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(ie.style.paddingLeft=xe.closeButtonPaddingX,ie.style.paddingRight=xe.closeButtonPaddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),xe.closeButtonPaddingY?(ie.style.paddingTop=xe.closeButtonPaddingY,ie.style.paddingBottom=xe.closeButtonPaddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let on=(sl=xe.closeButtonIconName)!=null?sl:"x",On=(al=xe.closeButtonIconText)!=null?al:"\xD7";ie.innerHTML="";let un=pe(on,"20px","currentColor",2);un?ie.appendChild(un):ie.textContent=On;let Ft=(il=xe.closeButtonTooltipText)!=null?il:"Close chat",Tn=(ll=xe.closeButtonShowTooltip)!=null?ll:!0;if(ie.setAttribute("aria-label",Ft),ze&&(ze._cleanupTooltip&&(ze._cleanupTooltip(),delete ze._cleanupTooltip),Tn&&Ft)){let Ge=null,Gt=()=>{if(Ge||!ie)return;let Ir=ie.ownerDocument,wo=Ir.body;if(!wo)return;Ge=Un(Ir,"div","persona-clear-chat-tooltip"),Ge.textContent=Ft;let So=Un(Ir,"div");So.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(So);let Pr=ie.getBoundingClientRect();Ge.style.position="fixed",Ge.style.zIndex=String(Cr),Ge.style.left=`${Pr.left+Pr.width/2}px`,Ge.style.top=`${Pr.top-8}px`,Ge.style.transform="translate(-50%, -100%)",wo.appendChild(Ge)},hn=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};ze.addEventListener("mouseenter",Gt),ze.addEventListener("mouseleave",hn),ie.addEventListener("focus",Gt),ie.addEventListener("blur",hn),ze._cleanupTooltip=()=>{hn(),ze&&(ze.removeEventListener("mouseenter",Gt),ze.removeEventListener("mouseleave",hn)),ie&&(ie.removeEventListener("focus",Gt),ie.removeEventListener("blur",hn))}}}let{clearChatButton:Ve,clearChatButtonWrapper:yt}=re;if(Ve){let V=(cl=xe.clearChat)!=null?cl:{},it=(dl=V.enabled)!=null?dl:!0,It=(ul=(pl=n.layout)==null?void 0:pl.header)==null?void 0:ul.showClearChat,ze=It!==void 0?It:it,ct=(gl=V.placement)!=null?gl:"inline";if(yt){yt.style.display=ze?"":"none";let{closeButtonWrapper:Ut}=re;Ut&&!Ut.classList.contains("persona-absolute")&&(ze?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let on=ct==="top-right",On=yt.classList.contains("persona-absolute");if(on!==On&&ze){if(yt.remove(),on)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",_.style.position="relative",_.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Ft=_.querySelector(".persona-border-b-persona-divider"),Tn=re.closeButtonWrapper;Ft&&Tn&&Tn.parentElement===Ft?Ft.insertBefore(yt,Tn):Ft&&Ft.appendChild(yt)}let un=re.closeButtonWrapper;un&&!un.classList.contains("persona-absolute")&&(on?un.classList.add("persona-ml-auto"):un.classList.remove("persona-ml-auto"))}}if(ze){let Ut=(ml=V.size)!=null?ml:"32px";Ve.style.height=Ut,Ve.style.width=Ut;let on=(fl=V.iconName)!=null?fl:"refresh-cw",On=(hl=V.iconColor)!=null?hl:"";Ve.style.color=On||bn.actionIconColor,Ve.innerHTML="";let un=pe(on,"20px","currentColor",2);if(un&&Ve.appendChild(un),V.backgroundColor?(Ve.style.backgroundColor=V.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),V.borderWidth||V.borderColor){let Ge=V.borderWidth||"0px",Gt=V.borderColor||"transparent";Ve.style.border=`${Ge} solid ${Gt}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");V.borderRadius?(Ve.style.borderRadius=V.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),V.paddingX?(Ve.style.paddingLeft=V.paddingX,Ve.style.paddingRight=V.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),V.paddingY?(Ve.style.paddingTop=V.paddingY,Ve.style.paddingBottom=V.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Ft=(yl=V.tooltipText)!=null?yl:"Clear chat",Tn=(bl=V.showTooltip)!=null?bl:!0;if(Ve.setAttribute("aria-label",Ft),yt&&(yt._cleanupTooltip&&(yt._cleanupTooltip(),delete yt._cleanupTooltip),Tn&&Ft)){let Ge=null,Gt=()=>{if(Ge||!Ve)return;let Ir=Ve.ownerDocument,wo=Ir.body;if(!wo)return;Ge=Un(Ir,"div","persona-clear-chat-tooltip"),Ge.textContent=Ft;let So=Un(Ir,"div");So.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(So);let Pr=Ve.getBoundingClientRect();Ge.style.position="fixed",Ge.style.zIndex=String(Cr),Ge.style.left=`${Pr.left+Pr.width/2}px`,Ge.style.top=`${Pr.top-8}px`,Ge.style.transform="translate(-50%, -100%)",wo.appendChild(Ge)},hn=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};yt.addEventListener("mouseenter",Gt),yt.addEventListener("mouseleave",hn),Ve.addEventListener("focus",Gt),Ve.addEventListener("blur",hn),yt._cleanupTooltip=()=>{hn(),yt&&(yt.removeEventListener("mouseenter",Gt),yt.removeEventListener("mouseleave",hn)),Ve&&(Ve.removeEventListener("focus",Gt),Ve.removeEventListener("blur",hn))}}}}let In=n.actionParsers&&n.actionParsers.length?n.actionParsers:[_o],fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[$r.message,$r.messageAndClick];M=jo({parsers:In,handlers:fr,getSessionMetadata:u,updateSessionMetadata:h,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),$=id(n,M,se),H.updateConfig(n),Mr(Q,H.getMessages(),$),Bn.render(n.suggestionChips,H,K,void 0,n.suggestionChipsConfig),ho(),Jr(H.isStreaming());let er=((xl=n.voiceRecognition)==null?void 0:xl.enabled)===!0,hr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),tr=((Cl=(vl=n.voiceRecognition)==null?void 0:vl.provider)==null?void 0:Cl.type)==="runtype";if(er&&(hr||tr))if(!O||!Ee){let V=_t(n.voiceRecognition,n.sendButton);V&&(O=V.micButton,Ee=V.micButtonWrapper,tn.insertBefore(Ee,St),O.addEventListener("click",N),O.disabled=H.isStreaming())}else{let V=(wl=n.voiceRecognition)!=null?wl:{},it=(Sl=n.sendButton)!=null?Sl:{},It=(Al=V.iconName)!=null?Al:"mic",ze=(El=it.size)!=null?El:"40px",ct=(Tl=V.iconSize)!=null?Tl:ze,Ut=parseFloat(ct)||24;O.style.width=ct,O.style.height=ct,O.style.minWidth=ct,O.style.minHeight=ct;let on=(kl=(Ml=V.iconColor)!=null?Ml:it.textColor)!=null?kl:"currentColor";O.innerHTML="";let On=pe(It,Ut,on,2);On?O.appendChild(On):O.textContent="\u{1F3A4}";let un=(Ll=V.backgroundColor)!=null?Ll:it.backgroundColor;un?O.style.backgroundColor=un:O.style.backgroundColor="",on?O.style.color=on:O.style.color="var(--persona-text, #111827)",V.borderWidth?(O.style.borderWidth=V.borderWidth,O.style.borderStyle="solid"):(O.style.borderWidth="",O.style.borderStyle=""),V.borderColor?O.style.borderColor=V.borderColor:O.style.borderColor="",V.paddingX?(O.style.paddingLeft=V.paddingX,O.style.paddingRight=V.paddingX):(O.style.paddingLeft="",O.style.paddingRight=""),V.paddingY?(O.style.paddingTop=V.paddingY,O.style.paddingBottom=V.paddingY):(O.style.paddingTop="",O.style.paddingBottom="");let Ft=Ee==null?void 0:Ee.querySelector(".persona-send-button-tooltip"),Tn=(Il=V.tooltipText)!=null?Il:"Start voice recognition";if(((Pl=V.showTooltip)!=null?Pl:!1)&&Tn)if(Ft)Ft.textContent=Tn,Ft.style.display="";else{let Gt=document.createElement("div");Gt.className="persona-send-button-tooltip",Gt.textContent=Tn,Ee==null||Ee.insertBefore(Gt,O)}else Ft&&(Ft.style.display="none");Ee.style.display="",O.disabled=H.isStreaming()}else O&&Ee&&(Ee.style.display="none",((Rl=(Wl=n.voiceRecognition)==null?void 0:Wl.provider)==null?void 0:Rl.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():En&&nt());if(((Hl=n.attachments)==null?void 0:Hl.enabled)===!0)if(!dt||!le){let V=(Bl=n.attachments)!=null?Bl:{},It=(Fl=((Dl=n.sendButton)!=null?Dl:{}).size)!=null?Fl:"40px";G||(G=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),G.style.display="none",st.insertBefore(G,K)),He||(He=document.createElement("input"),He.type="file",He.accept=((Nl=V.allowedTypes)!=null?Nl:rr).join(","),He.multiple=((Ol=V.maxFiles)!=null?Ol:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),st.insertBefore(He,K)),dt=f("div","persona-send-button-wrapper"),le=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",($l=V.buttonTooltipText)!=null?$l:"Attach file");let ze=(_l=V.buttonIconName)!=null?_l:"paperclip",ct=It,Ut=parseFloat(ct)||40,on=Math.round(Ut*.6);le.style.width=ct,le.style.height=ct,le.style.minWidth=ct,le.style.minHeight=ct,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let On=pe(ze,on,"currentColor",1.5);On?le.appendChild(On):le.textContent="\u{1F4CE}",le.addEventListener("click",Tn=>{Tn.preventDefault(),He==null||He.click()}),dt.appendChild(le);let un=(jl=V.buttonTooltipText)!=null?jl:"Attach file",Ft=f("div","persona-send-button-tooltip");Ft.textContent=un,dt.appendChild(Ft),Zt.append(dt),!Ne&&He&&G&&(Ne=Fr.fromConfig(V),Ne.setPreviewsContainer(G),He.addEventListener("change",async()=>{Ne&&(He!=null&&He.files)&&(await Ne.handleFileSelect(He.files),He.value="")}))}else{dt.style.display="";let V=(zl=n.attachments)!=null?zl:{};He&&(He.accept=((Vl=V.allowedTypes)!=null?Vl:rr).join(","),He.multiple=((ql=V.maxFiles)!=null?ql:4)>1),Ne&&Ne.updateConfig({allowedTypes:V.allowedTypes,maxFileSize:V.maxFileSize,maxFiles:V.maxFiles})}else dt&&(dt.style.display="none"),Ne&&Ne.clearAttachments();let Vt=(Ul=n.sendButton)!=null?Ul:{},Ko=(Jl=Vt.useIcon)!=null?Jl:!1,vo=(Yl=Vt.iconText)!=null?Yl:"\u2191",Co=Vt.iconName,Gr=(Kl=Vt.tooltipText)!=null?Kl:"Send message",Xo=(Xl=Vt.showTooltip)!=null?Xl:!1,yr=(Gl=Vt.size)!=null?Gl:"40px",Lr=Vt.backgroundColor,Xt=Vt.textColor;if(Ko){if(X.style.width=yr,X.style.height=yr,X.style.minWidth=yr,X.style.minHeight=yr,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Xt?X.style.color=Xt:X.style.color="var(--persona-button-primary-fg, #ffffff)",Co){let V=parseFloat(yr)||24,it=(Xt==null?void 0:Xt.trim())||"currentColor",It=pe(Co,V,it,2);It?X.appendChild(It):X.textContent=vo}else X.textContent=vo;X.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Lr?(X.style.backgroundColor=Lr,X.classList.remove("persona-bg-persona-primary")):(X.style.backgroundColor="",X.classList.add("persona-bg-persona-primary"))}else X.textContent=(Ql=(Zl=n.copy)==null?void 0:Zl.sendButtonLabel)!=null?Ql:"Send",X.style.width="",X.style.height="",X.style.minWidth="",X.style.minHeight="",X.style.fontSize="",X.style.lineHeight="",X.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",Lr?(X.style.backgroundColor=Lr,X.classList.remove("persona-bg-persona-accent")):X.classList.add("persona-bg-persona-accent"),Xt?X.style.color=Xt:X.classList.add("persona-text-white");Vt.borderWidth?(X.style.borderWidth=Vt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),Vt.borderColor?X.style.borderColor=Vt.borderColor:X.style.borderColor="",Vt.paddingX?(X.style.paddingLeft=Vt.paddingX,X.style.paddingRight=Vt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),Vt.paddingY?(X.style.paddingTop=Vt.paddingY,X.style.paddingBottom=Vt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let fn=St==null?void 0:St.querySelector(".persona-send-button-tooltip");if(Xo&&Gr)if(fn)fn.textContent=Gr,fn.style.display="";else{let V=document.createElement("div");V.className="persona-send-button-tooltip",V.textContent=Gr,St==null||St.insertBefore(V,X)}else fn&&(fn.style.display="none");let br=(ec=n.layout)==null?void 0:ec.contentMaxWidth;br?(Q.style.maxWidth=br,Q.style.marginLeft="auto",Q.style.marginRight="auto",Q.style.width="100%",st&&(st.style.maxWidth=br,st.style.marginLeft="auto",st.style.marginRight="auto")):(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight="",Q.style.width="",st&&(st.style.maxWidth="",st.style.marginLeft="",st.style.marginRight=""));let xr=(tc=n.statusIndicator)!=null?tc:{},Ud=(nc=xr.visible)!=null?nc:!0;if(Pt.style.display=Ud?"":"none",H){let V=H.getStatus();Et(Pt,(It=>{var ze,ct,Ut,on;return It==="idle"?(ze=xr.idleText)!=null?ze:sn.idle:It==="connecting"?(ct=xr.connectingText)!=null?ct:sn.connecting:It==="connected"?(Ut=xr.connectedText)!=null?Ut:sn.connected:It==="error"?(on=xr.errorText)!=null?on:sn.error:sn[It]})(V),xr,V)}Pt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Jd=xr.align==="left"?"persona-text-left":xr.align==="center"?"persona-text-center":"persona-text-right";Pt.classList.add(Jd)},open(){b&&kt(!0,"api")},close(){b&&kt(!1,"api")},toggle(){b&&kt(!T,"api")},clearChat(){an=!1,H.clearMessages(),Fn.clear(),gr();try{localStorage.removeItem(po),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${po}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==po)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let g=a.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}i={},M.syncFromMetadata(),J==null||J.clear(),ae==null||ae.update()},setMessage(l){return!K||H.isStreaming()?!1:(!T&&b&&kt(!0,"system"),K.value=l,K.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let g=(l==null?void 0:l.trim())||K.value.trim();return g?(!T&&b&&kt(!0,"system"),K.value="",K.style.height="auto",H.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return H.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!T&&b&&kt(!0,"system"),Ye.manuallyDeactivated=!1,mn(),H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),kn("user"),H.isVoiceActive()&&v()})),!0):En?!0:Z()?(!T&&b&&kt(!0,"system"),Ye.manuallyDeactivated=!1,mn(),qe("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,mn(),kn("user"),A()}),!0):!1:En?(Ye.manuallyDeactivated=!0,mn(),nt("user"),!0):!1},injectMessage(l){return!T&&b&&kt(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!T&&b&&kt(!0,"system");let g=H.injectAssistantMessage(l);return Y&&(Y=!1,ue&&(clearTimeout(ue),ue=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),g},injectUserMessage(l){return!T&&b&&kt(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!T&&b&&kt(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!T&&b&&kt(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!T&&b&&kt(!0,"system"),H.injectTestEvent(l)},async connectStream(l,g){return H.connectStream(l,g)},__pushEventStreamEvent(l){J&&J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ne||!J||Yn()},hideEventStream(){ge&&Rn()},isEventStreamVisible(){return ge},showArtifacts(){Wn(n)&&(an=!1,Cn(),tt==null||tt.setMobileOpen(!0))},hideArtifacts(){Wn(n)&&(an=!0,Cn())},upsertArtifact(l){return Wn(n)?(an=!1,H.upsertArtifact(l)):null},selectArtifact(l){Wn(n)&&H.selectArtifact(l)},clearArtifacts(){Wn(n)&&H.clearArtifacts()},focusInput(){return b&&!T||!K?!1:(K.focus(),!0)},async resolveApproval(l,g){let E=H.getMessages().find(L=>{var I;return L.variant==="approval"&&((I=L.approval)==null?void 0:I.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(E.approval,g)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){h(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&T},isVoiceActive(){return Ye.active},getState(){return{open:b&&T,launcherEnabled:b,voiceActive:Ye.active,streaming:H.isStreaming()}},showCSATFeedback(l){!T&&b&&kt(!0,"system");let g=Q.querySelector(".persona-feedback-container");g&&g.remove();let y=ks({onSubmit:async(E,L)=>{var I;H.isClientTokenMode()&&await H.submitCSATFeedback(E,L),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Q.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&b&&kt(!0,"system");let g=Q.querySelector(".persona-feedback-container");g&&g.remove();let y=Ls({onSubmit:async(E,L)=>{var I;H.isClientTokenMode()&&await H.submitNPSFeedback(E,L),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Q.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return H.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return H.submitNPSFeedback(l,g)},destroy(){xt.forEach(l=>l()),j.remove(),Ue==null||Ue.destroy(),$e==null||$e.remove(),Sn&&ie.removeEventListener("click",Sn)}};if((((ii=t==null?void 0:t.debugTools)!=null?ii:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:Ze,getMessages:Ze.getMessages,getStatus:Ze.getStatus,getMetadata:Ze.getPersistentMetadata,updateMetadata:Ze.updatePersistentMetadata,clearHistory:()=>Ze.clearChat(),setVoiceActive:y=>y?Ze.startVoiceRecognition():Ze.stopVoiceRecognition()};window.AgentWidgetBrowser=g,xt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.focusInput()};if(window.addEventListener("persona:focusInput",g),xt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ne){let q=oe=>{let be=oe.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&Ze.showEventStream()},B=oe=>{let be=oe.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&Ze.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),xt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let y=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.showArtifacts()},E=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.hideArtifacts()},L=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&Ze.upsertArtifact(B.artifact)},I=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&Ze.selectArtifact(B.id)},P=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",P),xt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",P)})}let Bt=ou(n.persistState);if(Bt&&b){let l=su(Bt.storage),g=`${Bt.keyPrefix}widget-open`,y=`${Bt.keyPrefix}widget-voice`,E=`${Bt.keyPrefix}widget-voice-mode`;if(l){let L=((li=Bt.persist)==null?void 0:li.openState)&&l.getItem(g)==="true",I=((ci=Bt.persist)==null?void 0:ci.voiceState)&&l.getItem(y)==="true",P=((di=Bt.persist)==null?void 0:di.voiceState)&&l.getItem(E)==="true";if(L&&setTimeout(()=>{Ze.open(),setTimeout(()=>{var q;if(I||P)Ze.startVoiceRecognition();else if((q=Bt.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(pi=Bt.persist)!=null&&pi.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(ui=Bt.persist)!=null&&ui.voiceState&&(o.on("voice:state",q=>{l.setItem(y,q.active?"true":"false")}),o.on("user:message",q=>{l.setItem(E,q.viaVoice?"true":"false")})),Bt.clearOnChatClear){let q=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},B=()=>q();window.addEventListener("persona:clear-chat",B),xt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return c&&b&&setTimeout(()=>{Ze.open()},0),Ze};var au=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},ld=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},ga=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=""},cd=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",ga(e)},da=e=>{e.style.transition=""},pa=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=""},ua=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ps=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},iu=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},lu=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},dd=(e,r,t,n,s,o,a)=>{var C,M,b,x,S,F;let i=Pn(o),d=i.reveal==="push";iu(e,r,t,n,d),lu(e,r,t,n,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 c=e.ownerDocument.defaultView,p=(M=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileFullscreen)!=null?M:!0,u=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,h=c!=null?c.innerWidth<=u:!1;if(p&&h&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),pa(r),da(n),cd(n),ua(t),Ps(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((F=(S=o==null?void 0:o.launcher)==null?void 0:S.zIndex)!=null?F:yn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),cd(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",pa(r),da(n),ua(t),Ps(s,n);let w=i.animate?"transform 180ms ease":"none",k=i.side==="right"?"translateX(100%)":"translateX(-100%)",R=a?"translateX(0)":k;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=R,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",da(n),ga(n),Ps(s,n);let w=au(i.width,e.clientWidth),k=Math.max(0,e.clientWidth),R=i.animate?"transform 180ms ease":"none",T=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${k+w}px`,r.style.transition=R,r.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${k}px`,t.style.maxWidth=`${k}px`,t.style.minWidth=`${k}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",pa(r),ga(n),ua(t),Ps(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?i.width:"0px",R=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${k}`,n.style.width=k,n.style.maxWidth=k,n.style.minWidth=k,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||T?"hidden":"visible",n.style.transition=R,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},cu=(e,r)=>{let t=e.ownerDocument.createElement("div");return ld(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){ld(t,n)},destroy(){t.remove()}}},du=(e,r)=>{var S,F,w,k;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),u=(F=(S=r==null?void 0:r.launcher)==null?void 0:S.enabled)==null||F?(k=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?k:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),d.appendChild(e);let h=null,m=()=>{h==null||h.disconnect(),h=null},C=()=>{m(),Pn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(h=new ResizeObserver(()=>{dd(a,i,d,c,p,r,u)}),h.observe(a))},M=()=>{dd(a,i,d,c,p,r,u),C()},b=a.ownerDocument.defaultView,x=()=>{M()};return b==null||b.addEventListener("resize",x),Pn(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let T=R.launcherEnabled?R.open:!0;u!==T&&(u=T,M())},updateConfig(R){var T,Y;r=R,((Y=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)!=null?Y:!0)===!1&&(u=!0),M()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},zo=(e,r)=>Jt(r)?du(e,r):cu(e,r);var ma={},pu=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},uu=()=>{try{if(typeof ma!="undefined"&&ma.url)return new URL("../widget.css",ma.url).href}catch{}return null},pd=(e,r)=>{let t=uu(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},fa=e=>{var b;let r=pu(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=zo(r,s),a,i=[],d=(x,S)=>{var R,T;let w=!((T=(R=S==null?void 0:S.launcher)==null?void 0:R.enabled)!=null?T:!0)||Jt(S),k=n.createElement("div");if(k.setAttribute("data-persona-root","true"),w&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),t){let Y=x.attachShadow({mode:"open"});Y.appendChild(k),pd(Y,n)}else x.appendChild(k),pd(x,n);return r.id&&k.setAttribute("data-persona-instance",r.id),k},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let x=d(o.host,s);a=Is(x,s,{debugTools:e.debugTools}),p()},h=()=>{i.forEach(x=>x()),i=[],a.destroy()};u(),(b=e.onReady)==null||b.call(e);let m=x=>{h(),o.destroy(),o=zo(r,x),s=x,u()},C={update(x){var k,R,T,Y,ue,se;let S={...s,...x,launcher:{...(k=s==null?void 0:s.launcher)!=null?k:{},...(R=x==null?void 0:x.launcher)!=null?R:{},dock:{...(Y=(T=s==null?void 0:s.launcher)==null?void 0:T.dock)!=null?Y:{},...(se=(ue=x==null?void 0:x.launcher)==null?void 0:ue.dock)!=null?se:{}}}},F=Jt(s),w=Jt(S);if(F!==w){m(S);return}s=S,o.updateConfig(s),a.update(x),c()},destroy(){h(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},M=new Proxy(C,{get(x,S,F){if(S==="host")return o.host;if(S in x)return Reflect.get(x,S,F);let w=a[S];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=M),M};var hd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),gu=new Set(["button","a","input","select","textarea","details","summary"]),mu=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ha=/\b(product|card|item|listing|result)\b/i,ba=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,fu=3e3,hu=100;function yd(e){let r=typeof e.className=="string"?e.className:"";if(ha.test(r)||e.id&&ha.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&ha.test(n.value))return!0}return!1}function bd(e){var r;return ba.test(((r=e.textContent)!=null?r:"").trim())}function xd(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function yu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ud(e){let r=e.match(ba);return r?r[0]:null}function gd(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function bu(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var xu="commerce-card",vu="result-card";function md(e){return!yd(e)||!bd(e)||!xd(e)&&!yu(e)?0:5200}function fd(e){var n;return!yd(e)||bd(e)||!xd(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xa=[{id:xu,scoreElement(e){return md(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||ba.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,c,p;if(md(e)===0)return null;let{title:t,href:n}=gd(e),s=(p=(c=ud(((d=e.textContent)!=null?d:"").trim()))!=null?c:ud(r.text))!=null?p:"",o=bu(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
98
98
|
`)}},{id:vu,scoreElement(e){return fd(e)},formatSummary(e,r){if(fd(e)===0)return null;let{title:t,href:n}=gd(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
|
|
99
99
|
`)}}];function Cu(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function wu(e){var p,u,h,m,C,M,b,x,S,F,w,k,R;let r=(p=e.options)!=null?p:{},t=(h=(u=r.maxElements)!=null?u:e.maxElements)!=null?h:80,n=(C=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",s=(b=(M=r.maxTextLength)!=null?M:e.maxTextLength)!=null?b:200,o=(S=(x=r.visibleOnly)!=null?x:e.visibleOnly)!=null?S:!0,a=(F=r.root)!=null?F:e.root,i=(w=r.mode)!=null?w:"structured",d=(k=r.maxCandidates)!=null?k:Math.max(500,t*10),c=(R=e.rules)!=null?R:xa;return i==="simple"&&e.rules&&e.rules.length>0?(Cu(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function ya(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Su=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Au(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||gu.has(r)||t&&mu.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function vd(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Eu(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let d=e.getAttribute("role");d&&(r.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(r[p.name]=p.value)}return r}function va(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${ya(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Su){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${ya(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${r}.${t.map(a=>ya(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function Tu(e){return e==="static"?hu:fu}function Cd(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:va(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:Au(e),attributes:Eu(e)}}function Mu(e,r,t,n){let s=Tu(r.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,r,n);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function ku(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function Lu(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(hd.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!vd(c)){i=a.nextNode();continue}let u=Cd(c,e.maxTextLength),h=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(b=>b==="role");if(!h&&!m){i=a.nextNode();continue}if(n.has(u.selector)){i=a.nextNode();continue}n.add(u.selector);let{score:C,formattingRule:M}=Mu(c,u,e.rules,t);s.push({el:c,domIndex:o,enriched:u,score:C,formattingRule:M}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return u!==h?u-h:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;ku(d,c)||d.push(c)}return d.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return u!==h?u-h:u===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var h;let p;if((h=c.formattingRule)!=null&&h.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(p=m)}let u={...c.enriched};return p&&(u.formattedSummary=p),u})}function Iu(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,c=d.tagName.toLowerCase();if(hd.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!vd(d)){o=s.nextNode();continue}let p=Cd(d,e.maxTextLength),u=p.text.length>0,h=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!u&&!h){o=s.nextNode();continue}n.has(p.selector)||(n.add(p.selector),t.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function wd(e={}){var n;let r=wu(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?Iu(r,t):Lu(r,t):[]}var Ws=100;function Sd(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"structured",n=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
|
|
100
100
|
${a.map(i=>`- ${i.split(`
|
|
@@ -110,7 +110,7 @@ ${a.join(`
|
|
|
110
110
|
${a.join(`
|
|
111
111
|
`)}`)}return n.join(`
|
|
112
112
|
|
|
113
|
-
`)}var Ad={name:"@runtypelabs/persona",version:"3.8.
|
|
113
|
+
`)}var Ad={name:"@runtypelabs/persona",version:"3.8.1",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var _r=Ad.version;function ar(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function Wu(e){if(e)return{getHeaders:ar(e.getHeaders),onFeedback:ar(e.onFeedback),onCopy:ar(e.onCopy),requestMiddleware:ar(e.requestMiddleware),actionHandlers:ar(e.actionHandlers),actionParsers:ar(e.actionParsers),postprocessMessage:ar(e.postprocessMessage),contextProviders:ar(e.contextProviders),streamParser:ar(e.streamParser)}}var Ed=`({ text, message }: any) => {
|
|
114
114
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
115
115
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
116
116
|
let cleanJson = jsonSource
|