@runtypelabs/persona 2.2.0 → 2.3.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 +37 -37
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -1
- package/dist/index.d.ts +32 -1
- package/dist/index.global.js +90 -86
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +37 -37
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/package.json +2 -1
- package/src/components/artifact-pane.ts +6 -1
- package/src/components/message-bubble.test.ts +97 -0
- package/src/components/message-bubble.ts +20 -2
- package/src/index.ts +5 -0
- package/src/install-config.test.ts +38 -0
- package/src/install.ts +3 -1
- package/src/postprocessors.test.ts +84 -0
- package/src/types.ts +15 -1
- package/src/ui.ts +21 -7
- package/src/utils/actions.test.ts +114 -0
- package/src/utils/sanitize.test.ts +114 -0
- package/src/utils/sanitize.ts +83 -0
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
1
|
+
"use strict";var td=Object.create;var Ro=Object.defineProperty;var nd=Object.getOwnPropertyDescriptor;var rd=Object.getOwnPropertyNames;var od=Object.getPrototypeOf,sd=Object.prototype.hasOwnProperty;var ad=(e,n)=>{for(var t in n)Ro(e,t,{get:n[t],enumerable:!0})},bl=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of rd(n))!sd.call(e,s)&&s!==t&&Ro(e,s,{get:()=>n[s],enumerable:!(r=nd(n,s))||r.enumerable});return e};var xl=(e,n,t)=>(t=e!=null?td(od(e)):{},bl(n||!e||!e.__esModule?Ro(t,"default",{value:e,enumerable:!0}):t,e)),id=e=>bl(Ro({},"__esModule",{value:!0}),e);var Xp={};ad(Xp,{AgentWidgetClient:()=>Qn,AgentWidgetSession:()=>Cr,AttachmentManager:()=>rr,DEFAULT_COMPONENTS:()=>Es,DEFAULT_DARK_THEME:()=>qs,DEFAULT_LIGHT_THEME:()=>Us,DEFAULT_PALETTE:()=>Ss,DEFAULT_SEMANTIC:()=>As,DEFAULT_WIDGET_CONFIG:()=>ut,PRESETS:()=>aa,PRESET_FULLSCREEN:()=>sa,PRESET_MINIMAL:()=>oa,PRESET_SHOP:()=>ra,THEME_ZONES:()=>Ul,VERSION:()=>ir,accessibilityPlugin:()=>zc,animationsPlugin:()=>Jc,applyThemeVariables:()=>On,attachHeaderToContainer:()=>or,brandPlugin:()=>Kc,buildComposer:()=>Er,buildDefaultHeader:()=>Ws,buildHeader:()=>Pn,buildHeaderWithLayout:()=>Ar,buildMinimalHeader:()=>Rs,collectEnrichedPageContext:()=>Fc,componentRegistry:()=>In,createActionManager:()=>po,createAgentExperience:()=>ls,createBestAvailableVoiceProvider:()=>qo,createBubbleWithLayout:()=>oc,createCSATFeedback:()=>as,createComponentMiddleware:()=>Cc,createComponentStreamParser:()=>ns,createDefaultSanitizer:()=>vs,createDirectivePostprocessor:()=>Al,createFlexibleJsonStreamParser:()=>Ll,createImagePart:()=>Bl,createJsonStreamParser:()=>No,createLocalStorageAdapter:()=>ts,createMarkdownProcessor:()=>Zr,createMarkdownProcessorFromConfig:()=>Zn,createMessageActions:()=>Fs,createNPSFeedback:()=>is,createPlainTextParser:()=>Fo,createPlugin:()=>Xc,createRegexJsonParser:()=>$o,createStandardBubble:()=>Tr,createTextPart:()=>_o,createTheme:()=>wr,createThemeObserver:()=>Go,createTypingIndicator:()=>sr,createVoiceProvider:()=>nr,createWidgetHostLayout:()=>uo,createXmlParser:()=>Oo,default:()=>Gp,defaultActionHandlers:()=>ar,defaultJsonActionParser:()=>co,defaultParseRules:()=>ea,detectColorScheme:()=>no,directivePostprocessor:()=>El,escapeHtml:()=>br,extractComponentDirectiveFromMessage:()=>ss,fileToImagePart:()=>Fl,formatEnrichedContext:()=>$c,generateAssistantMessageId:()=>er,generateCodeSnippet:()=>Uc,generateMessageId:()=>Pl,generateStableSelector:()=>ta,generateUserMessageId:()=>vr,getActiveTheme:()=>Is,getColorScheme:()=>Ps,getDisplayText:()=>Wl,getHeaderLayout:()=>Hs,getImageParts:()=>Hl,getPreset:()=>Zc,hasComponentDirective:()=>os,hasImages:()=>Rl,headerLayouts:()=>Xo,highContrastPlugin:()=>Gc,initAgentWidget:()=>Gs,isComponentDirectiveType:()=>vc,isDockedMountMode:()=>Ut,isVoiceSupported:()=>to,markdownPostprocessor:()=>xs,mergeWithDefaults:()=>es,migrateV1Theme:()=>Yo,normalizeContent:()=>Il,pluginRegistry:()=>lo,reducedMotionPlugin:()=>Yc,renderComponentDirective:()=>rs,renderLoadingIndicatorWithFallback:()=>Bs,resolveDockConfig:()=>Sr,resolveSanitizer:()=>xr,resolveTokens:()=>Jo,themeToCssVariables:()=>Ko,validateImageFile:()=>$l,validateTheme:()=>Ts,validateV1Theme:()=>zl});module.exports=id(Xp);var Cl=require("marked"),ld=e=>{if(e)return e},Zr=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new Cl.Marked({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=ld(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Zn=e=>e?Zr({markedOptions:e.options,renderer:e.renderer}):Zr(),cd=Zr(),xs=e=>cd(e),br=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),wl=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),vl=e=>`%%FORM_PLACEHOLDER_${e}%%`,Sl=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=vl(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=vl(n.length);return n.push({token:o,type:s}),o}),t},Al=e=>{let n=Zn(e);return t=>{let r=[],s=Sl(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),g=`<div class="persona-form-directive" data-tv-form="${wl(i)}"></div>`;o=o.replace(d,g)}),o}},El=e=>{let n=[],t=Sl(e,n),r=xs(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${wl(o)}"></div>`;r=r.replace(a,d)}),r};var Tl=xl(require("dompurify"),1),dd={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"]},pd=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,vs=()=>{let e=(0,Tl.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!pd.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,dd)},xr=e=>e===!1?null:typeof e=="function"?e:vs();var kn=require("partial-json"),Ho=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Qr=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},ud=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Ml=e=>e.status==="complete"?ud(e):e.status==="pending"?"Waiting":"",gd=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 kl=e=>e.status==="complete"?gd(e):"Using tool...",md=()=>{let e=null,n=0,t=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Ho=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Bo=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Fo=()=>{var n;let e=cd();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},$o=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,kn.parse)(t,kn.STR|kn.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ro(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ro(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},El=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ro(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ro(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=(0,kn.parse)(o,kn.STR|kn.OBJ),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},No=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var dd="https://api.runtype.com/v1/dispatch",xs="https://api.runtype.com",vs=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 pd(e){switch(e){case"json":return $o;case"regex-json":return Fo;case"xml":return No;default:return Bo}}var Qn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s;this.apiUrl=(t=n.apiUrl)!=null?t:dd,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:pd(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xs;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xs}/v1/client/feedback`}async sendFeedback(n){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(n.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(vs).map(m=>{var C,v,E;return{id:m.id,role:m.role,content:(E=(v=(C=m.contentParts)!=null?C:m.llmContent)!=null?v:m.rawContent)!=null?E:m.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let y=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!y.ok){let m=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(y.status===429){let v=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!y.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(y.body,t,n.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(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xs}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(vs).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(r.context=s)}return r}async buildPayload(n){let r={messages:n.slice().filter(vs).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(r.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...r},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return r}async handleCustomSSEEvent(n,t,r,s,o){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(n);if(a===null)return!1;let i=()=>{if(r.current)return r.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return r.current=d,s(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,s(d)}return a.done&&(r.current&&(r.current.streaming=!1,s(r.current)),t({type:"status",status:"idle"})),a.error&&t({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(n,t,r){var mt,It,de,ae,U,ne,ie,Te,Xe,te,X,He,Ue,tt,Ut,Dt,ce,ze,ke,nt,Ve,Ze,Wt,Rt,Tt,B,G,z,j,xe,Pe,Be,pt,ve,Ce,Fe,ge,bt,Zt,un,gn,uo,Rn,lr,Qe,mn,Hn,ln,Ir,fn,dt,nn,wn,Wr,cr,Rr,Dn,hn,_n,xt,yn,Hr,Bn,bn,H,Fn,$n,Br,Sn,jn,Fr,An,En,dr,pr,go,mo,fo,$r,ur,qe,Nr,rn,Kt,ho,yo,Or,Vn,Tn,bo,xo,vo,fs,Un,gr,ft,mr,fr,Dr,_r,jr,Vr,qt,Qt,Mn,Re,Ur,qn,cn,Co,hr,yr,zn,Nn,wo,So,dn,Jn,Ao;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=Z=>{let $e=Z.reasoning?{...Z.reasoning,chunks:[...Z.reasoning.chunks]}:void 0,we=Z.toolCall?{...Z.toolCall,chunks:Z.toolCall.chunks?[...Z.toolCall.chunks]:void 0}:void 0,Ne=Z.tools?Z.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...Z,reasoning:$e,toolCall:we,tools:Ne}},p=Z=>{t({type:"message",message:g(Z)})},y=null,m={current:null},C=new Map,v=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=Z=>{if(Z==null)return null;try{return String(Z)}catch{return null}},q=Z=>{var $e,we,Ne,vt,Nt;return k((Nt=(vt=(Ne=(we=($e=Z.stepId)!=null?$e:Z.step_id)!=null?we:Z.step)!=null?Ne:Z.parentId)!=null?vt:Z.flowStepId)!=null?Nt:Z.flow_step_id)},M=Z=>{var $e,we,Ne,vt,Nt,Ct,b;return k((b=(Ct=(Nt=(vt=(Ne=(we=($e=Z.callId)!=null?$e:Z.call_id)!=null?we:Z.requestId)!=null?Ne:Z.request_id)!=null?vt:Z.toolCallId)!=null?Nt:Z.tool_call_id)!=null?Ct:Z.stepId)!=null?b:Z.step_id)},N=()=>y||(y={id:r!=null?r:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(y),y),w=(Z,$e)=>{E.lastId=$e,Z&&E.byStep.set(Z,$e)},F=(Z,$e)=>{var Nt;let we=(Nt=Z.reasoningId)!=null?Nt:Z.id,Ne=q(Z);if(we){let Ct=String(we);return w(Ne,Ct),Ct}if(Ne){let Ct=E.byStep.get(Ne);if(Ct)return E.lastId=Ct,Ct}if(E.lastId&&!$e)return E.lastId;if(!$e)return null;let vt=`reason-${c()}`;return w(Ne,vt),vt},Q=Z=>{let $e=C.get(Z);if($e)return $e;let we={id:`reason-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Z,status:"streaming",chunks:[]}};return C.set(Z,we),p(we),we},K=(Z,$e)=>{x.lastId=$e,Z&&x.byCall.set(Z,$e)},oe=new Set,J=new Map,me=new Set,We=new Map,Ge=Z=>{if(!Z)return!1;let $e=Z.replace(/_+/g,"_").replace(/^_|_$/g,"");return $e==="emit_artifact_markdown"||$e==="emit_artifact_component"},ye=(Z,$e)=>{var Nt;let we=(Nt=Z.toolId)!=null?Nt:Z.id,Ne=M(Z);if(we){let Ct=String(we);return K(Ne,Ct),Ct}if(Ne){let Ct=x.byCall.get(Ne);if(Ct)return x.lastId=Ct,Ct}if(x.lastId&&!$e)return x.lastId;if(!$e)return null;let vt=`tool-${c()}`;return K(Ne,vt),vt},ee=Z=>{let $e=v.get(Z);if($e)return $e;let we={id:`tool-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Z,status:"pending"}};return v.set(Z,we),p(we),we},Y=Z=>{if(typeof Z=="number"&&Number.isFinite(Z))return Z;if(typeof Z=="string"){let $e=Number(Z);if(!Number.isNaN($e)&&Number.isFinite($e))return $e;let we=Date.parse(Z);if(!Number.isNaN(we))return we}return Date.now()},_=Z=>{if(typeof Z=="string")return Z;if(Z==null)return"";try{return JSON.stringify(Z)}catch{return String(Z)}},D=new Map,ue=new Map,be=null,gt=new Map,ct=(mt=this.config.iterationDisplay)!=null?mt:"separate";for(;;){let{done:Z,value:$e}=await s.read();if(Z)break;a+=o.decode($e,{stream:!0});let we=a.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Bo=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Fo=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},$o=()=>{var n;let e=md();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},No=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,kn.parse)(t,kn.STR|kn.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ho(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ho(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Ll=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ho(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ho(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=(0,kn.parse)(o,kn.STR|kn.OBJ),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},Oo=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var fd="https://api.runtype.com/v1/dispatch",Cs="https://api.runtype.com",ws=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 hd(e){switch(e){case"json":return No;case"regex-json":return $o;case"xml":return Oo;default:return Fo}}var Qn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s;this.apiUrl=(t=n.apiUrl)!=null?t:fd,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:hd(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Cs;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Cs}/v1/client/feedback`}async sendFeedback(n){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(n.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(ws).map(m=>{var C,v,E;return{id:m.id,role:m.role,content:(E=(v=(C=m.contentParts)!=null?C:m.llmContent)!=null?v:m.rawContent)!=null?E:m.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(f.status===429){let v=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!f.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(f.body,t,n.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(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Cs}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(ws).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(r.context=s)}return r}async buildPayload(n){let r={messages:n.slice().filter(ws).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(r.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...r},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return r}async handleCustomSSEEvent(n,t,r,s,o){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(n);if(a===null)return!1;let i=()=>{if(r.current)return r.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return r.current=d,s(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,s(d)}return a.done&&(r.current&&(r.current.streaming=!1,s(r.current)),t({type:"status",status:"idle"})),a.error&&t({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(n,t,r){var gt,Wt,de,ie,qe,j,G,be,ze,X,K,tt,We,Ve,Tt,_t,ce,Je,Me,nt,je,Ze,Rt,Ht,Mt,B,Z,J,_,xe,Le,He,pt,ve,Ce,Be,ue,bt,Zt,un,gn,go,Rn,lr,Qe,mn,Hn,ln,Wr,fn,dt,nn,wn,Rr,cr,Hr,Dn,hn,_n,xt,yn,Br,Bn,bn,H,Fn,$n,Fr,Sn,jn,$r,An,En,dr,pr,mo,fo,ho,Nr,ur,Ue,Or,rn,Kt,yo,bo,Dr,Vn,Tn,xo,vo,Co,hs,Un,gr,mt,mr,fr,_r,jr,Vr,Ur,qt,Qt,Mn,Re,qr,qn,cn,wo,hr,yr,zn,Nn,So,Ao,dn,Jn,Eo;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=Q=>{let Fe=Q.reasoning?{...Q.reasoning,chunks:[...Q.reasoning.chunks]}:void 0,we=Q.toolCall?{...Q.toolCall,chunks:Q.toolCall.chunks?[...Q.toolCall.chunks]:void 0}:void 0,$e=Q.tools?Q.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...Q,reasoning:Fe,toolCall:we,tools:$e}},p=Q=>{t({type:"message",message:g(Q)})},f=null,m={current:null},C=new Map,v=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=Q=>{if(Q==null)return null;try{return String(Q)}catch{return null}},q=Q=>{var Fe,we,$e,vt,Ot;return k((Ot=(vt=($e=(we=(Fe=Q.stepId)!=null?Fe:Q.step_id)!=null?we:Q.step)!=null?$e:Q.parentId)!=null?vt:Q.flowStepId)!=null?Ot:Q.flow_step_id)},M=Q=>{var Fe,we,$e,vt,Ot,Ct,b;return k((b=(Ct=(Ot=(vt=($e=(we=(Fe=Q.callId)!=null?Fe:Q.call_id)!=null?we:Q.requestId)!=null?$e:Q.request_id)!=null?vt:Q.toolCallId)!=null?Ot:Q.tool_call_id)!=null?Ct:Q.stepId)!=null?b:Q.step_id)},N=()=>f||(f={id:r!=null?r:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(f),f),w=(Q,Fe)=>{E.lastId=Fe,Q&&E.byStep.set(Q,Fe)},F=(Q,Fe)=>{var Ot;let we=(Ot=Q.reasoningId)!=null?Ot:Q.id,$e=q(Q);if(we){let Ct=String(we);return w($e,Ct),Ct}if($e){let Ct=E.byStep.get($e);if(Ct)return E.lastId=Ct,Ct}if(E.lastId&&!Fe)return E.lastId;if(!Fe)return null;let vt=`reason-${c()}`;return w($e,vt),vt},re=Q=>{let Fe=C.get(Q);if(Fe)return Fe;let we={id:`reason-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Q,status:"streaming",chunks:[]}};return C.set(Q,we),p(we),we},Y=(Q,Fe)=>{x.lastId=Fe,Q&&x.byCall.set(Q,Fe)},ae=new Set,z=new Map,ge=new Set,Ie=new Map,Xe=Q=>{if(!Q)return!1;let Fe=Q.replace(/_+/g,"_").replace(/^_|_$/g,"");return Fe==="emit_artifact_markdown"||Fe==="emit_artifact_component"},ye=(Q,Fe)=>{var Ot;let we=(Ot=Q.toolId)!=null?Ot:Q.id,$e=M(Q);if(we){let Ct=String(we);return Y($e,Ct),Ct}if($e){let Ct=x.byCall.get($e);if(Ct)return x.lastId=Ct,Ct}if(x.lastId&&!Fe)return x.lastId;if(!Fe)return null;let vt=`tool-${c()}`;return Y($e,vt),vt},ee=Q=>{let Fe=v.get(Q);if(Fe)return Fe;let we={id:`tool-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Q,status:"pending"}};return v.set(Q,we),p(we),we},te=Q=>{if(typeof Q=="number"&&Number.isFinite(Q))return Q;if(typeof Q=="string"){let Fe=Number(Q);if(!Number.isNaN(Fe)&&Number.isFinite(Fe))return Fe;let we=Date.parse(Q);if(!Number.isNaN(we))return we}return Date.now()},D=Q=>{if(typeof Q=="string")return Q;if(Q==null)return"";try{return JSON.stringify(Q)}catch{return String(Q)}},U=new Map,oe=new Map,he=null,ht=new Map,at=(gt=this.config.iterationDisplay)!=null?gt:"separate";for(;;){let{done:Q,value:Fe}=await s.read();if(Q)break;a+=o.decode(Fe,{stream:!0});let we=a.split(`
|
|
5
5
|
|
|
6
|
-
`);a=(
|
|
7
|
-
`),Nt="message",Ct="";for(let T of vt)T.startsWith("event:")?Nt=T.replace("event:","").trim():T.startsWith("data:")&&(Ct+=T.replace("data:","").trim());if(!Ct)continue;let b;try{b=JSON.parse(Ct)}catch(T){t({type:"error",error:T instanceof Error?T:new Error("Failed to parse chat stream payload")});continue}let _e=Nt!=="message"?Nt:(de=b.type)!=null?de:"message";if((ae=this.onSSEEvent)==null||ae.call(this,_e,b),this.parseSSEEvent){m.current=y;let T=await this.handleCustomSSEEvent(b,t,m,p,c);if(m.current&&!y&&(y=m.current),T)continue}if(_e==="reason_start"){let T=(U=F(b,!0))!=null?U:`reason-${c()}`,A=Q(T);A.reasoning=(ne=A.reasoning)!=null?ne:{id:T,status:"streaming",chunks:[]},A.reasoning.startedAt=(Te=A.reasoning.startedAt)!=null?Te:Y((ie=b.startedAt)!=null?ie:b.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",p(A)}else if(_e==="reason_delta"||_e==="reason_chunk"){let T=(te=(Xe=F(b,!1))!=null?Xe:F(b,!0))!=null?te:`reason-${c()}`,A=Q(T);A.reasoning=(X=A.reasoning)!=null?X:{id:T,status:"streaming",chunks:[]},A.reasoning.startedAt=(Ue=A.reasoning.startedAt)!=null?Ue:Y((He=b.startedAt)!=null?He:b.timestamp);let W=(Dt=(Ut=(tt=b.reasoningText)!=null?tt:b.text)!=null?Ut:b.delta)!=null?Dt:"";if(W&&b.hidden!==!0&&A.reasoning.chunks.push(String(W)),A.reasoning.status=b.done?"complete":"streaming",b.done){A.reasoning.completedAt=Y((ce=b.completedAt)!=null?ce:b.timestamp);let le=(ze=A.reasoning.startedAt)!=null?ze:Date.now();A.reasoning.durationMs=Math.max(0,((ke=A.reasoning.completedAt)!=null?ke:Date.now())-le)}A.streaming=A.reasoning.status!=="complete",p(A)}else if(_e==="reason_complete"){let T=(Ve=(nt=F(b,!1))!=null?nt:F(b,!0))!=null?Ve:`reason-${c()}`,A=C.get(T);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=Y((Ze=b.completedAt)!=null?Ze:b.timestamp);let le=(Wt=A.reasoning.startedAt)!=null?Wt:Date.now();A.reasoning.durationMs=Math.max(0,((Rt=A.reasoning.completedAt)!=null?Rt:Date.now())-le),A.streaming=!1,p(A)}let W=q(b);W&&E.byStep.delete(W)}else if(_e==="tool_start"){let T=(Tt=ye(b,!0))!=null?Tt:`tool-${c()}`,A=(B=b.toolName)!=null?B:b.name;if(Ge(A)){oe.add(T);continue}let W=ee(T),le=(G=W.toolCall)!=null?G:{id:T,status:"pending"};le.name=A!=null?A:le.name,le.status="running",b.args!==void 0?le.args=b.args:b.parameters!==void 0&&(le.args=b.parameters),le.startedAt=(j=le.startedAt)!=null?j:Y((z=b.startedAt)!=null?z:b.timestamp),le.completedAt=void 0,le.durationMs=void 0,W.toolCall=le,W.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(W.agentMetadata={executionId:(xe=Se==null?void 0:Se.executionId)!=null?xe:b.executionId,iteration:(Pe=Se==null?void 0:Se.iteration)!=null?Pe:b.iteration}),p(W)}else if(_e==="tool_chunk"||_e==="tool_delta"){let T=(pt=(Be=ye(b,!1))!=null?Be:ye(b,!0))!=null?pt:`tool-${c()}`;if(oe.has(T))continue;let A=ee(T),W=(ve=A.toolCall)!=null?ve:{id:T,status:"running"};W.startedAt=(Fe=W.startedAt)!=null?Fe:Y((Ce=b.startedAt)!=null?Ce:b.timestamp);let le=(Zt=(bt=(ge=b.text)!=null?ge:b.delta)!=null?bt:b.message)!=null?Zt:"";le&&(W.chunks=(un=W.chunks)!=null?un:[],W.chunks.push(String(le))),W.status="running",A.toolCall=W,A.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(A.agentMetadata=(Rn=A.agentMetadata)!=null?Rn:{executionId:(gn=Se==null?void 0:Se.executionId)!=null?gn:b.executionId,iteration:(uo=Se==null?void 0:Se.iteration)!=null?uo:b.iteration}),p(A)}else if(_e==="tool_complete"){let T=(Qe=(lr=ye(b,!1))!=null?lr:ye(b,!0))!=null?Qe:`tool-${c()}`;if(oe.has(T)){oe.delete(T);continue}let A=ee(T),W=(mn=A.toolCall)!=null?mn:{id:T,status:"running"};W.status="complete",b.result!==void 0&&(W.result=b.result),typeof b.duration=="number"&&(W.duration=b.duration),W.completedAt=Y((Hn=b.completedAt)!=null?Hn:b.timestamp);let le=(ln=b.duration)!=null?ln:b.executionTime;if(typeof le=="number")W.durationMs=le;else{let Mt=(Ir=W.startedAt)!=null?Ir:Date.now();W.durationMs=Math.max(0,((fn=W.completedAt)!=null?fn:Date.now())-Mt)}A.toolCall=W,A.streaming=!1;let Se=b.agentContext;(Se||b.executionId)&&(A.agentMetadata=(wn=A.agentMetadata)!=null?wn:{executionId:(dt=Se==null?void 0:Se.executionId)!=null?dt:b.executionId,iteration:(nn=Se==null?void 0:Se.iteration)!=null?nn:b.iteration}),p(A);let ot=M(b);ot&&x.byCall.delete(ot)}else if(_e==="step_chunk"||_e==="step_delta"){let T=b.stepType,A=b.executionType;if(T==="tool"||A==="context")continue;let W=N(),le=(Dn=(Rr=(cr=(Wr=b.text)!=null?Wr:b.delta)!=null?cr:b.content)!=null?Rr:b.chunk)!=null?Dn:"";if(le){let ot=((hn=ue.get(W.id))!=null?hn:"")+le;W.rawContent=ot,D.has(W.id)||D.set(W.id,this.createStreamParser());let Mt=D.get(W.id),wt=ot.trim().startsWith("{")||ot.trim().startsWith("[");if(wt&&ue.set(W.id,ot),Mt.__isPlainTextParser===!0){W.content+=le,ue.delete(W.id),D.delete(W.id),W.rawContent=void 0,p(W);continue}let kt=Mt.processChunk(ot);if(kt instanceof Promise)kt.then(st=>{var At;let it=typeof st=="string"?st:(At=st==null?void 0:st.text)!=null?At:null;if(it!==null&&it.trim()!==""){let lt=y;lt&<.id===W.id&&(lt.content=it,p(lt))}else if(!wt&&!ot.trim().startsWith("<")){let lt=y;lt&<.id===W.id&&(lt.content+=le,ue.delete(lt.id),D.delete(lt.id),lt.rawContent=void 0,p(lt))}}).catch(()=>{W.content+=le,ue.delete(W.id),D.delete(W.id),W.rawContent=void 0,p(W)});else{let st=typeof kt=="string"?kt:(_n=kt==null?void 0:kt.text)!=null?_n:null;st!==null&&st.trim()!==""?(W.content=st,p(W)):!wt&&!ot.trim().startsWith("<")&&(W.content+=le,ue.delete(W.id),D.delete(W.id),W.rawContent=void 0,p(W))}}if(b.isComplete){let Se=(yn=(xt=b.result)==null?void 0:xt.response)!=null?yn:W.content;if(Se){let ot=ue.get(W.id),Mt=ot!=null?ot:_(Se);W.rawContent=Mt;let wt=D.get(W.id),Ht=null,kt=!1;if(wt&&(Ht=wt.getExtractedText(),Ht===null&&(Ht=Ho(Mt)),Ht===null)){let st=wt.processChunk(Mt);st instanceof Promise?(kt=!0,st.then(it=>{var lt;let At=typeof it=="string"?it:(lt=it==null?void 0:it.text)!=null?lt:null;if(At!==null){let Bt=y;Bt&&Bt.id===W.id&&(Bt.content=At,Bt.streaming=!1,D.delete(Bt.id),ue.delete(Bt.id),p(Bt))}})):Ht=typeof st=="string"?st:(Hr=st==null?void 0:st.text)!=null?Hr:null}if(!kt){Ht!==null&&Ht.trim()!==""?W.content=Ht:ue.has(W.id)||(W.content=_(Se));let st=D.get(W.id);if(st){let it=(Bn=st.close)==null?void 0:Bn.call(st);it instanceof Promise&&it.catch(()=>{}),D.delete(W.id)}ue.delete(W.id),W.streaming=!1,p(W)}}}}else if(_e==="step_complete"){let T=b.stepType,A=b.executionType;if(T==="tool"||A==="context")continue;let W=(bn=b.result)==null?void 0:bn.response,le=N();if(W!=null){let Se=D.get(le.id),ot=!1,Mt=!1;if(Se){let wt=Se.getExtractedText(),Ht=ue.get(le.id),kt=Ht!=null?Ht:_(W);if(le.rawContent=kt,wt!==null&&wt.trim()!=="")le.content=wt,ot=!0;else{let st=Ho(kt);if(st!==null)le.content=st,ot=!0;else{let it=Se.processChunk(kt);if(it instanceof Promise)Mt=!0,it.then(At=>{var Bt;let lt=typeof At=="string"?At:(Bt=At==null?void 0:At.text)!=null?Bt:null;if(lt!==null&<.trim()!==""){let Yt=y;Yt&&Yt.id===le.id&&(Yt.content=lt,Yt.streaming=!1,D.delete(Yt.id),ue.delete(Yt.id),p(Yt))}else{let Yt=Se.getExtractedText(),on=y;on&&on.id===le.id&&(Yt!==null&&Yt.trim()!==""?on.content=Yt:ue.has(on.id)||(on.content=_(W)),on.streaming=!1,D.delete(on.id),ue.delete(on.id),p(on))}});else{let At=typeof it=="string"?it:(H=it==null?void 0:it.text)!=null?H:null;if(At!==null&&At.trim()!=="")le.content=At,ot=!0;else{let lt=Se.getExtractedText();lt!==null&<.trim()!==""&&(le.content=lt,ot=!0)}}}}}if(!Mt){if(!le.rawContent){let wt=ue.get(le.id);le.rawContent=wt!=null?wt:_(W)}if(!ot&&!ue.has(le.id)&&(le.content=_(W)),Se){let wt=(Fn=Se.close)==null?void 0:Fn.call(Se);wt instanceof Promise&&wt.catch(()=>{})}D.delete(le.id),ue.delete(le.id),le.streaming=!1,p(le)}}else D.delete(le.id),ue.delete(le.id),le.streaming=!1,p(le)}else if(_e==="flow_complete"){let T=($n=b.result)==null?void 0:$n.response;if(T!=null){let A=N(),W=ue.get(A.id),le=W!=null?W:_(T);A.rawContent=le;let Se=_(T),ot=D.get(A.id);if(ot){let Ht=Ho(le);if(Ht!==null)Se=Ht;else{let kt=ot.processChunk(le);kt instanceof Promise&&kt.then(it=>{var lt;let At=typeof it=="string"?it:(lt=it==null?void 0:it.text)!=null?lt:null;if(At!==null){let Bt=y;Bt&&Bt.id===A.id&&(Bt.content=At,Bt.streaming=!1,p(Bt))}});let st=ot.getExtractedText();st!==null&&(Se=st)}}D.delete(A.id),ue.delete(A.id);let Mt=Se!==A.content,wt=A.streaming!==!1;Mt&&(A.content=Se),A.streaming=!1,(Mt||wt)&&p(A)}else if(y!==null){let A=y;D.delete(A.id),ue.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}t({type:"status",status:"idle"})}else if(_e==="agent_start")be={executionId:b.executionId,agentId:(Br=b.agentId)!=null?Br:"virtual",agentName:(Sn=b.agentName)!=null?Sn:"",status:"running",currentIteration:0,maxTurns:(jn=b.maxTurns)!=null?jn:1,startedAt:Y(b.startedAt)};else if(_e==="agent_iteration_start"){if(be&&(be.currentIteration=b.iteration),ct==="separate"&&b.iteration>1){let T=y;T&&(T.streaming=!1,p(T),gt.set(b.iteration-1,T),y=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(b.contentType==="text"){let T=N();T.content+=(Fr=b.delta)!=null?Fr:"",T.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:be==null?void 0:be.agentName},p(T)}else if(b.contentType==="thinking"){let T=(An=b.turnId)!=null?An:`agent-think-${b.iteration}`,A=Q(T);A.reasoning=(En=A.reasoning)!=null?En:{id:T,status:"streaming",chunks:[]},A.reasoning.chunks.push((dr=b.delta)!=null?dr:""),A.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},p(A)}else if(b.contentType==="tool_input"){let T=(pr=b.toolCallId)!=null?pr:x.lastId;if(T){let A=v.get(T);A!=null&&A.toolCall&&(A.toolCall.chunks=(go=A.toolCall.chunks)!=null?go:[],A.toolCall.chunks.push((mo=b.delta)!=null?mo:""),p(A))}}}else if(_e==="agent_turn_complete"){let T=b.turnId;if(T){let A=C.get(T);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=Y(b.completedAt);let W=(fo=A.reasoning.startedAt)!=null?fo:Date.now();A.reasoning.durationMs=Math.max(0,(($r=A.reasoning.completedAt)!=null?$r:Date.now())-W),A.streaming=!1,p(A)}}}else if(_e==="agent_tool_start"){let T=(ur=b.toolCallId)!=null?ur:`agent-tool-${c()}`;K(M(b),T);let A=ee(T),W=(qe=A.toolCall)!=null?qe:{id:T,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};W.name=(rn=(Nr=b.toolName)!=null?Nr:b.name)!=null?rn:W.name,W.status="running",b.parameters!==void 0&&(W.args=b.parameters),W.startedAt=Y((Kt=b.startedAt)!=null?Kt:b.timestamp),A.toolCall=W,A.streaming=!0,A.agentMetadata={executionId:b.executionId,iteration:b.iteration},p(A)}else if(_e==="agent_tool_delta"){let T=(ho=b.toolCallId)!=null?ho:x.lastId;if(T){let A=(yo=v.get(T))!=null?yo:ee(T);A.toolCall&&(A.toolCall.chunks=(Or=A.toolCall.chunks)!=null?Or:[],A.toolCall.chunks.push((Vn=b.delta)!=null?Vn:""),A.toolCall.status="running",A.streaming=!0,p(A))}}else if(_e==="agent_tool_complete"){let T=(Tn=b.toolCallId)!=null?Tn:x.lastId;if(T){let A=(bo=v.get(T))!=null?bo:ee(T);if(A.toolCall){A.toolCall.status="complete",b.result!==void 0&&(A.toolCall.result=b.result),typeof b.executionTime=="number"&&(A.toolCall.durationMs=b.executionTime),A.toolCall.completedAt=Y((xo=b.completedAt)!=null?xo:b.timestamp),A.streaming=!1,p(A);let W=M(b);W&&x.byCall.delete(W)}}}else if(_e!=="agent_iteration_complete"){if(_e==="agent_reflection"||_e==="agent_reflect"){let T=`agent-reflection-${b.executionId}-${b.iteration}`,A={id:T,role:"assistant",content:(vo=b.reflection)!=null?vo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(fs=b.reflection)!=null?fs:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};p(A)}else if(_e==="agent_complete"){be&&(be.status=b.success?"complete":"error",be.completedAt=Y(b.completedAt),be.stopReason=b.stopReason);let T=y;T&&(T.streaming=!1,p(T)),t({type:"status",status:"idle"})}else if(_e==="agent_error"){let T=typeof b.error=="string"?b.error:(gr=(Un=b.error)==null?void 0:Un.message)!=null?gr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",T):t({type:"error",error:new Error(T)})}else if(_e!=="agent_ping")if(_e==="agent_approval_start"){let T=(ft=b.approvalId)!=null?ft:`approval-${c()}`,A={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(mr=be==null?void 0:be.agentId)!=null?mr:"virtual",executionId:(Dr=(fr=b.executionId)!=null?fr:be==null?void 0:be.executionId)!=null?Dr:"",toolName:(_r=b.toolName)!=null?_r:"",toolType:b.toolType,description:(Vr=b.description)!=null?Vr:`Execute ${(jr=b.toolName)!=null?jr:"tool"}`,parameters:b.parameters}};p(A)}else if(_e==="step_await"&&b.awaitReason==="approval_required"){let T=(qt=b.approvalId)!=null?qt:`approval-${c()}`,A={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Qt=be==null?void 0:be.agentId)!=null?Qt:"virtual",executionId:(Re=(Mn=b.executionId)!=null?Mn:be==null?void 0:be.executionId)!=null?Re:"",toolName:(Ur=b.toolName)!=null?Ur:"",toolType:b.toolType,description:(cn=b.description)!=null?cn:`Execute ${(qn=b.toolName)!=null?qn:"tool"}`,parameters:b.parameters}};p(A)}else if(_e==="agent_approval_complete"){let T=b.approvalId;if(T){let W={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:(Co=b.decision)!=null?Co:"approved",agentId:(hr=be==null?void 0:be.agentId)!=null?hr:"virtual",executionId:(zn=(yr=b.executionId)!=null?yr:be==null?void 0:be.executionId)!=null?zn:"",toolName:(Nn=b.toolName)!=null?Nn:"",description:(wo=b.description)!=null?wo:"",resolvedAt:Date.now()}};p(W)}}else if(_e==="artifact_start"||_e==="artifact_delta"||_e==="artifact_update"||_e==="artifact_complete"){if(_e==="artifact_start"){let T=b.artifactType,A=String(b.id),W=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:A,artifactType:T,title:W,component:typeof b.component=="string"?b.component:void 0}),We.set(A,{markdown:"",title:W}),!me.has(A)){me.add(A);let le={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:W,artifactType:T,status:"streaming"}})};J.set(A,le),p(le)}}else if(_e==="artifact_delta"){let T=String(b.id),A=typeof b.delta=="string"?b.delta:String((So=b.delta)!=null?So:"");t({type:"artifact_delta",id:T,artDelta:A});let W=We.get(T);W&&(W.markdown+=A)}else if(_e==="artifact_update"){let T=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:T,component:typeof b.component=="string"?b.component:void 0})}else if(_e==="artifact_complete"){let T=String(b.id);t({type:"artifact_complete",id:T});let A=J.get(T);if(A){A.streaming=!1;try{let W=JSON.parse((dn=A.rawContent)!=null?dn:"{}");if(W.props){W.props.status="complete";let le=We.get(T);le!=null&&le.markdown&&(W.props.markdown=le.markdown)}A.rawContent=JSON.stringify(W)}catch{}We.delete(T),p(A),J.delete(T)}}}else if(_e==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let A=String((Jn=T.id)!=null?Jn:`msg-${c()}`),W=T.role,Se={id:A,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(p(Se),Se.rawContent)try{let ot=JSON.parse(Se.rawContent),Mt=(Ao=ot==null?void 0:ot.props)==null?void 0:Ao.artifactId;typeof Mt=="string"&&me.add(Mt)}catch{}y=null,m.current=null,D.delete(A),ue.delete(A)}else _e==="error"&&b.error&&t({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function Tl(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function xr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function er(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Oo="[Image]";function Ml(e){return typeof e=="string"?[{type:"text",text:e}]:e}function kl(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Ll(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Pl(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Do(e){return{type:"text",text:e}}function Il(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Wl(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Rl(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Hl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ud=["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"],Ln=[...Hl,...ud];function gd(e){return Hl.includes(e)||e.startsWith("image/")}function _o(e){return gd(e.type)}async function Bl(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;_o(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Fl(e,n=Ln,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function md(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function $l(e,n){let t=md(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var jo=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Vo=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let g=0;g<a.length;g++)i+=a[g]*a[g];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Qr=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Vo;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let g=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((y,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,v=x=>{C||(C=!0,clearTimeout(E),m(new Error(x)))},E=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),y())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+g+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let k=x.code!==1006?` (code ${x.code})`:"";v("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new jo(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let 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=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=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(y=>y("processing")),this.processingStartCallbacks.forEach(y=>y());let g=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:g});await this.sendAudio(p),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(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let c=0;c<t.length;c++)r[c]=t.charCodeAt(c);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var tr=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function nr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Qr(e.runtype);case"browser":if(!tr.isSupported())throw new Error("Browser speech recognition not supported");return new tr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Uo(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return nr({type:"runtype",runtype:e.runtype});if(tr.isSupported())return nr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function eo(e){try{return Uo(e),!0}catch{return!1}}var vr=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,d;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=n.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return eo((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=nr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var g,p,y,m,C,v;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((g=c.transcript)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((y=c.text)!=null&&y.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 E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}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 g,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(g=this.callbacks).onVoiceStatusChanged)==null||p.call(g,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(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,c,g;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=n.browser)==null?void 0:c.language)||"en-US",continuous:(g=n.browser)==null?void 0:g.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new Qn(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g}=n,y={id:a!=null?a:t==="user"?xr():t==="assistant"?er():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...g!==void 0&&{voiceProcessing:g}};return this.upsertMessage(y),y}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:p=!1}=r,m={id:d!=null?d:s==="user"?xr():s==="assistant"?er():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:p,...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(n,t){var c,g,p,y,m;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=xr(),o=er(),a={id:s,role:"user",content:r||Oo,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 v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let E={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(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(C instanceof Error?(p=(g=this.callbacks).onError)==null||p.call(g,C):(m=(y=this.callbacks).onError)==null||m.call(y,new Error(String(C))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=er();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(c){let g={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(g),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(n,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,c,g;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):p=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),p){let y=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}y=p.body}else p instanceof ReadableStream&&(y=p);y?await this.connectStream(y):t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(g=(c=this.callbacks).onError)==null||g.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===r?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,c;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var f=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},vn=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};var fd=rd(require("lucide"),1),fe=(e,n=24,t="currentColor",r=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=fd[s];return o?hd(o,n,t,r):(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 hd(e,n,t,r){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){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,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),s.appendChild(d)}}}),s}var qo={allowedTypes:Ln,maxFileSize:10*1024*1024,maxFiles:4};function yd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function bd(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 rr=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:qo.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:qo.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:qo.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:qo.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let g=Fl(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let p=(s=g.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await Bl(c),y=_o(c)?URL.createObjectURL(c):null,m={id:yd(),file:c,previewUrl:y,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=_o(n.file),r=f("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=f("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=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=bd(n.file.type),d=fe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=f("span");c.textContent=$l(n.file.type,n.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),r.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=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var Cs={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}},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"}},ws={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",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.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.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"}},Ss={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",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:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{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:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},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"}}};function Nl(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Nl(e,r):r}function zo(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Nl(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function As(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function Ol(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=Ol(o,s):t[r]=s}return t}function xd(e,n){return n?Ol(e,n):e}function Cr(e,n={}){var s,o,a,i,d,c,g,p,y,m,C,v,E;let t={palette:Cs,semantic:ws,components:Ss},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(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,...(g=e==null?void 0:e.semantic)==null?void 0:g.colors,interactive:{...t.semantic.colors.interactive,...(y=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:y.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,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...t.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:xd(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let x=As(r);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(k=>k.message).join(", ")}`)}if(n.plugins)for(let x of n.plugins)r=x.transform(r);return r}function Jo(e){var g,p,y,m,C,v,E,x,k,q,M,N,w,F,Q,K,oe,J,me,We,Ge,ye,ee,Y,_,D,ue,be,gt,ct,mt,It,de,ae,U,ne,ie,Te,Xe,te,X,He,Ue,tt,Ut,Dt,ce,ze,ke,nt,Ve,Ze,Wt,Rt,Tt,B,G,z;let n=zo(e),t={};for(let[j,xe]of Object.entries(n)){let Pe=j.replace(/\./g,"-");t[`--persona-${Pe}`]=xe.value}t["--persona-primary"]=(g=t["--persona-semantic-colors-primary"])!=null?g:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(p=t["--persona-semantic-colors-secondary"])!=null?p:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(y=t["--persona-semantic-colors-accent"])!=null?y:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(m=t["--persona-semantic-colors-surface"])!=null?m:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(C=t["--persona-semantic-colors-background"])!=null?C:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(v=t["--persona-semantic-colors-container"])!=null?v:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(E=t["--persona-semantic-colors-text"])!=null?E:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(x=t["--persona-semantic-colors-text-muted"])!=null?x:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(k=t["--persona-semantic-colors-text-inverse"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(q=t["--persona-semantic-colors-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(M=t["--persona-semantic-colors-divider"])!=null?M:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(N=t["--persona-components-voice-recording-indicator"])!=null?N:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(w=t["--persona-components-voice-recording-background"])!=null?w:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(F=t["--persona-components-voice-processing-icon"])!=null?F:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(Q=t["--persona-components-voice-speaking-icon"])!=null?Q:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(K=t["--persona-components-approval-requested-background"])!=null?K:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(oe=t["--persona-components-approval-requested-border"])!=null?oe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(J=t["--persona-components-approval-requested-text"])!=null?J: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"]=(We=t["--persona-components-approval-deny-background"])!=null?We:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Ge=t["--persona-components-attachment-image-background"])!=null?Ge:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ye=t["--persona-components-attachment-image-border"])!=null?ye:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ee=t["--persona-semantic-typography-fontFamily"])!=null?ee:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Y=t["--persona-semantic-typography-fontSize"])!=null?Y:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(_=t["--persona-semantic-typography-fontWeight"])!=null?_:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(D=t["--persona-semantic-typography-lineHeight"])!=null?D:t["--persona-palette-typography-lineHeight-normal"],t["--persona-radius-sm"]=(ue=t["--persona-palette-radius-sm"])!=null?ue:"0.125rem",t["--persona-radius-md"]=(be=t["--persona-palette-radius-md"])!=null?be:"0.375rem",t["--persona-radius-lg"]=(gt=t["--persona-palette-radius-lg"])!=null?gt:"0.5rem",t["--persona-radius-xl"]=(ct=t["--persona-palette-radius-xl"])!=null?ct:"0.75rem",t["--persona-launcher-radius"]=(It=(mt=t["--persona-components-launcher-borderRadius"])!=null?mt:t["--persona-palette-radius-full"])!=null?It:"9999px",t["--persona-button-radius"]=(ae=(de=t["--persona-components-button-primary-borderRadius"])!=null?de:t["--persona-palette-radius-full"])!=null?ae:"9999px",t["--persona-panel-radius"]=(ne=(U=t["--persona-components-panel-borderRadius"])!=null?U:t["--persona-radius-xl"])!=null?ne:"0.75rem",t["--persona-input-radius"]=(Te=(ie=t["--persona-components-input-borderRadius"])!=null?ie:t["--persona-radius-lg"])!=null?Te:"0.5rem",t["--persona-message-user-radius"]=(te=(Xe=t["--persona-components-message-user-borderRadius"])!=null?Xe:t["--persona-radius-lg"])!=null?te:"0.5rem",t["--persona-message-assistant-radius"]=(He=(X=t["--persona-components-message-assistant-borderRadius"])!=null?X:t["--persona-radius-lg"])!=null?He:"0.5rem",t["--persona-header-bg"]=(Ue=t["--persona-components-header-background"])!=null?Ue:t["--persona-surface"],t["--persona-header-border"]=(tt=t["--persona-components-header-border"])!=null?tt:t["--persona-divider"],t["--persona-message-user-bg"]=(Ut=t["--persona-components-message-user-background"])!=null?Ut:t["--persona-accent"],t["--persona-message-user-text"]=(Dt=t["--persona-components-message-user-text"])!=null?Dt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(ce=t["--persona-components-message-user-shadow"])!=null?ce:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(ze=t["--persona-components-message-assistant-background"])!=null?ze:t["--persona-surface"],t["--persona-message-assistant-text"]=(ke=t["--persona-components-message-assistant-text"])!=null?ke:t["--persona-text"],t["--persona-message-assistant-border"]=(nt=t["--persona-components-message-assistant-border"])!=null?nt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Ve=t["--persona-components-message-assistant-shadow"])!=null?Ve:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(Ze=t["--persona-components-toolBubble-shadow"])!=null?Ze:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Wt=t["--persona-components-reasoningBubble-shadow"])!=null?Wt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Rt=t["--persona-components-composer-shadow"])!=null?Rt:"none",t["--persona-md-inline-code-bg"]=(Tt=t["--persona-components-markdown-inlineCode-background"])!=null?Tt:t["--persona-container"],t["--persona-md-inline-code-color"]=(B=t["--persona-components-markdown-inlineCode-foreground"])!=null?B:t["--persona-text"],t["--persona-md-link-color"]=(z=(G=t["--persona-components-markdown-link-foreground"])!=null?G:t["--persona-accent"])!=null?z:"#3b82f6";let r=t["--persona-components-markdown-heading-h1-fontSize"];r&&(t["--persona-md-h1-size"]=r);let s=t["--persona-components-markdown-heading-h1-fontWeight"];s&&(t["--persona-md-h1-weight"]=s);let o=t["--persona-components-markdown-heading-h2-fontSize"];o&&(t["--persona-md-h2-size"]=o);let a=t["--persona-components-markdown-heading-h2-fontWeight"];a&&(t["--persona-md-h2-weight"]=a);let i=t["--persona-components-markdown-prose-fontFamily"];i&&i!=="inherit"&&(t["--persona-md-prose-font-family"]=i);let d=e.components,c=d==null?void 0:d.artifact;if(c!=null&&c.toolbar){let j=c.toolbar;j.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=j.iconHoverColor),j.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=j.iconHoverBackground),j.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=j.iconPadding),j.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=j.iconBorderRadius),j.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=j.iconBorder),j.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=j.toggleGroupGap),j.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=j.toggleBorderRadius),j.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=j.copyBackground),j.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=j.copyBorder),j.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=j.copyColor),j.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=j.copyBorderRadius),j.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=j.copyPadding),j.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=j.copyMenuBackground),j.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=j.copyMenuBorder),j.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=j.copyMenuShadow),j.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=j.copyMenuBorderRadius),j.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=j.copyMenuItemHoverBackground)}if(c!=null&&c.tab){let j=c.tab;j.background&&(t["--persona-artifact-tab-bg"]=j.background),j.activeBackground&&(t["--persona-artifact-tab-active-bg"]=j.activeBackground),j.activeBorder&&(t["--persona-artifact-tab-active-border"]=j.activeBorder),j.borderRadius&&(t["--persona-artifact-tab-radius"]=j.borderRadius),j.textColor&&(t["--persona-artifact-tab-color"]=j.textColor)}if(c!=null&&c.pane){let j=c.pane;j.toolbarBackground&&(t["--persona-artifact-toolbar-bg"]=j.toolbarBackground)}return t}var Dl={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 Es={primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.accent.600",surface:"palette.colors.gray.50",muted:"palette.colors.gray.500",container:"palette.colors.gray.100",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",messageBorder:"palette.colors.gray.200",inputBackground:"palette.colors.gray.50",callToAction:"palette.colors.gray.900",callToActionBackground:"palette.colors.gray.50",sendButtonBackgroundColor:"semantic.colors.primary",sendButtonTextColor:"semantic.colors.textInverse",sendButtonBorderColor:"semantic.colors.primary",closeButtonColor:"palette.colors.gray.500",closeButtonBackgroundColor:"transparent",clearChatIconColor:"palette.colors.gray.500",clearChatBackgroundColor:"transparent",micIconColor:"palette.colors.gray.900",micBackgroundColor:"transparent",recordingIconColor:"palette.colors.white",recordingBackgroundColor:"palette.colors.error.500",tooltipBackground:"palette.colors.gray.900",tooltipForeground:"palette.colors.white"},_l={radiusSm:"palette.radius.md",radiusMd:"palette.radius.lg",radiusLg:"palette.radius.xl",launcherRadius:"palette.radius.full",buttonRadius:"palette.radius.full"};function Ko(e,n={}){if(!e)return{};let t={palette:{colors:{primary:{},gray:{},secondary:{},accent:{},success:{},warning:{},error:{}}},semantic:{colors:{interactive:{},feedback:{}}}};for(let[r,s]of Object.entries(e))if(s)if(r in Es){let o=Es[r],[a,i,d,c]=o.split(".");if(a==="palette"&&i==="colors"){let g=d;t.palette.colors[g]&&(t.palette.colors[g][c||"500"]=s)}else if(a==="semantic"){let g=o.replace("semantic.colors.","").split(".");g.length===1?t.semantic.colors[g[0]]=s:t.semantic.colors[g[0]]={...t.semantic.colors[g[0]],[g[1]]:s}}}else if(r in _l){t.palette.radius||(t.palette.radius={});let o=r.replace("radius","").toLowerCase();t.palette.radius[o||"md"]=s}else r==="inputFontFamily"?(t.palette.typography||(t.palette.typography={fontFamily:{}}),t.palette.typography.fontFamily={sans:s==="sans-serif"?"system-ui, sans-serif":void 0,serif:s==="serif"?"Georgia, serif":void 0,mono:s==="mono"?"monospace":void 0}):r==="inputFontWeight"?(t.palette.typography||(t.palette.typography={fontWeight:{}}),t.palette.typography.fontWeight={normal:s}):r==="panelBorder"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.border=s):r==="panelShadow"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.shadow=s):r==="panelBorderRadius"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.borderRadius=s):r==="messageUserShadow"?(t.components||(t.components={}),t.components.message||(t.components.message={}),t.components.message.user||(t.components.message.user={}),t.components.message.user.shadow=s):r==="messageAssistantShadow"?(t.components||(t.components={}),t.components.message||(t.components.message={}),t.components.message.assistant||(t.components.message.assistant={}),t.components.message.assistant.shadow=s):r==="toolBubbleShadow"?(t.components||(t.components={}),t.components.toolBubble||(t.components.toolBubble={}),t.components.toolBubble.shadow=s):r==="reasoningBubbleShadow"?(t.components||(t.components={}),t.components.reasoningBubble||(t.components.reasoningBubble={}),t.components.reasoningBubble.shadow=s):r==="composerShadow"&&(t.components||(t.components={}),t.components.composer||(t.components.composer={}),t.components.composer.shadow=s);return n.warn!==!1&&console.warn("[Persona Widget] v1 theme configuration detected. v1 themes are deprecated in v2.0.0. Please migrate to the new semantic token system. See https://persona.sh/docs/v2-migration for guidance."),t}function jl(e){let n=[],t=e;if(!t)return{valid:!0,warnings:[]};let r=new Set(["panelBorder","panelShadow","panelBorderRadius","messageUserShadow","messageAssistantShadow","toolBubbleShadow","reasoningBubbleShadow","composerShadow"]),s=Object.keys(t).filter(o=>!(o in Es||o in _l||o==="inputFontFamily"||o==="inputFontWeight"||o.startsWith("panel")||r.has(o)));return s.length>0&&n.push(`The following v1 theme properties have no v2 equivalent and will be ignored: ${s.join(", ")}`),{valid:!0,warnings:n}}var vd={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}}},Ts=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ms=(e,n)=>{if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];Ts(o)&&Ts(s)?t[r]=Ms(o,s):t[r]=s}return t},Cd=e=>Ts(e)&&("palette"in e||"semantic"in e||"components"in e),Vl=e=>{if(!e)return;let n=Ko(e,{warn:!1});return Cd(e)?Ms(n,e):n},to=()=>{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"},wd=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":to()},ks=e=>wd(e),Sd=e=>Cr(e),Ad=e=>{var t;let n=Cr(void 0,{validate:!1});return Cr({...e,palette:{...n.palette,colors:{...vd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Ls=e=>{let n=ks(e),t=Vl(e==null?void 0:e.theme),r=Vl(e==null?void 0:e.darkTheme);return n==="dark"?Ad(Ms(t,r)):Sd(t)},Ed=e=>Jo(e),On=(e,n)=>{var o;let t=Ls(n),r=Ed(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Yo=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(to())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(to());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};var Ul=require("idiomorph"),ql=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Ul.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&r&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function zl(e,n){var t,r,s,o,a,i,d,c,g,p,y,m,C,v,E,x,k,q;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(g=(c=e.llmContent)==null?void 0:c.length)!=null?g:0,(y=(p=e.approval)==null?void 0:p.status)!=null?y:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(E=(v=e.reasoning)==null?void 0:v.chunks)==null?void 0:E.length)!=null?x:0,(q=(k=e.contentParts)==null?void 0:k.length)!=null?q:0,n].join("\0")}function Jl(){return new Map}function Kl(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Yl(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Xl(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}var jt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Td={side:"right",width:"420px",collapsedWidth:"72px"},Vt=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},wr=e=>{var n,t;return{...Td,...(t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock)!=null?t:{}}};var pn={"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 no=(e,n)=>{let t=f("button");t.type="button",t.innerHTML=`
|
|
6
|
+
`);a=(Wt=we.pop())!=null?Wt:"";for(let $e of we){let vt=$e.split(`
|
|
7
|
+
`),Ot="message",Ct="";for(let T of vt)T.startsWith("event:")?Ot=T.replace("event:","").trim():T.startsWith("data:")&&(Ct+=T.replace("data:","").trim());if(!Ct)continue;let b;try{b=JSON.parse(Ct)}catch(T){t({type:"error",error:T instanceof Error?T:new Error("Failed to parse chat stream payload")});continue}let De=Ot!=="message"?Ot:(de=b.type)!=null?de:"message";if((ie=this.onSSEEvent)==null||ie.call(this,De,b),this.parseSSEEvent){m.current=f;let T=await this.handleCustomSSEEvent(b,t,m,p,c);if(m.current&&!f&&(f=m.current),T)continue}if(De==="reason_start"){let T=(qe=F(b,!0))!=null?qe:`reason-${c()}`,A=re(T);A.reasoning=(j=A.reasoning)!=null?j:{id:T,status:"streaming",chunks:[]},A.reasoning.startedAt=(be=A.reasoning.startedAt)!=null?be:te((G=b.startedAt)!=null?G:b.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",p(A)}else if(De==="reason_delta"||De==="reason_chunk"){let T=(X=(ze=F(b,!1))!=null?ze:F(b,!0))!=null?X:`reason-${c()}`,A=re(T);A.reasoning=(K=A.reasoning)!=null?K:{id:T,status:"streaming",chunks:[]},A.reasoning.startedAt=(We=A.reasoning.startedAt)!=null?We:te((tt=b.startedAt)!=null?tt:b.timestamp);let W=(_t=(Tt=(Ve=b.reasoningText)!=null?Ve:b.text)!=null?Tt:b.delta)!=null?_t:"";if(W&&b.hidden!==!0&&A.reasoning.chunks.push(String(W)),A.reasoning.status=b.done?"complete":"streaming",b.done){A.reasoning.completedAt=te((ce=b.completedAt)!=null?ce:b.timestamp);let le=(Je=A.reasoning.startedAt)!=null?Je:Date.now();A.reasoning.durationMs=Math.max(0,((Me=A.reasoning.completedAt)!=null?Me:Date.now())-le)}A.streaming=A.reasoning.status!=="complete",p(A)}else if(De==="reason_complete"){let T=(je=(nt=F(b,!1))!=null?nt:F(b,!0))!=null?je:`reason-${c()}`,A=C.get(T);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=te((Ze=b.completedAt)!=null?Ze:b.timestamp);let le=(Rt=A.reasoning.startedAt)!=null?Rt:Date.now();A.reasoning.durationMs=Math.max(0,((Ht=A.reasoning.completedAt)!=null?Ht:Date.now())-le),A.streaming=!1,p(A)}let W=q(b);W&&E.byStep.delete(W)}else if(De==="tool_start"){let T=(Mt=ye(b,!0))!=null?Mt:`tool-${c()}`,A=(B=b.toolName)!=null?B:b.name;if(Xe(A)){ae.add(T);continue}let W=ee(T),le=(Z=W.toolCall)!=null?Z:{id:T,status:"pending"};le.name=A!=null?A:le.name,le.status="running",b.args!==void 0?le.args=b.args:b.parameters!==void 0&&(le.args=b.parameters),le.startedAt=(_=le.startedAt)!=null?_:te((J=b.startedAt)!=null?J:b.timestamp),le.completedAt=void 0,le.durationMs=void 0,W.toolCall=le,W.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(W.agentMetadata={executionId:(xe=Se==null?void 0:Se.executionId)!=null?xe:b.executionId,iteration:(Le=Se==null?void 0:Se.iteration)!=null?Le:b.iteration}),p(W)}else if(De==="tool_chunk"||De==="tool_delta"){let T=(pt=(He=ye(b,!1))!=null?He:ye(b,!0))!=null?pt:`tool-${c()}`;if(ae.has(T))continue;let A=ee(T),W=(ve=A.toolCall)!=null?ve:{id:T,status:"running"};W.startedAt=(Be=W.startedAt)!=null?Be:te((Ce=b.startedAt)!=null?Ce:b.timestamp);let le=(Zt=(bt=(ue=b.text)!=null?ue:b.delta)!=null?bt:b.message)!=null?Zt:"";le&&(W.chunks=(un=W.chunks)!=null?un:[],W.chunks.push(String(le))),W.status="running",A.toolCall=W,A.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(A.agentMetadata=(Rn=A.agentMetadata)!=null?Rn:{executionId:(gn=Se==null?void 0:Se.executionId)!=null?gn:b.executionId,iteration:(go=Se==null?void 0:Se.iteration)!=null?go:b.iteration}),p(A)}else if(De==="tool_complete"){let T=(Qe=(lr=ye(b,!1))!=null?lr:ye(b,!0))!=null?Qe:`tool-${c()}`;if(ae.has(T)){ae.delete(T);continue}let A=ee(T),W=(mn=A.toolCall)!=null?mn:{id:T,status:"running"};W.status="complete",b.result!==void 0&&(W.result=b.result),typeof b.duration=="number"&&(W.duration=b.duration),W.completedAt=te((Hn=b.completedAt)!=null?Hn:b.timestamp);let le=(ln=b.duration)!=null?ln:b.executionTime;if(typeof le=="number")W.durationMs=le;else{let kt=(Wr=W.startedAt)!=null?Wr:Date.now();W.durationMs=Math.max(0,((fn=W.completedAt)!=null?fn:Date.now())-kt)}A.toolCall=W,A.streaming=!1;let Se=b.agentContext;(Se||b.executionId)&&(A.agentMetadata=(wn=A.agentMetadata)!=null?wn:{executionId:(dt=Se==null?void 0:Se.executionId)!=null?dt:b.executionId,iteration:(nn=Se==null?void 0:Se.iteration)!=null?nn:b.iteration}),p(A);let ot=M(b);ot&&x.byCall.delete(ot)}else if(De==="step_chunk"||De==="step_delta"){let T=b.stepType,A=b.executionType;if(T==="tool"||A==="context")continue;let W=N(),le=(Dn=(Hr=(cr=(Rr=b.text)!=null?Rr:b.delta)!=null?cr:b.content)!=null?Hr:b.chunk)!=null?Dn:"";if(le){let ot=((hn=oe.get(W.id))!=null?hn:"")+le;W.rawContent=ot,U.has(W.id)||U.set(W.id,this.createStreamParser());let kt=U.get(W.id),wt=ot.trim().startsWith("{")||ot.trim().startsWith("[");if(wt&&oe.set(W.id,ot),kt.__isPlainTextParser===!0){W.content+=le,oe.delete(W.id),U.delete(W.id),W.rawContent=void 0,p(W);continue}let Lt=kt.processChunk(ot);if(Lt instanceof Promise)Lt.then(st=>{var At;let lt=typeof st=="string"?st:(At=st==null?void 0:st.text)!=null?At:null;if(lt!==null&<.trim()!==""){let ct=f;ct&&ct.id===W.id&&(ct.content=lt,p(ct))}else if(!wt&&!ot.trim().startsWith("<")){let ct=f;ct&&ct.id===W.id&&(ct.content+=le,oe.delete(ct.id),U.delete(ct.id),ct.rawContent=void 0,p(ct))}}).catch(()=>{W.content+=le,oe.delete(W.id),U.delete(W.id),W.rawContent=void 0,p(W)});else{let st=typeof Lt=="string"?Lt:(_n=Lt==null?void 0:Lt.text)!=null?_n:null;st!==null&&st.trim()!==""?(W.content=st,p(W)):!wt&&!ot.trim().startsWith("<")&&(W.content+=le,oe.delete(W.id),U.delete(W.id),W.rawContent=void 0,p(W))}}if(b.isComplete){let Se=(yn=(xt=b.result)==null?void 0:xt.response)!=null?yn:W.content;if(Se){let ot=oe.get(W.id),kt=ot!=null?ot:D(Se);W.rawContent=kt;let wt=U.get(W.id),Bt=null,Lt=!1;if(wt&&(Bt=wt.getExtractedText(),Bt===null&&(Bt=Bo(kt)),Bt===null)){let st=wt.processChunk(kt);st instanceof Promise?(Lt=!0,st.then(lt=>{var ct;let At=typeof lt=="string"?lt:(ct=lt==null?void 0:lt.text)!=null?ct:null;if(At!==null){let Ft=f;Ft&&Ft.id===W.id&&(Ft.content=At,Ft.streaming=!1,U.delete(Ft.id),oe.delete(Ft.id),p(Ft))}})):Bt=typeof st=="string"?st:(Br=st==null?void 0:st.text)!=null?Br:null}if(!Lt){Bt!==null&&Bt.trim()!==""?W.content=Bt:oe.has(W.id)||(W.content=D(Se));let st=U.get(W.id);if(st){let lt=(Bn=st.close)==null?void 0:Bn.call(st);lt instanceof Promise&<.catch(()=>{}),U.delete(W.id)}oe.delete(W.id),W.streaming=!1,p(W)}}}}else if(De==="step_complete"){let T=b.stepType,A=b.executionType;if(T==="tool"||A==="context")continue;let W=(bn=b.result)==null?void 0:bn.response,le=N();if(W!=null){let Se=U.get(le.id),ot=!1,kt=!1;if(Se){let wt=Se.getExtractedText(),Bt=oe.get(le.id),Lt=Bt!=null?Bt:D(W);if(le.rawContent=Lt,wt!==null&&wt.trim()!=="")le.content=wt,ot=!0;else{let st=Bo(Lt);if(st!==null)le.content=st,ot=!0;else{let lt=Se.processChunk(Lt);if(lt instanceof Promise)kt=!0,lt.then(At=>{var Ft;let ct=typeof At=="string"?At:(Ft=At==null?void 0:At.text)!=null?Ft:null;if(ct!==null&&ct.trim()!==""){let Yt=f;Yt&&Yt.id===le.id&&(Yt.content=ct,Yt.streaming=!1,U.delete(Yt.id),oe.delete(Yt.id),p(Yt))}else{let Yt=Se.getExtractedText(),on=f;on&&on.id===le.id&&(Yt!==null&&Yt.trim()!==""?on.content=Yt:oe.has(on.id)||(on.content=D(W)),on.streaming=!1,U.delete(on.id),oe.delete(on.id),p(on))}});else{let At=typeof lt=="string"?lt:(H=lt==null?void 0:lt.text)!=null?H:null;if(At!==null&&At.trim()!=="")le.content=At,ot=!0;else{let ct=Se.getExtractedText();ct!==null&&ct.trim()!==""&&(le.content=ct,ot=!0)}}}}}if(!kt){if(!le.rawContent){let wt=oe.get(le.id);le.rawContent=wt!=null?wt:D(W)}if(!ot&&!oe.has(le.id)&&(le.content=D(W)),Se){let wt=(Fn=Se.close)==null?void 0:Fn.call(Se);wt instanceof Promise&&wt.catch(()=>{})}U.delete(le.id),oe.delete(le.id),le.streaming=!1,p(le)}}else U.delete(le.id),oe.delete(le.id),le.streaming=!1,p(le)}else if(De==="flow_complete"){let T=($n=b.result)==null?void 0:$n.response;if(T!=null){let A=N(),W=oe.get(A.id),le=W!=null?W:D(T);A.rawContent=le;let Se=D(T),ot=U.get(A.id);if(ot){let Bt=Bo(le);if(Bt!==null)Se=Bt;else{let Lt=ot.processChunk(le);Lt instanceof Promise&&Lt.then(lt=>{var ct;let At=typeof lt=="string"?lt:(ct=lt==null?void 0:lt.text)!=null?ct:null;if(At!==null){let Ft=f;Ft&&Ft.id===A.id&&(Ft.content=At,Ft.streaming=!1,p(Ft))}});let st=ot.getExtractedText();st!==null&&(Se=st)}}U.delete(A.id),oe.delete(A.id);let kt=Se!==A.content,wt=A.streaming!==!1;kt&&(A.content=Se),A.streaming=!1,(kt||wt)&&p(A)}else if(f!==null){let A=f;U.delete(A.id),oe.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}t({type:"status",status:"idle"})}else if(De==="agent_start")he={executionId:b.executionId,agentId:(Fr=b.agentId)!=null?Fr:"virtual",agentName:(Sn=b.agentName)!=null?Sn:"",status:"running",currentIteration:0,maxTurns:(jn=b.maxTurns)!=null?jn:1,startedAt:te(b.startedAt)};else if(De==="agent_iteration_start"){if(he&&(he.currentIteration=b.iteration),at==="separate"&&b.iteration>1){let T=f;T&&(T.streaming=!1,p(T),ht.set(b.iteration-1,T),f=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(b.contentType==="text"){let T=N();T.content+=($r=b.delta)!=null?$r:"",T.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:he==null?void 0:he.agentName},p(T)}else if(b.contentType==="thinking"){let T=(An=b.turnId)!=null?An:`agent-think-${b.iteration}`,A=re(T);A.reasoning=(En=A.reasoning)!=null?En:{id:T,status:"streaming",chunks:[]},A.reasoning.chunks.push((dr=b.delta)!=null?dr:""),A.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},p(A)}else if(b.contentType==="tool_input"){let T=(pr=b.toolCallId)!=null?pr:x.lastId;if(T){let A=v.get(T);A!=null&&A.toolCall&&(A.toolCall.chunks=(mo=A.toolCall.chunks)!=null?mo:[],A.toolCall.chunks.push((fo=b.delta)!=null?fo:""),p(A))}}}else if(De==="agent_turn_complete"){let T=b.turnId;if(T){let A=C.get(T);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=te(b.completedAt);let W=(ho=A.reasoning.startedAt)!=null?ho:Date.now();A.reasoning.durationMs=Math.max(0,((Nr=A.reasoning.completedAt)!=null?Nr:Date.now())-W),A.streaming=!1,p(A)}}}else if(De==="agent_tool_start"){let T=(ur=b.toolCallId)!=null?ur:`agent-tool-${c()}`;Y(M(b),T);let A=ee(T),W=(Ue=A.toolCall)!=null?Ue:{id:T,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};W.name=(rn=(Or=b.toolName)!=null?Or:b.name)!=null?rn:W.name,W.status="running",b.parameters!==void 0&&(W.args=b.parameters),W.startedAt=te((Kt=b.startedAt)!=null?Kt:b.timestamp),A.toolCall=W,A.streaming=!0,A.agentMetadata={executionId:b.executionId,iteration:b.iteration},p(A)}else if(De==="agent_tool_delta"){let T=(yo=b.toolCallId)!=null?yo:x.lastId;if(T){let A=(bo=v.get(T))!=null?bo:ee(T);A.toolCall&&(A.toolCall.chunks=(Dr=A.toolCall.chunks)!=null?Dr:[],A.toolCall.chunks.push((Vn=b.delta)!=null?Vn:""),A.toolCall.status="running",A.streaming=!0,p(A))}}else if(De==="agent_tool_complete"){let T=(Tn=b.toolCallId)!=null?Tn:x.lastId;if(T){let A=(xo=v.get(T))!=null?xo:ee(T);if(A.toolCall){A.toolCall.status="complete",b.result!==void 0&&(A.toolCall.result=b.result),typeof b.executionTime=="number"&&(A.toolCall.durationMs=b.executionTime),A.toolCall.completedAt=te((vo=b.completedAt)!=null?vo:b.timestamp),A.streaming=!1,p(A);let W=M(b);W&&x.byCall.delete(W)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let T=`agent-reflection-${b.executionId}-${b.iteration}`,A={id:T,role:"assistant",content:(Co=b.reflection)!=null?Co:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(hs=b.reflection)!=null?hs:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};p(A)}else if(De==="agent_complete"){he&&(he.status=b.success?"complete":"error",he.completedAt=te(b.completedAt),he.stopReason=b.stopReason);let T=f;T&&(T.streaming=!1,p(T)),t({type:"status",status:"idle"})}else if(De==="agent_error"){let T=typeof b.error=="string"?b.error:(gr=(Un=b.error)==null?void 0:Un.message)!=null?gr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",T):t({type:"error",error:new Error(T)})}else if(De!=="agent_ping")if(De==="agent_approval_start"){let T=(mt=b.approvalId)!=null?mt:`approval-${c()}`,A={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(mr=he==null?void 0:he.agentId)!=null?mr:"virtual",executionId:(_r=(fr=b.executionId)!=null?fr:he==null?void 0:he.executionId)!=null?_r:"",toolName:(jr=b.toolName)!=null?jr:"",toolType:b.toolType,description:(Ur=b.description)!=null?Ur:`Execute ${(Vr=b.toolName)!=null?Vr:"tool"}`,parameters:b.parameters}};p(A)}else if(De==="step_await"&&b.awaitReason==="approval_required"){let T=(qt=b.approvalId)!=null?qt:`approval-${c()}`,A={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Qt=he==null?void 0:he.agentId)!=null?Qt:"virtual",executionId:(Re=(Mn=b.executionId)!=null?Mn:he==null?void 0:he.executionId)!=null?Re:"",toolName:(qr=b.toolName)!=null?qr:"",toolType:b.toolType,description:(cn=b.description)!=null?cn:`Execute ${(qn=b.toolName)!=null?qn:"tool"}`,parameters:b.parameters}};p(A)}else if(De==="agent_approval_complete"){let T=b.approvalId;if(T){let W={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:(wo=b.decision)!=null?wo:"approved",agentId:(hr=he==null?void 0:he.agentId)!=null?hr:"virtual",executionId:(zn=(yr=b.executionId)!=null?yr:he==null?void 0:he.executionId)!=null?zn:"",toolName:(Nn=b.toolName)!=null?Nn:"",description:(So=b.description)!=null?So:"",resolvedAt:Date.now()}};p(W)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let T=b.artifactType,A=String(b.id),W=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:A,artifactType:T,title:W,component:typeof b.component=="string"?b.component:void 0}),Ie.set(A,{markdown:"",title:W}),!ge.has(A)){ge.add(A);let le={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:W,artifactType:T,status:"streaming"}})};z.set(A,le),p(le)}}else if(De==="artifact_delta"){let T=String(b.id),A=typeof b.delta=="string"?b.delta:String((Ao=b.delta)!=null?Ao:"");t({type:"artifact_delta",id:T,artDelta:A});let W=Ie.get(T);W&&(W.markdown+=A)}else if(De==="artifact_update"){let T=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:T,component:typeof b.component=="string"?b.component:void 0})}else if(De==="artifact_complete"){let T=String(b.id);t({type:"artifact_complete",id:T});let A=z.get(T);if(A){A.streaming=!1;try{let W=JSON.parse((dn=A.rawContent)!=null?dn:"{}");if(W.props){W.props.status="complete";let le=Ie.get(T);le!=null&&le.markdown&&(W.props.markdown=le.markdown)}A.rawContent=JSON.stringify(W)}catch{}Ie.delete(T),p(A),z.delete(T)}}}else if(De==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let A=String((Jn=T.id)!=null?Jn:`msg-${c()}`),W=T.role,Se={id:A,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(p(Se),Se.rawContent)try{let ot=JSON.parse(Se.rawContent),kt=(Eo=ot==null?void 0:ot.props)==null?void 0:Eo.artifactId;typeof kt=="string"&&ge.add(kt)}catch{}f=null,m.current=null,U.delete(A),oe.delete(A)}else De==="error"&&b.error&&t({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function Pl(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function vr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function er(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Do="[Image]";function Il(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Wl(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Rl(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Hl(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function _o(e){return{type:"text",text:e}}function Bl(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Fl(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function $l(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Nl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yd=["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"],Ln=[...Nl,...yd];function bd(e){return Nl.includes(e)||e.startsWith("image/")}function jo(e){return bd(e.type)}async function Ol(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;jo(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Dl(e,n=Ln,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function xd(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function _l(e,n){let t=xd(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var Vo=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Uo=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let g=0;g<a.length;g++)i+=a[g]*a[g];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var eo=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Uo;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let g=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,v=x=>{C||(C=!0,clearTimeout(E),m(new Error(x)))},E=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+g+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let k=x.code!==1006?` (code ${x.code})`:"";v("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Vo(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let 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=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let g=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:g});await this.sendAudio(p),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(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let c=0;c<t.length;c++)r[c]=t.charCodeAt(c);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var tr=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function nr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new eo(e.runtype);case"browser":if(!tr.isSupported())throw new Error("Browser speech recognition not supported");return new tr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function qo(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return nr({type:"runtype",runtype:e.runtype});if(tr.isSupported())return nr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function to(e){try{return qo(e),!0}catch{return!1}}var Cr=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,d;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=n.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return to((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=nr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var g,p,f,m,C,v;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((g=c.transcript)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}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 g,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(g=this.callbacks).onVoiceStatusChanged)==null||p.call(g,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(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,c,g;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=n.browser)==null?void 0:c.language)||"en-US",continuous:(g=n.browser)==null?void 0:g.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new Qn(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g}=n,f={id:a!=null?a:t==="user"?vr():t==="assistant"?er():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...g!==void 0&&{voiceProcessing:g}};return this.upsertMessage(f),f}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:p=!1}=r,m={id:d!=null?d:s==="user"?vr():s==="assistant"?er():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:p,...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(n,t){var c,g,p,f,m;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=vr(),o=er(),a={id:s,role:"user",content:r||Do,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 v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let E={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(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(C instanceof Error?(p=(g=this.callbacks).onError)==null||p.call(g,C):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(C))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=er();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(c){let g={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(g),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(n,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,c,g;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):p=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(g=(c=this.callbacks).onError)==null||g.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===r?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,c;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},vn=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};var vd=xl(require("lucide"),1),me=(e,n=24,t="currentColor",r=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=vd[s];return o?Cd(o,n,t,r):(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 Cd(e,n,t,r){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){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,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),s.appendChild(d)}}}),s}var zo={allowedTypes:Ln,maxFileSize:10*1024*1024,maxFiles:4};function wd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Sd(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 rr=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:zo.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:zo.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:zo.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:zo.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let g=Dl(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let p=(s=g.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await Ol(c),f=jo(c)?URL.createObjectURL(c):null,m={id:wd(),file:c,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=jo(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Sd(n.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=_l(n.file.type,n.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),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=me("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var Ss={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}},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"}},As={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",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.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.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"}},Es={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",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:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{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:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},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"}}};function jl(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?jl(e,r):r}function Jo(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=jl(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function Ts(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function Vl(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=Vl(o,s):t[r]=s}return t}function Ad(e,n){return n?Vl(e,n):e}function wr(e,n={}){var s,o,a,i,d,c,g,p,f,m,C,v,E;let t={palette:Ss,semantic:As,components:Es},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(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,...(g=e==null?void 0:e.semantic)==null?void 0:g.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...t.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Ad(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let x=Ts(r);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(k=>k.message).join(", ")}`)}if(n.plugins)for(let x of n.plugins)r=x.transform(r);return r}function Ko(e){var g,p,f,m,C,v,E,x,k,q,M,N,w,F,re,Y,ae,z,ge,Ie,Xe,ye,ee,te,D,U,oe,he,ht,at,gt,Wt,de,ie,qe,j,G,be,ze,X,K,tt,We,Ve,Tt,_t,ce,Je,Me,nt,je,Ze,Rt,Ht,Mt,B,Z,J;let n=Jo(e),t={};for(let[_,xe]of Object.entries(n)){let Le=_.replace(/\./g,"-");t[`--persona-${Le}`]=xe.value}t["--persona-primary"]=(g=t["--persona-semantic-colors-primary"])!=null?g:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(p=t["--persona-semantic-colors-secondary"])!=null?p:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(f=t["--persona-semantic-colors-accent"])!=null?f:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(m=t["--persona-semantic-colors-surface"])!=null?m:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(C=t["--persona-semantic-colors-background"])!=null?C:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(v=t["--persona-semantic-colors-container"])!=null?v:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(E=t["--persona-semantic-colors-text"])!=null?E:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(x=t["--persona-semantic-colors-text-muted"])!=null?x:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(k=t["--persona-semantic-colors-text-inverse"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(q=t["--persona-semantic-colors-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(M=t["--persona-semantic-colors-divider"])!=null?M:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(N=t["--persona-components-voice-recording-indicator"])!=null?N:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(w=t["--persona-components-voice-recording-background"])!=null?w:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(F=t["--persona-components-voice-processing-icon"])!=null?F:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(re=t["--persona-components-voice-speaking-icon"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Y=t["--persona-components-approval-requested-background"])!=null?Y:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ae=t["--persona-components-approval-requested-border"])!=null?ae:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(z=t["--persona-components-approval-requested-text"])!=null?z:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ge=t["--persona-components-approval-approve-background"])!=null?ge:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Ie=t["--persona-components-approval-deny-background"])!=null?Ie:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Xe=t["--persona-components-attachment-image-background"])!=null?Xe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ye=t["--persona-components-attachment-image-border"])!=null?ye:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ee=t["--persona-semantic-typography-fontFamily"])!=null?ee:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(te=t["--persona-semantic-typography-fontSize"])!=null?te:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(D=t["--persona-semantic-typography-fontWeight"])!=null?D:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(U=t["--persona-semantic-typography-lineHeight"])!=null?U:t["--persona-palette-typography-lineHeight-normal"],t["--persona-radius-sm"]=(oe=t["--persona-palette-radius-sm"])!=null?oe:"0.125rem",t["--persona-radius-md"]=(he=t["--persona-palette-radius-md"])!=null?he:"0.375rem",t["--persona-radius-lg"]=(ht=t["--persona-palette-radius-lg"])!=null?ht:"0.5rem",t["--persona-radius-xl"]=(at=t["--persona-palette-radius-xl"])!=null?at:"0.75rem",t["--persona-launcher-radius"]=(Wt=(gt=t["--persona-components-launcher-borderRadius"])!=null?gt:t["--persona-palette-radius-full"])!=null?Wt:"9999px",t["--persona-button-radius"]=(ie=(de=t["--persona-components-button-primary-borderRadius"])!=null?de:t["--persona-palette-radius-full"])!=null?ie:"9999px",t["--persona-panel-radius"]=(j=(qe=t["--persona-components-panel-borderRadius"])!=null?qe:t["--persona-radius-xl"])!=null?j:"0.75rem",t["--persona-input-radius"]=(be=(G=t["--persona-components-input-borderRadius"])!=null?G:t["--persona-radius-lg"])!=null?be:"0.5rem",t["--persona-message-user-radius"]=(X=(ze=t["--persona-components-message-user-borderRadius"])!=null?ze:t["--persona-radius-lg"])!=null?X:"0.5rem",t["--persona-message-assistant-radius"]=(tt=(K=t["--persona-components-message-assistant-borderRadius"])!=null?K:t["--persona-radius-lg"])!=null?tt:"0.5rem",t["--persona-header-bg"]=(We=t["--persona-components-header-background"])!=null?We:t["--persona-surface"],t["--persona-header-border"]=(Ve=t["--persona-components-header-border"])!=null?Ve:t["--persona-divider"],t["--persona-message-user-bg"]=(Tt=t["--persona-components-message-user-background"])!=null?Tt:t["--persona-accent"],t["--persona-message-user-text"]=(_t=t["--persona-components-message-user-text"])!=null?_t:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(ce=t["--persona-components-message-user-shadow"])!=null?ce:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Je=t["--persona-components-message-assistant-background"])!=null?Je:t["--persona-surface"],t["--persona-message-assistant-text"]=(Me=t["--persona-components-message-assistant-text"])!=null?Me:t["--persona-text"],t["--persona-message-assistant-border"]=(nt=t["--persona-components-message-assistant-border"])!=null?nt: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-tool-bubble-shadow"]=(Ze=t["--persona-components-toolBubble-shadow"])!=null?Ze:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Rt=t["--persona-components-reasoningBubble-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Ht=t["--persona-components-composer-shadow"])!=null?Ht:"none",t["--persona-md-inline-code-bg"]=(Mt=t["--persona-components-markdown-inlineCode-background"])!=null?Mt:t["--persona-container"],t["--persona-md-inline-code-color"]=(B=t["--persona-components-markdown-inlineCode-foreground"])!=null?B:t["--persona-text"],t["--persona-md-link-color"]=(J=(Z=t["--persona-components-markdown-link-foreground"])!=null?Z:t["--persona-accent"])!=null?J:"#3b82f6";let r=t["--persona-components-markdown-heading-h1-fontSize"];r&&(t["--persona-md-h1-size"]=r);let s=t["--persona-components-markdown-heading-h1-fontWeight"];s&&(t["--persona-md-h1-weight"]=s);let o=t["--persona-components-markdown-heading-h2-fontSize"];o&&(t["--persona-md-h2-size"]=o);let a=t["--persona-components-markdown-heading-h2-fontWeight"];a&&(t["--persona-md-h2-weight"]=a);let i=t["--persona-components-markdown-prose-fontFamily"];i&&i!=="inherit"&&(t["--persona-md-prose-font-family"]=i);let d=e.components,c=d==null?void 0:d.artifact;if(c!=null&&c.toolbar){let _=c.toolbar;_.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=_.iconHoverColor),_.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=_.iconHoverBackground),_.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=_.iconPadding),_.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=_.iconBorderRadius),_.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=_.iconBorder),_.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=_.toggleGroupGap),_.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=_.toggleBorderRadius),_.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=_.copyBackground),_.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=_.copyBorder),_.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=_.copyColor),_.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=_.copyBorderRadius),_.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=_.copyPadding),_.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=_.copyMenuBackground),_.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=_.copyMenuBorder),_.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=_.copyMenuShadow),_.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=_.copyMenuBorderRadius),_.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=_.copyMenuItemHoverBackground)}if(c!=null&&c.tab){let _=c.tab;_.background&&(t["--persona-artifact-tab-bg"]=_.background),_.activeBackground&&(t["--persona-artifact-tab-active-bg"]=_.activeBackground),_.activeBorder&&(t["--persona-artifact-tab-active-border"]=_.activeBorder),_.borderRadius&&(t["--persona-artifact-tab-radius"]=_.borderRadius),_.textColor&&(t["--persona-artifact-tab-color"]=_.textColor)}if(c!=null&&c.pane){let _=c.pane;_.toolbarBackground&&(t["--persona-artifact-toolbar-bg"]=_.toolbarBackground)}return t}var Ul={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 Ms={primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.accent.600",surface:"palette.colors.gray.50",muted:"palette.colors.gray.500",container:"palette.colors.gray.100",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",messageBorder:"palette.colors.gray.200",inputBackground:"palette.colors.gray.50",callToAction:"palette.colors.gray.900",callToActionBackground:"palette.colors.gray.50",sendButtonBackgroundColor:"semantic.colors.primary",sendButtonTextColor:"semantic.colors.textInverse",sendButtonBorderColor:"semantic.colors.primary",closeButtonColor:"palette.colors.gray.500",closeButtonBackgroundColor:"transparent",clearChatIconColor:"palette.colors.gray.500",clearChatBackgroundColor:"transparent",micIconColor:"palette.colors.gray.900",micBackgroundColor:"transparent",recordingIconColor:"palette.colors.white",recordingBackgroundColor:"palette.colors.error.500",tooltipBackground:"palette.colors.gray.900",tooltipForeground:"palette.colors.white"},ql={radiusSm:"palette.radius.md",radiusMd:"palette.radius.lg",radiusLg:"palette.radius.xl",launcherRadius:"palette.radius.full",buttonRadius:"palette.radius.full"};function Yo(e,n={}){if(!e)return{};let t={palette:{colors:{primary:{},gray:{},secondary:{},accent:{},success:{},warning:{},error:{}}},semantic:{colors:{interactive:{},feedback:{}}}};for(let[r,s]of Object.entries(e))if(s)if(r in Ms){let o=Ms[r],[a,i,d,c]=o.split(".");if(a==="palette"&&i==="colors"){let g=d;t.palette.colors[g]&&(t.palette.colors[g][c||"500"]=s)}else if(a==="semantic"){let g=o.replace("semantic.colors.","").split(".");g.length===1?t.semantic.colors[g[0]]=s:t.semantic.colors[g[0]]={...t.semantic.colors[g[0]],[g[1]]:s}}}else if(r in ql){t.palette.radius||(t.palette.radius={});let o=r.replace("radius","").toLowerCase();t.palette.radius[o||"md"]=s}else r==="inputFontFamily"?(t.palette.typography||(t.palette.typography={fontFamily:{}}),t.palette.typography.fontFamily={sans:s==="sans-serif"?"system-ui, sans-serif":void 0,serif:s==="serif"?"Georgia, serif":void 0,mono:s==="mono"?"monospace":void 0}):r==="inputFontWeight"?(t.palette.typography||(t.palette.typography={fontWeight:{}}),t.palette.typography.fontWeight={normal:s}):r==="panelBorder"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.border=s):r==="panelShadow"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.shadow=s):r==="panelBorderRadius"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.borderRadius=s):r==="messageUserShadow"?(t.components||(t.components={}),t.components.message||(t.components.message={}),t.components.message.user||(t.components.message.user={}),t.components.message.user.shadow=s):r==="messageAssistantShadow"?(t.components||(t.components={}),t.components.message||(t.components.message={}),t.components.message.assistant||(t.components.message.assistant={}),t.components.message.assistant.shadow=s):r==="toolBubbleShadow"?(t.components||(t.components={}),t.components.toolBubble||(t.components.toolBubble={}),t.components.toolBubble.shadow=s):r==="reasoningBubbleShadow"?(t.components||(t.components={}),t.components.reasoningBubble||(t.components.reasoningBubble={}),t.components.reasoningBubble.shadow=s):r==="composerShadow"&&(t.components||(t.components={}),t.components.composer||(t.components.composer={}),t.components.composer.shadow=s);return n.warn!==!1&&console.warn("[Persona Widget] v1 theme configuration detected. v1 themes are deprecated in v2.0.0. Please migrate to the new semantic token system. See https://persona.sh/docs/v2-migration for guidance."),t}function zl(e){let n=[],t=e;if(!t)return{valid:!0,warnings:[]};let r=new Set(["panelBorder","panelShadow","panelBorderRadius","messageUserShadow","messageAssistantShadow","toolBubbleShadow","reasoningBubbleShadow","composerShadow"]),s=Object.keys(t).filter(o=>!(o in Ms||o in ql||o==="inputFontFamily"||o==="inputFontWeight"||o.startsWith("panel")||r.has(o)));return s.length>0&&n.push(`The following v1 theme properties have no v2 equivalent and will be ignored: ${s.join(", ")}`),{valid:!0,warnings:n}}var Ed={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}}},ks=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ls=(e,n)=>{if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];ks(o)&&ks(s)?t[r]=Ls(o,s):t[r]=s}return t},Td=e=>ks(e)&&("palette"in e||"semantic"in e||"components"in e),Jl=e=>{if(!e)return;let n=Yo(e,{warn:!1});return Td(e)?Ls(n,e):n},no=()=>{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"},Md=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":no()},Ps=e=>Md(e),kd=e=>wr(e),Ld=e=>{var t;let n=wr(void 0,{validate:!1});return wr({...e,palette:{...n.palette,colors:{...Ed.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Is=e=>{let n=Ps(e),t=Jl(e==null?void 0:e.theme),r=Jl(e==null?void 0:e.darkTheme);return n==="dark"?Ld(Ls(t,r)):kd(t)},Pd=e=>Ko(e),On=(e,n)=>{var o;let t=Is(n),r=Pd(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Go=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(no())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(no());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};var Kl=require("idiomorph"),Yl=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Kl.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&r&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function Gl(e,n){var t,r,s,o,a,i,d,c,g,p,f,m,C,v,E,x,k,q;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(g=(c=e.llmContent)==null?void 0:c.length)!=null?g:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(E=(v=e.reasoning)==null?void 0:v.chunks)==null?void 0:E.length)!=null?x:0,(q=(k=e.contentParts)==null?void 0:k.length)!=null?q:0,n].join("\0")}function Xl(){return new Map}function Zl(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Ql(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function ec(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}var Vt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Id={side:"right",width:"420px",collapsedWidth:"72px"},Ut=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},Sr=e=>{var n,t;return{...Id,...(t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock)!=null?t:{}}};var pn={"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 ro=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
8
8
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
9
9
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="persona-flex persona-flex-col persona-items-start persona-text-left">
|
|
@@ -12,12 +12,12 @@
|
|
|
12
12
|
<span class="persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
15
|
-
`,t.addEventListener("click",n);let r=o=>{var q,M,N,w,F,Q,K,oe,J,me,We,Ge;let a=(q=o.launcher)!=null?q:{},i=Vt(o),d=t.querySelector("[data-role='launcher-title']");d&&(d.textContent=(M=a.title)!=null?M:"Chat Assistant");let c=t.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(N=a.subtitle)!=null?N:"Get answers fast");let g=t.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ye=(w=a.agentIconSize)!=null?w:"40px";if(p.style.height=ye,p.style.width=ye,p.innerHTML="",a.agentIconName){let ee=parseFloat(ye)||24,Y=fe(a.agentIconName,ee*.6,"var(--persona-text-inverse, #ffffff)",2);Y?(p.appendChild(Y),p.style.display=""):(p.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(Q=a.agentIconText)!=null?Q:"\u{1F4AC}",p.style.display="")}let y=t.querySelector("[data-role='launcher-image']");if(y){let ye=(K=a.agentIconSize)!=null?K:"40px";y.style.height=ye,y.style.width=ye,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(oe=a.callToActionIconSize)!=null?oe:"32px";m.style.height=ye,m.style.width=ye,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let ee=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ee=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Y=parseFloat(ye)||24,_=Math.max(Y-ee,8),D=fe(a.callToActionIconName,_,"currentColor",2);D?m.appendChild(D):m.textContent=(J=a.callToActionIconText)!=null?J:"\u2197"}else m.textContent=(me=a.callToActionIconText)!=null?me:"\u2197"}let C=a.position&&pn[a.position]?pn[a.position]:pn["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer persona-z-50",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?E:`${v} ${C}`;let x="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";if(t.style.border=(We=a.border)!=null?We:x,t.style.boxShadow=(Ge=a.shadow)!=null?Ge:k,i){let ye=wr(o);t.style.width=`calc(${ye.collapsedWidth} - 16px)`,t.style.minWidth="40px",t.style.maxWidth=`calc(${ye.collapsedWidth} - 16px)`,t.style.justifyContent="center",t.style.padding="12px 0"}else t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.justifyContent="",t.style.padding=""},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Pn=e=>{var oe,J,me,We,Ge,ye,ee,Y,_,D,ue,be,gt,ct,mt,It,de,ae,U,ne,ie,Te,Xe,te,X,He,Ue,tt,Ut,Dt,ce,ze;let{config:n,showClose:t=!0}=e,r=f("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomWidth="1px",r.style.borderBottomStyle="solid",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))";let s=(oe=n==null?void 0:n.launcher)!=null?oe:{},o=(J=s.headerIconSize)!=null?J:"48px",a=(me=s.closeButtonSize)!=null?me:"32px",i=(We=s.closeButtonPlacement)!=null?We:"inline",d=(Ge=s.headerIconHidden)!=null?Ge:!1,c=s.headerIconName,g=f("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-bg-persona-primary persona-text-white persona-text-xl");if(g.style.height=o,g.style.width=o,!d)if(c){let ke=parseFloat(o)||24,nt=fe(c,ke*.6,"var(--persona-text-inverse, #ffffff)",1);nt?g.replaceChildren(nt):g.textContent=(ee=(ye=n==null?void 0:n.launcher)==null?void 0:ye.agentIconText)!=null?ee:"\u{1F4AC}"}else if((Y=n==null?void 0:n.launcher)!=null&&Y.iconUrl){let ke=f("img");ke.src=n.launcher.iconUrl,ke.alt="",ke.className="persona-rounded-xl persona-object-cover",ke.style.height=o,ke.style.width=o,g.replaceChildren(ke)}else g.textContent=(D=(_=n==null?void 0:n.launcher)==null?void 0:_.agentIconText)!=null?D:"\u{1F4AC}";let p=f("div","persona-flex persona-flex-col"),y=f("span","persona-text-base persona-font-semibold");y.textContent=(be=(ue=n==null?void 0:n.launcher)==null?void 0:ue.title)!=null?be:"Chat Assistant";let m=f("span","persona-text-xs persona-text-persona-muted");m.textContent=(ct=(gt=n==null?void 0:n.launcher)==null?void 0:gt.subtitle)!=null?ct:"Here to help you get answers fast",p.append(y,m),d?r.append(p):r.append(g,p);let C=(mt=s.clearChat)!=null?mt:{},v=(It=C.enabled)!=null?It:!0,E=(de=C.placement)!=null?de:"inline",x=null,k=null;if(v){let ke=(ae=C.size)!=null?ae:"32px",nt=(U=C.iconName)!=null?U:"refresh-cw",Ve=(ne=C.iconColor)!=null?ne:"",Ze=(ie=C.backgroundColor)!=null?ie:"",Wt=(Te=C.borderWidth)!=null?Te:"",Rt=(Xe=C.borderColor)!=null?Xe:"",Tt=(te=C.borderRadius)!=null?te:"",B=(X=C.paddingX)!=null?X:"",G=(He=C.paddingY)!=null?He:"",z=(Ue=C.tooltipText)!=null?Ue:"Clear chat",j=(tt=C.showTooltip)!=null?tt:!0;k=f("div",E==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),x=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),x.style.height=ke,x.style.width=ke,x.type="button",x.setAttribute("aria-label",z);let xe=fe(nt,"20px",Ve||"",1);if(xe&&x.appendChild(xe),Ve&&(x.style.color=Ve,x.classList.remove("persona-text-persona-muted")),Ze&&(x.style.backgroundColor=Ze,x.classList.remove("hover:persona-bg-gray-100")),Wt||Rt){let Pe=Wt||"0px",Be=Rt||"transparent";x.style.border=`${Pe} solid ${Be}`,x.classList.remove("persona-border-none")}if(Tt&&(x.style.borderRadius=Tt,x.classList.remove("persona-rounded-full")),B?(x.style.paddingLeft=B,x.style.paddingRight=B):(x.style.paddingLeft="",x.style.paddingRight=""),G?(x.style.paddingTop=G,x.style.paddingBottom=G):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),j&&z&&x&&k){let Pe=null,Be=()=>{if(Pe||!x)return;let ve=x.ownerDocument,Ce=ve.body;if(!Ce)return;Pe=vn(ve,"div","persona-clear-chat-tooltip"),Pe.textContent=z;let Fe=vn(ve,"div");Fe.className="persona-clear-chat-tooltip-arrow",Pe.appendChild(Fe);let ge=x.getBoundingClientRect();Pe.style.position="fixed",Pe.style.left=`${ge.left+ge.width/2}px`,Pe.style.top=`${ge.top-8}px`,Pe.style.transform="translate(-50%, -100%)",Ce.appendChild(Pe)},pt=()=>{Pe&&Pe.parentNode&&(Pe.parentNode.removeChild(Pe),Pe=null)};k.addEventListener("mouseenter",Be),k.addEventListener("mouseleave",pt),x.addEventListener("focus",Be),x.addEventListener("blur",pt),k._cleanupTooltip=()=>{pt(),k&&(k.removeEventListener("mouseenter",Be),k.removeEventListener("mouseleave",pt)),x&&(x.removeEventListener("focus",Be),x.removeEventListener("blur",pt))}}E==="inline"&&r.appendChild(k)}let q=f("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&E==="inline"?"":"persona-ml-auto"),M=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=a,M.style.width=a,M.type="button";let N=(Ut=s.closeButtonTooltipText)!=null?Ut:"Close chat",w=(Dt=s.closeButtonShowTooltip)!=null?Dt:!0;M.setAttribute("aria-label",N),M.style.display=t?"":"none";let F=(ce=s.closeButtonIconName)!=null?ce:"x",Q=(ze=s.closeButtonIconText)!=null?ze:"\xD7",K=fe(F,"20px",s.closeButtonColor||"",1);if(K?M.appendChild(K):M.textContent=Q,s.closeButtonColor?(M.style.color=s.closeButtonColor,M.classList.remove("persona-text-persona-muted")):(M.style.color="",M.classList.add("persona-text-persona-muted")),s.closeButtonBackgroundColor?(M.style.backgroundColor=s.closeButtonBackgroundColor,M.classList.remove("hover:persona-bg-gray-100")):(M.style.backgroundColor="",M.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let ke=s.closeButtonBorderWidth||"0px",nt=s.closeButtonBorderColor||"transparent";M.style.border=`${ke} solid ${nt}`,M.classList.remove("persona-border-none")}else M.style.border="",M.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(M.style.borderRadius=s.closeButtonBorderRadius,M.classList.remove("persona-rounded-full")):(M.style.borderRadius="",M.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(M.style.paddingLeft=s.closeButtonPaddingX,M.style.paddingRight=s.closeButtonPaddingX):(M.style.paddingLeft="",M.style.paddingRight=""),s.closeButtonPaddingY?(M.style.paddingTop=s.closeButtonPaddingY,M.style.paddingBottom=s.closeButtonPaddingY):(M.style.paddingTop="",M.style.paddingBottom=""),q.appendChild(M),w&&N){let ke=null,nt=()=>{if(ke)return;let Ze=M.ownerDocument,Wt=Ze.body;if(!Wt)return;ke=vn(Ze,"div","persona-clear-chat-tooltip"),ke.textContent=N;let Rt=vn(Ze,"div");Rt.className="persona-clear-chat-tooltip-arrow",ke.appendChild(Rt);let Tt=M.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${Tt.left+Tt.width/2}px`,ke.style.top=`${Tt.top-8}px`,ke.style.transform="translate(-50%, -100%)",Wt.appendChild(ke)},Ve=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};q.addEventListener("mouseenter",nt),q.addEventListener("mouseleave",Ve),M.addEventListener("focus",nt),M.addEventListener("blur",Ve),q._cleanupTooltip=()=>{Ve(),q.removeEventListener("mouseenter",nt),q.removeEventListener("mouseleave",Ve),M.removeEventListener("focus",nt),M.removeEventListener("blur",Ve)}}return i!=="top-right"&&r.appendChild(q),{header:r,iconHolder:g,headerTitle:y,headerSubtitle:m,closeButton:M,closeButtonWrapper:q,clearChatButton:x,clearChatButtonWrapper:k}},or=(e,n,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var Ps=e=>{var r;let n=Pn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function Md(e,n,t){var r,s;if(n!=null&&n.length)for(let o of n){let a=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(a.type="button",a.setAttribute("aria-label",(s=(r=o.ariaLabel)!=null?r:o.label)!=null?s:o.id),o.icon){let i=fe(o.icon,14,"currentColor",2);i&&a.appendChild(i)}else o.label&&(a.textContent=o.label);a.addEventListener("click",()=>t==null?void 0:t(o.id)),e.appendChild(a)}}var Is=e=>{var x,k,q,M,N;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(x=n==null?void 0:n.launcher)!=null?x:{},i=f("div","persona-flex persona-items-center persona-justify-between persona-bg-persona-surface persona-px-6 persona-py-4 persona-border-b-persona-divider");i.setAttribute("data-persona-theme-zone","header");let d=f("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=f("span","persona-text-base persona-font-semibold persona-truncate");if(c.textContent=(k=a.title)!=null?k:"Chat Assistant",d.appendChild(c),Md(d,s==null?void 0:s.trailingActions,(q=s==null?void 0:s.onAction)!=null?q:o),s!=null&&s.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let w=s.onTitleClick;d.addEventListener("click",F=>{F.target.closest("button")||w()}),d.addEventListener("keydown",F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),w())})}i.appendChild(d);let g=(M=a.closeButtonSize)!=null?M:"32px",p=f("div",""),y=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");y.style.height=g,y.style.width=g,y.type="button",y.setAttribute("aria-label","Close chat"),y.style.display=t?"":"none";let m=(N=a.closeButtonIconName)!=null?N:"x",C=fe(m,"20px",a.closeButtonColor||"",2);C?y.appendChild(C):y.textContent="\xD7",r&&y.addEventListener("click",r),p.appendChild(y),i.appendChild(p);let v=f("div");v.style.display="none";let E=f("span");return E.style.display="none",{header:i,iconHolder:v,headerTitle:c,headerSubtitle:E,closeButton:y,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},Xo={default:Ps,minimal:Is},Ws=e=>{var n;return(n=Xo[e])!=null?n:Xo.default},Sr=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let c=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),g=f("div");g.style.display="none";let p=f("span"),y=f("span"),m=f("button");m.style.display="none";let C=f("div");return C.style.display="none",{header:c,iconHolder:g,headerTitle:p,headerSubtitle:y,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=Ws(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var kd=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Ar=e=>{var de,ae,U,ne,ie,Te,Xe,te,X,He,Ue,tt,Ut,Dt,ce,ze,ke,nt,Ve,Ze,Wt,Rt,Tt,B,G,z,j,xe,Pe,Be,pt;let{config:n}=e,t=f("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=f("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=f("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let o=f("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(ae=(de=n==null?void 0:n.copy)==null?void 0:de.inputPlaceholder)!=null?ae:"Type your message\u2026",o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1;let a=(ne=(U=n==null?void 0:n.theme)==null?void 0:U.inputFontFamily)!=null?ne:"sans-serif",i=(Te=(ie=n==null?void 0:n.theme)==null?void 0:ie.inputFontWeight)!=null?Te:"400";o.style.fontFamily=kd(a),o.style.fontWeight=i;let g=3*20;o.style.maxHeight=`${g}px`,o.style.overflowY="auto";let p=()=>{o.style.height="auto";let ve=Math.min(o.scrollHeight,g);o.style.height=`${ve}px`};o.addEventListener("input",p),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let y=(Xe=n==null?void 0:n.sendButton)!=null?Xe:{},m=(te=y.useIcon)!=null?te:!1,C=(X=y.iconText)!=null?X:"\u2191",v=y.iconName,E=(He=y.tooltipText)!=null?He:"Send message",x=(Ue=y.showTooltip)!=null?Ue:!1,k=(tt=y.size)!=null?tt:"40px",q=y.backgroundColor,M=y.textColor,N=f("div","persona-send-button-wrapper"),w=f("button",m?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),m){if(w.style.width=k,w.style.height=k,w.style.minWidth=k,w.style.minHeight=k,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",v){let ve=parseFloat(k)||24,Ce=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",Fe=fe(v,ve,Ce,2);Fe?(w.appendChild(Fe),w.style.color=Ce):(w.textContent=C,M?w.style.color=M:w.classList.add("persona-text-white"))}else w.textContent=C,M?w.style.color=M:w.classList.add("persona-text-white");q?w.style.backgroundColor=q:w.classList.add("persona-bg-persona-primary")}else w.textContent=(Dt=(Ut=n==null?void 0:n.copy)==null?void 0:Ut.sendButtonLabel)!=null?Dt:"Send",M?w.style.color=M:w.classList.add("persona-text-white");if(y.borderWidth&&(w.style.borderWidth=y.borderWidth,w.style.borderStyle="solid"),y.borderColor&&(w.style.borderColor=y.borderColor),y.paddingX?(w.style.paddingLeft=y.paddingX,w.style.paddingRight=y.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),y.paddingY?(w.style.paddingTop=y.paddingY,w.style.paddingBottom=y.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),x&&E){let ve=f("div","persona-send-button-tooltip");ve.textContent=E,N.appendChild(ve)}N.appendChild(w);let F=(ce=n==null?void 0:n.voiceRecognition)!=null?ce:{},Q=F.enabled===!0,K=null,oe=null,J=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),me=((ze=F.provider)==null?void 0:ze.type)==="runtype";if(Q&&(J||me)){oe=f("div","persona-send-button-wrapper"),K=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),K.type="button",K.setAttribute("data-persona-composer-mic",""),K.setAttribute("aria-label","Start voice recognition");let ve=(ke=F.iconName)!=null?ke:"mic",Ce=(nt=F.iconSize)!=null?nt:k,Fe=parseFloat(Ce)||24,ge=(Ve=F.backgroundColor)!=null?Ve:q,bt=(Ze=F.iconColor)!=null?Ze:M;K.style.width=Ce,K.style.height=Ce,K.style.minWidth=Ce,K.style.minHeight=Ce,K.style.fontSize="18px",K.style.lineHeight="1";let Zt=bt||"currentColor",un=fe(ve,Fe,Zt,1.5);un?(K.appendChild(un),K.style.color=Zt):(K.textContent="\u{1F3A4}",K.style.color=Zt),ge?K.style.backgroundColor=ge:K.classList.add("persona-bg-persona-primary"),bt?K.style.color=bt:!bt&&!M&&K.classList.add("persona-text-white"),F.borderWidth&&(K.style.borderWidth=F.borderWidth,K.style.borderStyle="solid"),F.borderColor&&(K.style.borderColor=F.borderColor),F.paddingX&&(K.style.paddingLeft=F.paddingX,K.style.paddingRight=F.paddingX),F.paddingY&&(K.style.paddingTop=F.paddingY,K.style.paddingBottom=F.paddingY),oe.appendChild(K);let gn=(Wt=F.tooltipText)!=null?Wt:"Start voice recognition";if(((Rt=F.showTooltip)!=null?Rt:!1)&&gn){let Rn=f("div","persona-send-button-tooltip");Rn.textContent=gn,oe.appendChild(Rn)}}let Ge=(Tt=n==null?void 0:n.attachments)!=null?Tt:{},ye=Ge.enabled===!0,ee=null,Y=null,_=null,D=null;if(ye){D=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),D.style.display="none",_=f("input"),_.type="file",_.accept=((B=Ge.allowedTypes)!=null?B:Ln).join(","),_.multiple=((G=Ge.maxFiles)!=null?G:4)>1,_.style.display="none",_.setAttribute("aria-label","Attach files"),Y=f("div","persona-send-button-wrapper"),ee=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ee.type="button",ee.setAttribute("aria-label",(z=Ge.buttonTooltipText)!=null?z:"Attach file");let ve=(j=Ge.buttonIconName)!=null?j:"paperclip",Ce=k,Fe=parseFloat(Ce)||40,ge=Math.round(Fe*.6);ee.style.width=Ce,ee.style.height=Ce,ee.style.minWidth=Ce,ee.style.minHeight=Ce,ee.style.fontSize="18px",ee.style.lineHeight="1",ee.style.backgroundColor="transparent",ee.style.color="var(--persona-primary, #111827)",ee.style.border="none",ee.style.borderRadius="6px",ee.style.transition="background-color 0.15s ease",ee.addEventListener("mouseenter",()=>{ee.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ee.addEventListener("mouseleave",()=>{ee.style.backgroundColor="transparent"});let bt=fe(ve,ge,"currentColor",1.5);bt?ee.appendChild(bt):ee.textContent="\u{1F4CE}",ee.addEventListener("click",gn=>{gn.preventDefault(),_==null||_.click()}),Y.appendChild(ee);let Zt=(xe=Ge.buttonTooltipText)!=null?xe:"Attach file",un=f("div","persona-send-button-tooltip");un.textContent=Zt,Y.appendChild(un)}s.addEventListener("click",ve=>{ve.target!==w&&ve.target!==N&&ve.target!==K&&ve.target!==oe&&ve.target!==ee&&ve.target!==Y&&o.focus()}),D&&(D.style.gap="8px",s.append(D)),_&&s.append(_),s.append(o);let ue=f("div","persona-flex persona-items-center persona-justify-between persona-w-full"),be=f("div","persona-flex persona-items-center persona-gap-2");Y&&be.append(Y);let gt=f("div","persona-flex persona-items-center persona-gap-1");oe&>.append(oe),gt.append(N),ue.append(be,gt),s.append(ue);let ct=f("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");ct.setAttribute("data-persona-composer-status","");let mt=(Pe=n==null?void 0:n.statusIndicator)!=null?Pe:{},It=(Be=mt.visible)!=null?Be:!0;return ct.style.display=It?"":"none",ct.textContent=(pt=mt.idleText)!=null?pt:"Online",t.append(r,s,ct),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:N,micButton:K,micButtonWrapper:oe,statusText:ct,attachmentButton:ee,attachmentButtonWrapper:Y,attachmentInput:_,attachmentPreviewsContainer:D,actionsRow:ue,leftActions:be,rightActions:gt}};var Gl=e=>{var c,g,p,y,m,C,v;let n=(g=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?g:!0;if(Vt(e)){let E=f("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=f("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return E.appendChild(x),{wrapper:E,panel:x}}if(!n){let E=f("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=f("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),k=(y=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?y:"100%";return E.style.width=k,x.style.width="100%",E.appendChild(x),{wrapper:E,panel:x}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},s=r.position&&pn[r.position]?pn[r.position]:pn["bottom-right"],o=f("div",`persona-widget-wrapper persona-fixed ${s} persona-z-50 persona-transition`),a=f("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(v=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?v:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},Zl=(e,n=!0)=>{var v,E,x,k,q,M,N,w,F;let t=f("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let r=(v=e==null?void 0:e.layout)==null?void 0:v.header,s=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,o=r?Sr(e,r,{showClose:n}):Pn({config:e,showClose:n}),a=f("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=f("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm"),d=f("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let c=f("p","persona-mt-2 persona-text-sm persona-text-persona-muted");c.textContent=(M=(q=e==null?void 0:e.copy)==null?void 0:q.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",i.append(d,c);let g=f("div","persona-flex persona-flex-col persona-gap-3"),p=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;p&&(g.style.maxWidth=p,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((w=e==null?void 0:e.copy)==null?void 0:w.showWelcomeCard)!==!1?a.append(i,g):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(g));let m=Ar({config:e}),C=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;return s?or(t,o,e):(o.header.style.display="none",or(t,o,e)),t.append(a),C||(m.footer.style.display="none"),t.append(m.footer),{container:t,body:a,messagesWrapper:g,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:c,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions}};var Ld=320,Pd=320,Id=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Wd=(e,n,t)=>{if(e.length===0)return null;try{let r=f("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let c=f("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Ld}px`,c.style.maxHeight=`${Pd}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;s+=1,c.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{g=!0}),c.src=i.image,r.appendChild(c)}),s===0?(a(),null):r}catch{return t==null||t(),null}},sr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},Rs=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:sr};if(n){let s=n(r);if(s!==null)return s}return sr()},Rd=(e,n)=>{let t=f("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=f("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Ql=(e,n)=>{let t=f("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Hd=(e,n="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Hs=(e,n,t)=>{var m,C,v,E,x,k;let r=(m=n.showCopy)!=null?m:!0,s=(C=n.showUpvote)!=null?C:!0,o=(v=n.showDownvote)!=null?v:!0;if(!r&&!s&&!o){let q=f("div");return q.style.display="none",q.id=`actions-${e.id}`,q.setAttribute("data-actions-for",e.id),q}let a=(E=n.visibility)!=null?E:"hover",i=(x=n.align)!=null?x:"right",d=(k=n.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=f("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${g} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let y=(q,M,N)=>{let w=document.createElement("button");w.className="persona-message-action-btn",w.setAttribute("aria-label",M),w.setAttribute("title",M),w.setAttribute("data-action",N);let F=fe(q,14,"currentColor",2);return F&&w.appendChild(F),w};return r&&p.appendChild(y("copy","Copy message","copy")),s&&p.appendChild(y("thumbs-up","Upvote","upvote")),o&&p.appendChild(y("thumbs-down","Downvote","downvote")),p},Er=(e,n,t,r,s,o)=>{var oe,J,me,We,Ge,ye,ee;let a=t!=null?t:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,g=(J=d==null?void 0:d.show)!=null?J:!1,p=(me=c==null?void 0:c.show)!=null?me:!1,y=(We=d==null?void 0:d.position)!=null?We:"left",m=(Ge=c==null?void 0:c.position)!=null?Ge:"below",C=Hd(e.role,i),v=f("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=Id(e),x=(ee=(ye=e.content)==null?void 0:ye.trim())!=null?ee:"",q=E.length>0&&x===Oo,M=document.createElement("div");M.classList.add("persona-message-content");let N=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),w=null;if(q?(w=document.createElement("div"),w.innerHTML=N,w.style.display="none",M.appendChild(w)):M.innerHTML=N,p&&m==="inline"&&e.createdAt){let Y=Ql(e,c);Y.classList.add("persona-ml-2","persona-inline"),M.appendChild(Y)}if(E.length>0){let Y=Wd(E,!q&&!!x,()=>{q&&w&&(w.style.display="")});Y?v.appendChild(Y):q&&w&&(w.style.display="")}if(v.appendChild(M),p&&m==="below"&&e.createdAt){let Y=Ql(e,c);Y.classList.add("persona-mt-1"),v.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=Rs("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Y&&v.appendChild(Y)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Y=Hs(e,r,s);v.appendChild(Y)}if(!g||e.role==="system")return v;let Q=f("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),K=Rd(d,e.role);return y==="right"||y==="left"&&e.role==="user"?Q.append(v,K):Q.append(K,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Q},ec=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Er(e,n,t,r,s,o)};var Tr=new Set,tc=(e,n)=>{let t=Tr.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t");if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let o=r.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=fe(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},Bs=e=>{let n=e.reasoning,t=f("div",["vanilla-message-bubble","vanilla-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!n)return t;let r=Tr.has(e.id),s=f("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");s.type="button",s.setAttribute("aria-expanded",r?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=f("div","persona-flex persona-flex-col persona-text-left"),a=f("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=f("span","persona-text-xs persona-text-persona-primary");i.textContent=Sl(n),o.appendChild(i),n.status==="complete"?a.style.display="none":a.style.display="";let d=f("div","persona-flex persona-items-center"),g=fe(r?"chevron-up":"chevron-down",16,"currentColor",2);g?d.appendChild(g):d.textContent=r?"Hide":"Show";let p=f("div","persona-flex persona-items-center persona-ml-auto");p.append(d),s.append(o,p);let y=f("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");y.style.display=r?"":"none";let m=n.chunks.join(""),C=f("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return C.textContent=m||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),y.appendChild(C),(()=>{s.setAttribute("aria-expanded",r?"true":"false"),d.innerHTML="";let x=fe(r?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=r?"Hide":"Show",y.style.display=r?"":"none"})(),t.append(s,y),t};var Mr=new Set,nc=(e,n,t)=>{var c;let r=Mr.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=s.toggleTextColor||s.headerTextColor||"currentColor",p=fe(r?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=r?"Hide":"Show"}a.style.display=r?"":"none"},Fs=(e,n)=>{var v;let t=e.toolCall,r=(v=n==null?void 0:n.toolCall)!=null?v:{},s=f("div",["vanilla-message-bubble","vanilla-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=Mr.has(e.id),a=f("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(a.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(a.style.paddingLeft=r.headerPaddingX,a.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(a.style.paddingTop=r.headerPaddingY,a.style.paddingBottom=r.headerPaddingY);let i=f("div","persona-flex persona-flex-col persona-text-left"),d=f("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(d.style.color=r.headerTextColor),d.textContent=Al(t),i.appendChild(d);let c=f("div","persona-flex persona-items-center"),g=r.toggleTextColor||r.headerTextColor||"currentColor",p=fe(o?"chevron-up":"chevron-down",16,g,2);p?c.appendChild(p):c.textContent=o?"Hide":"Show";let y=f("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");y.append(c),a.append(i,y);let m=f("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",r.contentBackgroundColor&&(m.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(m.style.color=r.contentTextColor),r.contentPaddingX&&(m.style.paddingLeft=r.contentPaddingX,m.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(m.style.paddingTop=r.contentPaddingY,m.style.paddingBottom=r.contentPaddingY),t.name){let E=f("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?E.style.color=r.contentTextColor:r.headerTextColor&&(E.style.color=r.headerTextColor),E.textContent=t.name,m.appendChild(E)}if(t.args!==void 0){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Arguments";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=Zr(t.args),E.append(x,k),m.appendChild(E)}if(t.chunks&&t.chunks.length){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Activity";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=t.chunks.join(`
|
|
16
|
-
`),E.append(x,k),m.appendChild(E)}if(t.status==="complete"&&t.result!==void 0){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Result";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=Zr(t.result),E.append(x,k),m.appendChild(E)}if(t.status==="complete"&&typeof t.duration=="number"){let E=f("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(E.style.color=r.contentTextColor),E.textContent=`Duration: ${t.duration}ms`,m.appendChild(E)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let E=r.toggleTextColor||r.headerTextColor||"currentColor",x=fe(o?"chevron-up":"chevron-down",16,E,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var $s=(e,n)=>{var v,E,x,k,q,M,N,w,F,Q,K,oe;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=f("div",["persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(v=r==null?void 0:r.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(E=r==null?void 0:r.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!t)return o;let a=f("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=f("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(x=r==null?void 0:r.titleColor)!=null?x:"currentColor",g=fe(d,20,c,2);g&&i.appendChild(g);let p=f("div","persona-flex-1 persona-min-w-0"),y=f("div","persona-flex persona-items-center persona-gap-2"),m=f("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",y.appendChild(m),!s){let J=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",t.status),t.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):t.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):t.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),y.appendChild(J)}p.appendChild(y);let C=f("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(C.style.color=r.descriptionColor),C.textContent=t.description,p.appendChild(C),t.parameters){let J=f("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(J.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(J.style.color=r.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=Zr(t.parameters),p.appendChild(J)}if(s){let J=f("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let me=f("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");me.type="button",me.style.backgroundColor=(q=r==null?void 0:r.approveButtonColor)!=null?q:"var(--persona-approval-approve-bg, #22c55e)",me.style.color=(M=r==null?void 0:r.approveButtonTextColor)!=null?M:"#ffffff",me.setAttribute("data-approval-action","approve");let We=fe("shield-check",14,(N=r==null?void 0:r.approveButtonTextColor)!=null?N:"#ffffff",2);We&&(We.style.marginRight="4px",me.appendChild(We));let Ge=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");me.appendChild(Ge);let ye=f("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");ye.type="button",ye.style.backgroundColor=(F=r==null?void 0:r.denyButtonColor)!=null?F:"transparent",ye.style.color=(Q=r==null?void 0:r.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",ye.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ye.setAttribute("data-approval-action","deny");let ee=fe("shield-x",14,(K=r==null?void 0:r.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",ye.appendChild(ee));let Y=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");ye.appendChild(Y),J.append(me,ye),p.appendChild(J)}return a.append(i,p),o.appendChild(a),o};var rc=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let g=document.createDocumentFragment(),p=s?s.isStreaming():!1,y=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let C=f("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");C.type="button",C.textContent=m,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=y(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),g.appendChild(C),n.push(C)}),e.appendChild(g)}}};var ro=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var oo=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function kr(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Bd={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Fd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},$d=["flowName","stepName","reasoningText","text","name","tool","toolName"],Nd=100;function Od(e,n){let t={...Bd,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Fd}function Dd(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function _d(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function jd(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Vd(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Ud(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function qd(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=f("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=f("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Ns(e,n,t,r,s,o,a,i){var y;let d=s.has(e.id),c=f("div","persona-border-b persona-border-persona-divider persona-text-xs");kr(c,(y=r.classNames)==null?void 0:y.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var me,We;let m=f("div",""),C=f("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let v=f("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=fe(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let x=f("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(me=r.timestampFormat)!=null?me:"relative";x.textContent=k==="relative"?Dd(e.timestamp,t):_d(e.timestamp);let q=null;r.showSequenceNumbers!==!1&&(q=f("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),q.textContent=String(n+1));let M=Od(e.type,r.badgeColors),N=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");N.style.backgroundColor=M.bg,N.style.color=M.text,N.style.borderColor=M.text+"50",N.textContent=e.type;let w=(We=r.descriptionFields)!=null?We:$d,F=jd(e.payload,w),Q=null;F&&(Q=f("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Q.textContent=F);let K=f("div","persona-flex-1 persona-min-w-0"),oe=f("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),J=fe("clipboard","12px","currentColor",1.5);return J&&oe.appendChild(J),oe.addEventListener("click",async Ge=>{Ge.stopPropagation(),await Vd(Ud(e)),oe.innerHTML="";let ye=fe("check","12px","currentColor",1.5);ye&&oe.appendChild(ye),setTimeout(()=>{oe.innerHTML="";let ee=fe("clipboard","12px","currentColor",1.5);ee&&oe.appendChild(ee)},1500)}),C.appendChild(v),C.appendChild(x),q&&C.appendChild(q),C.appendChild(N),Q&&C.appendChild(Q),C.appendChild(K),C.appendChild(oe),m.appendChild(C),d&&m.appendChild(qd(e,a,i)),m}}function oc(e){var c,g;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[]}=e,a=(g=(c=s==null?void 0:s.features)==null?void 0:c.eventStream)!=null?g:{},i=o.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let p=i.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>d().element,onClose:r});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,y=f("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");kr(y,p==null?void 0:p.panel);let m=[],C="",v="",E=null,x=[],k={},q=0,M=!1,N=0,w=0,F=!1,Q=null,K=!1,oe=0,J=new Set,me=new Map,We="",Ge="",ye=null,ee,Y,_,D,ue;function be(){let G=f("div","persona-flex persona-flex-col persona-flex-shrink-0"),z=f("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");kr(z,p==null?void 0:p.headerBar);let j=f("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");j.textContent="Events",ee=f("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ee.textContent="0";let xe=f("div","persona-flex-1");Y=f("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Pe=f("option","");Pe.value="",Pe.textContent="All events",Y.appendChild(Pe),_=f("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),_.type="button",_.title="Copy All";let pt=fe("clipboard-copy","12px","currentColor",1.5);pt&&_.appendChild(pt);let ve=f("span","persona-text-xs");ve.textContent="Copy All",_.appendChild(ve),z.appendChild(j),z.appendChild(ee),z.appendChild(xe),z.appendChild(Y),z.appendChild(_);let Ce=f("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");kr(Ce,p==null?void 0:p.searchBar);let Fe=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),ge=f("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Fe&&ge.appendChild(Fe),D=f("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),kr(D,p==null?void 0:p.searchInput),D.type="text",D.placeholder="Search event payloads...",ue=f("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ue.type="button",ue.style.display="none";let bt=fe("x","12px","currentColor",2);return bt&&ue.appendChild(bt),Ce.appendChild(ge),Ce.appendChild(D),Ce.appendChild(ue),G.appendChild(z),G.appendChild(Ce),G}let gt,ct=o.find(G=>G.renderEventStreamToolbar);if(ct!=null&&ct.renderEventStreamToolbar&&s){let G=ct.renderEventStreamToolbar({config:s,defaultRenderer:()=>be(),eventCount:n.getSize(),filteredCount:0,onFilterChange:z=>{C=z,X(),tt()},onSearchChange:z=>{v=z,X(),tt()}});gt=G!=null?G:be()}else gt=be();let mt=f("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");mt.style.display="none";let It=f("div","persona-flex-1 persona-min-h-0 persona-relative"),de=f("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");de.style.height="100%";let ae=f("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");kr(ae,p==null?void 0:p.scrollIndicator),ae.style.display="none";let U=fe("arrow-down","12px","currentColor",2);U&&ae.appendChild(U);let ne=f("span","");ae.appendChild(ne);let ie=f("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ie.style.display="none",It.appendChild(de),It.appendChild(ie),It.appendChild(ae),y.setAttribute("tabindex","0"),y.appendChild(gt),y.appendChild(mt),y.appendChild(It);function Te(){let G=n.getAll(),z={};for(let ve of G)z[ve.type]=(z[ve.type]||0)+1;let j=Object.keys(z).sort(),xe=j.length!==x.length||!j.every((ve,Ce)=>ve===x[Ce]),Pe=!xe&&j.some(ve=>z[ve]!==k[ve]),Be=G.length!==Object.values(k).reduce((ve,Ce)=>ve+Ce,0);if(!xe&&!Pe&&!Be||(x=j,k=z,!Y))return;let pt=Y.value;if(Y.options[0].textContent="All events",xe){for(;Y.options.length>1;)Y.remove(1);for(let ve of j){let Ce=f("option","");Ce.value=ve,Ce.textContent=`${ve} (${z[ve]||0})`,Y.appendChild(Ce)}pt&&j.includes(pt)?Y.value=pt:pt&&(Y.value="",C="")}else for(let ve=1;ve<Y.options.length;ve++){let Ce=Y.options[ve];Ce.textContent=`${Ce.value} (${z[Ce.value]||0})`}}function Xe(){let G=n.getAll();if(C&&(G=G.filter(z=>z.type===C)),v){let z=v.toLowerCase();G=G.filter(j=>j.type.toLowerCase().includes(z)||j.payload.toLowerCase().includes(z))}return G}function te(){return C!==""||v!==""}function X(){q=0,N=0,M=!1,ae.style.display="none"}function He(G){J.has(G)?J.delete(G):J.add(G),ye=G;let z=de.scrollTop,j=M;K=!0,M=!0,tt(),de.scrollTop=z,M=j,K=!1}function Ue(){return de.scrollHeight-de.scrollTop-de.clientHeight<=50}function tt(){w=Date.now(),F=!1,Te();let G=n.getEvictedCount();G>0?(mt.textContent=`${G.toLocaleString()} older events truncated`,mt.style.display=""):mt.style.display="none",m=Xe();let z=m.length,j=n.getSize()>0;ee&&(ee.textContent=String(n.getSize())),z===0&&j&&te()?(ie.textContent=v?`No events matching '${v}'`:"No events matching filter",ie.style.display="",de.style.display="none"):(ie.style.display="none",de.style.display=""),_&&(_.title=te()?`Copy Filtered (${z})`:"Copy All"),M&&z>q&&(N+=z-q,ne.textContent=`${N} new event${N===1?"":"s"}`,ae.style.display=""),q=z;let xe=n.getAll(),Pe=xe.length>0?xe[0].timestamp:0,Be=new Set(m.map(Ce=>Ce.id));for(let Ce of J)Be.has(Ce)||J.delete(Ce);let pt=C!==We||v!==Ge,ve=me.size===0&&m.length>0;if(pt||ve||m.length===0){de.innerHTML="",me.clear();let Ce=document.createDocumentFragment();for(let Fe=0;Fe<m.length;Fe++){let ge=Ns(m[Fe],Fe,Pe,a,J,He,o,s);me.set(m[Fe].id,ge),Ce.appendChild(ge)}de.appendChild(Ce),We=C,Ge=v,ye=null}else{if(ye!==null){let Fe=me.get(ye);if(Fe&&Fe.parentNode===de){let ge=m.findIndex(bt=>bt.id===ye);if(ge>=0){let bt=Ns(m[ge],ge,Pe,a,J,He,o,s);de.insertBefore(bt,Fe),Fe.remove(),me.set(ye,bt)}}ye=null}let Ce=new Set(m.map(Fe=>Fe.id));for(let[Fe,ge]of me)Ce.has(Fe)||(ge.remove(),me.delete(Fe));for(let Fe=0;Fe<m.length;Fe++){let ge=m[Fe];if(!me.has(ge.id)){let bt=Ns(ge,Fe,Pe,a,J,He,o,s);me.set(ge.id,bt),de.appendChild(bt)}}}M||(de.scrollTop=de.scrollHeight)}function Ut(){if(Date.now()-w>=Nd){Q!==null&&(cancelAnimationFrame(Q),Q=null),tt();return}F||(F=!0,Q=requestAnimationFrame(()=>{Q=null,tt()}))}let Dt=(G,z)=>{if(!_)return;_.innerHTML="";let j=fe(G,"12px","currentColor",1.5);j&&_.appendChild(j);let xe=f("span","persona-text-xs");xe.textContent="Copy All",_.appendChild(xe),setTimeout(()=>{_.innerHTML="";let Pe=fe("clipboard-copy","12px","currentColor",1.5);Pe&&_.appendChild(Pe);let Be=f("span","persona-text-xs");Be.textContent="Copy All",_.appendChild(Be),_.disabled=!1},z)},ce=async()=>{if(_){_.disabled=!0;try{let G;te()?G=m:t?(G=await t(),G.length===0&&(G=n.getAll())):G=n.getAll();let z=G.map(j=>{try{return JSON.parse(j.payload)}catch{return j.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),Dt("check",1500)}catch{Dt("x",1500)}}},ze=()=>{Y&&(C=Y.value,X(),tt())},ke=()=>{!D||!ue||(ue.style.display=D.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{v=D.value,X(),tt()},150))},nt=()=>{!D||!ue||(D.value="",v="",ue.style.display="none",E&&clearTimeout(E),X(),tt())},Ve=()=>{if(K)return;let G=de.scrollTop,z=G>oe;oe=G,Ue()&&z?(M=!1,N=0,ae.style.display="none"):Ue()||(M=!0)},Ze=G=>{G.deltaY<0&&(M=!0)},Wt=()=>{de.scrollTop=de.scrollHeight,M=!1,N=0,ae.style.display="none"},Rt=G=>{let z=G.target;if(!z||z.closest("button"))return;let j=z.closest("[data-event-id]");if(!j)return;let xe=j.getAttribute("data-event-id");xe&&He(xe)},Tt=G=>{if((G.metaKey||G.ctrlKey)&&G.key==="f"){G.preventDefault(),D==null||D.focus(),D==null||D.select();return}G.key==="Escape"&&(D&&document.activeElement===D?(nt(),D.blur(),y.focus()):r&&r())};_&&_.addEventListener("click",ce),Y&&Y.addEventListener("change",ze),D&&D.addEventListener("input",ke),ue&&ue.addEventListener("click",nt),de.addEventListener("scroll",Ve),de.addEventListener("wheel",Ze,{passive:!0}),de.addEventListener("click",Rt),ae.addEventListener("click",Wt),y.addEventListener("keydown",Tt);function B(){E&&clearTimeout(E),Q!==null&&(cancelAnimationFrame(Q),Q=null),F=!1,me.clear(),_&&_.removeEventListener("click",ce),Y&&Y.removeEventListener("change",ze),D&&D.removeEventListener("input",ke),ue&&ue.removeEventListener("click",nt),de.removeEventListener("scroll",Ve),de.removeEventListener("wheel",Ze),de.removeEventListener("click",Rt),ae.removeEventListener("click",Wt),y.removeEventListener("keydown",Tt)}return{element:y,update:Ut,destroy:B}}}var sc=e=>{let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",t=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",o=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",a=document.createElement("div");a.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.backgroundColor="var(--persona-bg, #ffffff)",a.style.cursor="pointer",a.tabIndex=0,a.setAttribute("role","button"),a.setAttribute("aria-label",`Open ${n} in artifact panel`),t&&a.setAttribute("data-open-artifact",t);let i=document.createElement("div");i.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.color="var(--persona-muted, #9ca3af)",i.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let c=document.createElement("div");c.className="persona-truncate persona-text-sm persona-font-medium",c.style.color="var(--persona-text, #1f2937)",c.textContent=n;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #3b82f6)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let y=document.createElement("span");y.textContent=`Generating ${o.toLowerCase()}...`,g.appendChild(y)}else g.textContent=o;if(d.append(c,g),a.append(i,d),r==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${n}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",t),a.append(p)}return a};var Os=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},In=new Os;In.register("PersonaArtifactCard",sc);function zd(e){var s;let n=f("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=f("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=f("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function so(e,n,t=""){let r=f("button",`persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-p-1 persona-text-persona-primary hover:persona-bg-persona-container ${t}`);r.type="button",r.setAttribute("aria-label",n),r.title=n;let s=fe(e,16,"currentColor",2);return s&&r.appendChild(s),r}function ao(e,n,t){let r=f("button",`persona-artifact-doc-icon-btn ${t}`.trim());r.type="button",r.setAttribute("aria-label",n),r.title=n;let s=fe(e,16,"currentColor",2);return s&&r.appendChild(s),r}function ac(e){let n=f("button","persona-artifact-doc-copy-btn");n.type="button",n.setAttribute("aria-label","Copy"),n.title="Copy";let t=fe("copy",e?14:16,"currentColor",2);if(t&&n.appendChild(t),e){let r=f("span","persona-artifact-doc-copy-label");r.textContent="Copy",n.appendChild(r)}return n}function Jd(){let e=f("button","persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn");e.type="button",e.setAttribute("aria-label","More copy options"),e.setAttribute("aria-haspopup","true"),e.setAttribute("aria-expanded","false");let n=fe("chevron-down",14,"currentColor",2);return n&&e.appendChild(n),e}function ic(e,n){var mt,It,de,ae;let t=(It=(mt=e.features)==null?void 0:mt.artifacts)==null?void 0:It.layout,s=((de=t==null?void 0:t.toolbarPreset)!=null?de:"default")==="document",o=(ae=t==null?void 0:t.panePadding)==null?void 0:ae.trim(),a=e.markdown?Zn(e.markdown):null,i=U=>a?a(U):br(U),d=typeof document!="undefined"?f("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,c=()=>{d==null||d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")};d&&d.addEventListener("click",()=>{var U;c(),(U=n.onDismiss)==null||U.call(n)});let g=f("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");g.setAttribute("data-persona-theme-zone","artifact-pane"),s&&g.classList.add("persona-artifact-pane-document");let p=f("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");p.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&p.classList.add("persona-artifact-toolbar-document");let y=f("span","persona-text-xs persona-font-medium persona-truncate");y.textContent="Artifacts";let m=f("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");m.type="button",m.textContent="Close",m.setAttribute("aria-label","Close artifacts panel"),m.addEventListener("click",()=>{var U;c(),(U=n.onDismiss)==null||U.call(n)});let C="rendered",v=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=s?ao("eye","Rendered view","persona-artifact-view-btn"):so("eye","Rendered view",""),x=s?ao("code-2","Source","persona-artifact-code-btn"):so("code-2","Source",""),k=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),q=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,M=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,N=t==null?void 0:t.documentToolbarCopyMenuItems,w=!!(M&&N&&N.length>0),F=null,Q,K=null,oe=null;if(s&&(q||M)&&!w){if(Q=ac(q),M){let U=fe("chevron-down",14,"currentColor",2);U&&Q.appendChild(U)}}else if(s&&w){F=f("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=ac(q),K=Jd(),F.append(Q,K),oe=f("div","persona-artifact-doc-copy-menu persona-absolute persona-right-0 persona-top-full persona-z-20 persona-mt-1 persona-min-w-[10rem] persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-py-1 persona-shadow-md persona-hidden"),F.appendChild(oe);for(let U of N){let ne=f("button","persona-block persona-w-full persona-text-left persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary hover:persona-bg-persona-container");ne.type="button",ne.textContent=U.label,ne.dataset.copyMenuId=U.id,oe.appendChild(ne)}}else s?Q=ao("copy","Copy",""):Q=so("copy","Copy","");let J=s?ao("refresh-cw","Refresh",""):so("refresh-cw","Refresh",""),me=s?ao("x","Close",""):so("x","Close",""),We=()=>{var Xe,te,X;let U=(Xe=D.find(He=>He.id===ue))!=null?Xe:D[D.length-1],ne=(te=U==null?void 0:U.id)!=null?te:null,ie=(U==null?void 0:U.artifactType)==="markdown"&&(X=U.markdown)!=null?X:"",Te=U?JSON.stringify({component:U.component,props:U.props},null,2):"";return{markdown:ie,jsonPayload:Te,id:ne}},Ge=async()=>{var Xe;let{markdown:U,jsonPayload:ne}=We(),ie=(Xe=D.find(te=>te.id===ue))!=null?Xe:D[D.length-1],Te=(ie==null?void 0:ie.artifactType)==="markdown"?U:ie?ne:"";try{await navigator.clipboard.writeText(Te)}catch{}};if(Q.addEventListener("click",async()=>{let U=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(U&&w){let{markdown:ne,jsonPayload:ie,id:Te}=We();try{await U({actionId:"primary",artifactId:Te,markdown:ne,jsonPayload:ie})}catch{}return}await Ge()}),K&&oe){let U=()=>{oe.classList.add("persona-hidden"),K.setAttribute("aria-expanded","false")};K.addEventListener("click",ne=>{ne.stopPropagation(),oe.classList.contains("persona-hidden")?(oe.classList.remove("persona-hidden"),K.setAttribute("aria-expanded","true")):U()}),typeof document!="undefined"&&document.addEventListener("click",U),oe.addEventListener("click",async ne=>{let ie=ne.target.closest("button[data-copy-menu-id]");if(!(ie!=null&&ie.dataset.copyMenuId))return;ne.stopPropagation();let Te=ie.dataset.copyMenuId,{markdown:Xe,jsonPayload:te,id:X}=We(),He=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{He?await He({actionId:Te,artifactId:X,markdown:Xe,jsonPayload:te}):Te==="markdown"||Te==="md"?await navigator.clipboard.writeText(Xe):Te==="json"||Te==="source"?await navigator.clipboard.writeText(te):await navigator.clipboard.writeText(Xe||te)}catch{}U()})}J.addEventListener("click",async()=>{var U;try{await((U=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:U.call(t))}catch{}gt()}),me.addEventListener("click",()=>{var U;c(),(U=n.onDismiss)==null||U.call(n)});let ye=()=>{s&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),x.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",ye(),gt()}),x.addEventListener("click",()=>{C="source",ye(),gt()});let ee=f("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(p.replaceChildren(),v.append(E,x),F?k.append(F,J,me):k.append(Q,J,me),p.append(v,ee,k),ye()):(p.appendChild(y),p.appendChild(m)),o&&(p.style.paddingLeft=o,p.style.paddingRight=o);let Y=f("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),_=f("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Y.style.paddingLeft=o,Y.style.paddingRight=o,_.style.padding=o),g.appendChild(p),g.appendChild(Y),g.appendChild(_);let D=[],ue=null,be=!1,gt=()=>{var Te,Xe,te,X;let U=s&&D.length<=1;Y.classList.toggle("persona-hidden",U),Y.replaceChildren();for(let He of D){let Ue=f("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary hover:persona-bg-persona-container");Ue.type="button",Ue.textContent=He.title||He.id.slice(0,8),He.id===ue&&Ue.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ue.addEventListener("click",()=>n.onSelect(He.id)),Y.appendChild(Ue)}_.replaceChildren();let ne=ue&&D.find(He=>He.id===ue)||D[D.length-1];if(!ne)return;if(s){let He=ne.artifactType==="markdown"?"MD":(Te=ne.component)!=null?Te:"Component",tt=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ee.textContent=`${tt} \xB7 ${He}`}else y.textContent="Artifacts";if(ne.artifactType==="markdown"){if(s&&C==="source"){let Ue=f("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ue.textContent=(Xe=ne.markdown)!=null?Xe:"",_.appendChild(Ue);return}let He=f("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");He.innerHTML=i((te=ne.markdown)!=null?te:""),_.appendChild(He);return}let ie=ne.component?In.get(ne.component):void 0;if(ie){let Ue={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let tt=ie((X=ne.props)!=null?X:{},Ue);if(tt){_.appendChild(tt);return}}catch{}}_.appendChild(zd(ne))},ct=()=>{var ne;let U=D.length>0;if(g.classList.toggle("persona-hidden",!U),d){let ie=typeof g.closest=="function"?g.closest("#persona-root"):null,Xe=((ne=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;U&&Xe&&be?(d.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:d,update(U){var ne,ie,Te;D=U.artifacts,ue=(Te=(ie=U.selectedId)!=null?ie:(ne=U.artifacts[U.artifacts.length-1])==null?void 0:ne.id)!=null?Te:null,D.length>0&&(be=!0),gt(),ct()},setMobileOpen(U){be=U,!U&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):ct()}}}function an(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function lc(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!an(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Kd(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Go(e,n){var d,c,g,p,y,m,C,v,E,x;if(!an(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Kd(e),lc(e,n);return}let t=(c=(d=n.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(g=t==null?void 0:t.splitGap)!=null?g:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(y=t==null?void 0:t.paneMaxWidth)!=null?y:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(x=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),lc(e,n)}var cc=["panel","seamless"];function Zo(e,n){var i,d,c,g,p,y;for(let m of cc)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!an(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=cc.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(g=t==null?void 0:t.paneBorderRadius)==null?void 0:g.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((y=t.unifiedSplitOuterRadius)==null?void 0:y.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function dc(e,n){var t,r,s;return!n||!an(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Yd(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function Xd(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function Gd(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Zd(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function pc(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function uc(e,n,t,r,s,o){let a=Yd(s,200),i=Zd(n,t,r,200);i=Math.max(a,i);let d=Xd(o);return d!==null&&(i=Math.min(i,d)),Gd(e,a,i)}var gc={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Ds=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var C,v,E;if(o.dataset.enhanced==="true")return;let a=(C=o.dataset.tvForm)!=null?C:"init";o.dataset.enhanced="true";let i=(v=gc[a])!=null?v:gc.init;o.classList.add("persona-form-card","persona-space-y-4");let d=f("div","persona-space-y-1"),c=f("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let x=f("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var w,F;let k=f("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${n.id}-${a}-${x.name}`;let q=f("span","persona-text-xs persona-font-medium persona-text-persona-muted");q.textContent=x.label,k.appendChild(q);let M=(w=x.type)!=null?w:"text",N;M==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=M),N.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",N.id=`${n.id}-${a}-${x.name}`,N.name=x.name,N.placeholder=(F=x.placeholder)!=null?F:"",x.required&&(N.required=!0),k.appendChild(N),g.appendChild(k)});let p=f("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=f("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=f("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(y),p.appendChild(m),g.appendChild(p),o.replaceChildren(d,g),g.addEventListener("submit",async x=>{var N,w;x.preventDefault();let k=(N=t.formEndpoint)!=null?N:"/form",q=new FormData(g),M={};q.forEach((F,Q)=>{M[Q]=F}),M.type=a,m.disabled=!0,y.textContent="Submitting\u2026";try{let F=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!F.ok)throw new Error(`Form submission failed (${F.status})`);let Q=await F.json();y.textContent=(w=Q.message)!=null?w:"Thanks! We'll be in touch soon.",Q.success&&Q.nextPrompt&&await r.sendMessage(String(Q.nextPrompt))}catch(F){y.textContent=F instanceof Error?F.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var _s=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},io=new _s;var js={primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},Vs={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},ut={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:js,darkTheme:Vs,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px",collapsedWidth:"72px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Qo(e){var n,t,r,s,o,a,i,d,c,g,p,y,m,C,v,E,x,k,q,M,N;return e?{...ut,...e,theme:{...ut.theme,...e.theme},darkTheme:{...ut.darkTheme,...e.darkTheme},launcher:{...ut.launcher,...e.launcher,dock:{...(n=ut.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=ut.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...ut.copy,...e.copy},sendButton:{...ut.sendButton,...e.sendButton},statusIndicator:{...ut.statusIndicator,...e.statusIndicator},voiceRecognition:{...ut.voiceRecognition,...e.voiceRecognition},features:(()=>{var K,oe;let w=(K=ut.features)==null?void 0:K.artifacts,F=(oe=e.features)==null?void 0:oe.artifacts,Q=w===void 0&&F===void 0?void 0:{...w,...F,layout:{...w==null?void 0:w.layout,...F==null?void 0:F.layout}};return{...ut.features,...e.features,...Q!==void 0?{artifacts:Q}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:ut.suggestionChips,suggestionChipsConfig:{...ut.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ut.layout,...e.layout,header:{...(a=ut.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=ut.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(g=ut.layout)==null?void 0:g.messages)==null?void 0:p.avatar,...(m=(y=e.layout)==null?void 0:y.messages)==null?void 0:m.avatar},timestamp:{...(v=(C=ut.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(x=(E=e.layout)==null?void 0:E.messages)==null?void 0:x.timestamp}},slots:{...(k=ut.layout)==null?void 0:k.slots,...(q=e.layout)==null?void 0:q.slots}},markdown:{...ut.markdown,...e.markdown,options:{...(M=ut.markdown)==null?void 0:M.options,...(N=e.markdown)==null?void 0:N.options}},messageActions:{...ut.messageActions,...e.messageActions}}:ut}var mc=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Qd=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},ep=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},lo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Qd(e),t=ep(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Us=e=>typeof e=="string"?e:e==null?"":String(e),ar={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Us(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=Us(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Us(t.text)}}},fc=e=>Array.isArray(e)?e.map(n=>String(n)):[],co=e=>{let n=new Set(fc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(fc(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,g)=>c||(g==null?void 0:g({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let g=()=>{e.emit("action:resubmit",d)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:g});if(!p)continue;if(p.handled){let y=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:y,resubmit:p.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:t}};var tp=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},np=e=>e.map(n=>({...n,streaming:!1})),es=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?tp(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?np(t.messages):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Lr=require("partial-json");function rp(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function op(e,n){if(!rp(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function ts(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=(0,Lr.parse)(t,Lr.STR|Lr.OBJ),o=op(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function hc(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ns(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=In.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function yc(){let e=ts();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rs(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function os(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var sp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ss(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=sp}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let p=null,y=document.createElement("div");y.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=r,m.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,m.appendChild(v),y.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let w=1;w<=5;w++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-star-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${c[w-1]}`),F.title=c[w-1],F.dataset.rating=String(w),F.innerHTML=`
|
|
15
|
+
`,t.addEventListener("click",n);let r=o=>{var q,M,N,w,F,re,Y,ae,z,ge,Ie,Xe;let a=(q=o.launcher)!=null?q:{},i=Ut(o),d=t.querySelector("[data-role='launcher-title']");d&&(d.textContent=(M=a.title)!=null?M:"Chat Assistant");let c=t.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(N=a.subtitle)!=null?N:"Get answers fast");let g=t.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ye=(w=a.agentIconSize)!=null?w:"40px";if(p.style.height=ye,p.style.width=ye,p.innerHTML="",a.agentIconName){let ee=parseFloat(ye)||24,te=me(a.agentIconName,ee*.6,"var(--persona-text-inverse, #ffffff)",2);te?(p.appendChild(te),p.style.display=""):(p.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(re=a.agentIconText)!=null?re:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ye=(Y=a.agentIconSize)!=null?Y:"40px";f.style.height=ye,f.style.width=ye,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(ae=a.callToActionIconSize)!=null?ae:"32px";m.style.height=ye,m.style.width=ye,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let ee=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ee=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let te=parseFloat(ye)||24,D=Math.max(te-ee,8),U=me(a.callToActionIconName,D,"currentColor",2);U?m.appendChild(U):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(ge=a.callToActionIconText)!=null?ge:"\u2197"}let C=a.position&&pn[a.position]?pn[a.position]:pn["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer persona-z-50",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?E:`${v} ${C}`;let x="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";if(t.style.border=(Ie=a.border)!=null?Ie:x,t.style.boxShadow=(Xe=a.shadow)!=null?Xe:k,i){let ye=Sr(o);t.style.width=`calc(${ye.collapsedWidth} - 16px)`,t.style.minWidth="40px",t.style.maxWidth=`calc(${ye.collapsedWidth} - 16px)`,t.style.justifyContent="center",t.style.padding="12px 0"}else t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.justifyContent="",t.style.padding=""},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Pn=e=>{var ae,z,ge,Ie,Xe,ye,ee,te,D,U,oe,he,ht,at,gt,Wt,de,ie,qe,j,G,be,ze,X,K,tt,We,Ve,Tt,_t,ce,Je;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomWidth="1px",r.style.borderBottomStyle="solid",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))";let s=(ae=n==null?void 0:n.launcher)!=null?ae:{},o=(z=s.headerIconSize)!=null?z:"48px",a=(ge=s.closeButtonSize)!=null?ge:"32px",i=(Ie=s.closeButtonPlacement)!=null?Ie:"inline",d=(Xe=s.headerIconHidden)!=null?Xe:!1,c=s.headerIconName,g=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-bg-persona-primary persona-text-white persona-text-xl");if(g.style.height=o,g.style.width=o,!d)if(c){let Me=parseFloat(o)||24,nt=me(c,Me*.6,"var(--persona-text-inverse, #ffffff)",1);nt?g.replaceChildren(nt):g.textContent=(ee=(ye=n==null?void 0:n.launcher)==null?void 0:ye.agentIconText)!=null?ee:"\u{1F4AC}"}else if((te=n==null?void 0:n.launcher)!=null&&te.iconUrl){let Me=h("img");Me.src=n.launcher.iconUrl,Me.alt="",Me.className="persona-rounded-xl persona-object-cover",Me.style.height=o,Me.style.width=o,g.replaceChildren(Me)}else g.textContent=(U=(D=n==null?void 0:n.launcher)==null?void 0:D.agentIconText)!=null?U:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col"),f=h("span","persona-text-base persona-font-semibold");f.textContent=(he=(oe=n==null?void 0:n.launcher)==null?void 0:oe.title)!=null?he:"Chat Assistant";let m=h("span","persona-text-xs persona-text-persona-muted");m.textContent=(at=(ht=n==null?void 0:n.launcher)==null?void 0:ht.subtitle)!=null?at:"Here to help you get answers fast",p.append(f,m),d?r.append(p):r.append(g,p);let C=(gt=s.clearChat)!=null?gt:{},v=(Wt=C.enabled)!=null?Wt:!0,E=(de=C.placement)!=null?de:"inline",x=null,k=null;if(v){let Me=(ie=C.size)!=null?ie:"32px",nt=(qe=C.iconName)!=null?qe:"refresh-cw",je=(j=C.iconColor)!=null?j:"",Ze=(G=C.backgroundColor)!=null?G:"",Rt=(be=C.borderWidth)!=null?be:"",Ht=(ze=C.borderColor)!=null?ze:"",Mt=(X=C.borderRadius)!=null?X:"",B=(K=C.paddingX)!=null?K:"",Z=(tt=C.paddingY)!=null?tt:"",J=(We=C.tooltipText)!=null?We:"Clear chat",_=(Ve=C.showTooltip)!=null?Ve:!0;k=h("div",E==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),x=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),x.style.height=Me,x.style.width=Me,x.type="button",x.setAttribute("aria-label",J);let xe=me(nt,"20px",je||"",1);if(xe&&x.appendChild(xe),je&&(x.style.color=je,x.classList.remove("persona-text-persona-muted")),Ze&&(x.style.backgroundColor=Ze,x.classList.remove("hover:persona-bg-gray-100")),Rt||Ht){let Le=Rt||"0px",He=Ht||"transparent";x.style.border=`${Le} solid ${He}`,x.classList.remove("persona-border-none")}if(Mt&&(x.style.borderRadius=Mt,x.classList.remove("persona-rounded-full")),B?(x.style.paddingLeft=B,x.style.paddingRight=B):(x.style.paddingLeft="",x.style.paddingRight=""),Z?(x.style.paddingTop=Z,x.style.paddingBottom=Z):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),_&&J&&x&&k){let Le=null,He=()=>{if(Le||!x)return;let ve=x.ownerDocument,Ce=ve.body;if(!Ce)return;Le=vn(ve,"div","persona-clear-chat-tooltip"),Le.textContent=J;let Be=vn(ve,"div");Be.className="persona-clear-chat-tooltip-arrow",Le.appendChild(Be);let ue=x.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${ue.left+ue.width/2}px`,Le.style.top=`${ue.top-8}px`,Le.style.transform="translate(-50%, -100%)",Ce.appendChild(Le)},pt=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};k.addEventListener("mouseenter",He),k.addEventListener("mouseleave",pt),x.addEventListener("focus",He),x.addEventListener("blur",pt),k._cleanupTooltip=()=>{pt(),k&&(k.removeEventListener("mouseenter",He),k.removeEventListener("mouseleave",pt)),x&&(x.removeEventListener("focus",He),x.removeEventListener("blur",pt))}}E==="inline"&&r.appendChild(k)}let q=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&E==="inline"?"":"persona-ml-auto"),M=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=a,M.style.width=a,M.type="button";let N=(Tt=s.closeButtonTooltipText)!=null?Tt:"Close chat",w=(_t=s.closeButtonShowTooltip)!=null?_t:!0;M.setAttribute("aria-label",N),M.style.display=t?"":"none";let F=(ce=s.closeButtonIconName)!=null?ce:"x",re=(Je=s.closeButtonIconText)!=null?Je:"\xD7",Y=me(F,"20px",s.closeButtonColor||"",1);if(Y?M.appendChild(Y):M.textContent=re,s.closeButtonColor?(M.style.color=s.closeButtonColor,M.classList.remove("persona-text-persona-muted")):(M.style.color="",M.classList.add("persona-text-persona-muted")),s.closeButtonBackgroundColor?(M.style.backgroundColor=s.closeButtonBackgroundColor,M.classList.remove("hover:persona-bg-gray-100")):(M.style.backgroundColor="",M.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Me=s.closeButtonBorderWidth||"0px",nt=s.closeButtonBorderColor||"transparent";M.style.border=`${Me} solid ${nt}`,M.classList.remove("persona-border-none")}else M.style.border="",M.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(M.style.borderRadius=s.closeButtonBorderRadius,M.classList.remove("persona-rounded-full")):(M.style.borderRadius="",M.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(M.style.paddingLeft=s.closeButtonPaddingX,M.style.paddingRight=s.closeButtonPaddingX):(M.style.paddingLeft="",M.style.paddingRight=""),s.closeButtonPaddingY?(M.style.paddingTop=s.closeButtonPaddingY,M.style.paddingBottom=s.closeButtonPaddingY):(M.style.paddingTop="",M.style.paddingBottom=""),q.appendChild(M),w&&N){let Me=null,nt=()=>{if(Me)return;let Ze=M.ownerDocument,Rt=Ze.body;if(!Rt)return;Me=vn(Ze,"div","persona-clear-chat-tooltip"),Me.textContent=N;let Ht=vn(Ze,"div");Ht.className="persona-clear-chat-tooltip-arrow",Me.appendChild(Ht);let Mt=M.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${Mt.left+Mt.width/2}px`,Me.style.top=`${Mt.top-8}px`,Me.style.transform="translate(-50%, -100%)",Rt.appendChild(Me)},je=()=>{Me&&Me.parentNode&&(Me.parentNode.removeChild(Me),Me=null)};q.addEventListener("mouseenter",nt),q.addEventListener("mouseleave",je),M.addEventListener("focus",nt),M.addEventListener("blur",je),q._cleanupTooltip=()=>{je(),q.removeEventListener("mouseenter",nt),q.removeEventListener("mouseleave",je),M.removeEventListener("focus",nt),M.removeEventListener("blur",je)}}return i!=="top-right"&&r.appendChild(q),{header:r,iconHolder:g,headerTitle:f,headerSubtitle:m,closeButton:M,closeButtonWrapper:q,clearChatButton:x,clearChatButtonWrapper:k}},or=(e,n,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var Ws=e=>{var r;let n=Pn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function Wd(e,n,t){var r,s;if(n!=null&&n.length)for(let o of n){let a=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(a.type="button",a.setAttribute("aria-label",(s=(r=o.ariaLabel)!=null?r:o.label)!=null?s:o.id),o.icon){let i=me(o.icon,14,"currentColor",2);i&&a.appendChild(i)}else o.label&&(a.textContent=o.label);a.addEventListener("click",()=>t==null?void 0:t(o.id)),e.appendChild(a)}}var Rs=e=>{var x,k,q,M,N;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(x=n==null?void 0:n.launcher)!=null?x:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-bg-persona-surface persona-px-6 persona-py-4 persona-border-b-persona-divider");i.setAttribute("data-persona-theme-zone","header");let d=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=h("span","persona-text-base persona-font-semibold persona-truncate");if(c.textContent=(k=a.title)!=null?k:"Chat Assistant",d.appendChild(c),Wd(d,s==null?void 0:s.trailingActions,(q=s==null?void 0:s.onAction)!=null?q:o),s!=null&&s.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let w=s.onTitleClick;d.addEventListener("click",F=>{F.target.closest("button")||w()}),d.addEventListener("keydown",F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),w())})}i.appendChild(d);let g=(M=a.closeButtonSize)!=null?M:"32px",p=h("div",""),f=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=g,f.style.width=g,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=t?"":"none";let m=(N=a.closeButtonIconName)!=null?N:"x",C=me(m,"20px",a.closeButtonColor||"",2);C?f.appendChild(C):f.textContent="\xD7",r&&f.addEventListener("click",r),p.appendChild(f),i.appendChild(p);let v=h("div");v.style.display="none";let E=h("span");return E.style.display="none",{header:i,iconHolder:v,headerTitle:c,headerSubtitle:E,closeButton:f,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},Xo={default:Ws,minimal:Rs},Hs=e=>{var n;return(n=Xo[e])!=null?n:Xo.default},Ar=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let c=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),g=h("div");g.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let C=h("div");return C.style.display="none",{header:c,iconHolder:g,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=Hs(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Rd=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Er=e=>{var de,ie,qe,j,G,be,ze,X,K,tt,We,Ve,Tt,_t,ce,Je,Me,nt,je,Ze,Rt,Ht,Mt,B,Z,J,_,xe,Le,He,pt;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(ie=(de=n==null?void 0:n.copy)==null?void 0:de.inputPlaceholder)!=null?ie:"Type your message\u2026",o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1;let a=(j=(qe=n==null?void 0:n.theme)==null?void 0:qe.inputFontFamily)!=null?j:"sans-serif",i=(be=(G=n==null?void 0:n.theme)==null?void 0:G.inputFontWeight)!=null?be:"400";o.style.fontFamily=Rd(a),o.style.fontWeight=i;let g=3*20;o.style.maxHeight=`${g}px`,o.style.overflowY="auto";let p=()=>{o.style.height="auto";let ve=Math.min(o.scrollHeight,g);o.style.height=`${ve}px`};o.addEventListener("input",p),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let f=(ze=n==null?void 0:n.sendButton)!=null?ze:{},m=(X=f.useIcon)!=null?X:!1,C=(K=f.iconText)!=null?K:"\u2191",v=f.iconName,E=(tt=f.tooltipText)!=null?tt:"Send message",x=(We=f.showTooltip)!=null?We:!1,k=(Ve=f.size)!=null?Ve:"40px",q=f.backgroundColor,M=f.textColor,N=h("div","persona-send-button-wrapper"),w=h("button",m?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),m){if(w.style.width=k,w.style.height=k,w.style.minWidth=k,w.style.minHeight=k,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",v){let ve=parseFloat(k)||24,Ce=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",Be=me(v,ve,Ce,2);Be?(w.appendChild(Be),w.style.color=Ce):(w.textContent=C,M?w.style.color=M:w.classList.add("persona-text-white"))}else w.textContent=C,M?w.style.color=M:w.classList.add("persona-text-white");q?w.style.backgroundColor=q:w.classList.add("persona-bg-persona-primary")}else w.textContent=(_t=(Tt=n==null?void 0:n.copy)==null?void 0:Tt.sendButtonLabel)!=null?_t:"Send",M?w.style.color=M:w.classList.add("persona-text-white");if(f.borderWidth&&(w.style.borderWidth=f.borderWidth,w.style.borderStyle="solid"),f.borderColor&&(w.style.borderColor=f.borderColor),f.paddingX?(w.style.paddingLeft=f.paddingX,w.style.paddingRight=f.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),f.paddingY?(w.style.paddingTop=f.paddingY,w.style.paddingBottom=f.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),x&&E){let ve=h("div","persona-send-button-tooltip");ve.textContent=E,N.appendChild(ve)}N.appendChild(w);let F=(ce=n==null?void 0:n.voiceRecognition)!=null?ce:{},re=F.enabled===!0,Y=null,ae=null,z=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ge=((Je=F.provider)==null?void 0:Je.type)==="runtype";if(re&&(z||ge)){ae=h("div","persona-send-button-wrapper"),Y=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),Y.type="button",Y.setAttribute("data-persona-composer-mic",""),Y.setAttribute("aria-label","Start voice recognition");let ve=(Me=F.iconName)!=null?Me:"mic",Ce=(nt=F.iconSize)!=null?nt:k,Be=parseFloat(Ce)||24,ue=(je=F.backgroundColor)!=null?je:q,bt=(Ze=F.iconColor)!=null?Ze:M;Y.style.width=Ce,Y.style.height=Ce,Y.style.minWidth=Ce,Y.style.minHeight=Ce,Y.style.fontSize="18px",Y.style.lineHeight="1";let Zt=bt||"currentColor",un=me(ve,Be,Zt,1.5);un?(Y.appendChild(un),Y.style.color=Zt):(Y.textContent="\u{1F3A4}",Y.style.color=Zt),ue?Y.style.backgroundColor=ue:Y.classList.add("persona-bg-persona-primary"),bt?Y.style.color=bt:!bt&&!M&&Y.classList.add("persona-text-white"),F.borderWidth&&(Y.style.borderWidth=F.borderWidth,Y.style.borderStyle="solid"),F.borderColor&&(Y.style.borderColor=F.borderColor),F.paddingX&&(Y.style.paddingLeft=F.paddingX,Y.style.paddingRight=F.paddingX),F.paddingY&&(Y.style.paddingTop=F.paddingY,Y.style.paddingBottom=F.paddingY),ae.appendChild(Y);let gn=(Rt=F.tooltipText)!=null?Rt:"Start voice recognition";if(((Ht=F.showTooltip)!=null?Ht:!1)&&gn){let Rn=h("div","persona-send-button-tooltip");Rn.textContent=gn,ae.appendChild(Rn)}}let Xe=(Mt=n==null?void 0:n.attachments)!=null?Mt:{},ye=Xe.enabled===!0,ee=null,te=null,D=null,U=null;if(ye){U=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),U.style.display="none",D=h("input"),D.type="file",D.accept=((B=Xe.allowedTypes)!=null?B:Ln).join(","),D.multiple=((Z=Xe.maxFiles)!=null?Z:4)>1,D.style.display="none",D.setAttribute("aria-label","Attach files"),te=h("div","persona-send-button-wrapper"),ee=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ee.type="button",ee.setAttribute("aria-label",(J=Xe.buttonTooltipText)!=null?J:"Attach file");let ve=(_=Xe.buttonIconName)!=null?_:"paperclip",Ce=k,Be=parseFloat(Ce)||40,ue=Math.round(Be*.6);ee.style.width=Ce,ee.style.height=Ce,ee.style.minWidth=Ce,ee.style.minHeight=Ce,ee.style.fontSize="18px",ee.style.lineHeight="1",ee.style.backgroundColor="transparent",ee.style.color="var(--persona-primary, #111827)",ee.style.border="none",ee.style.borderRadius="6px",ee.style.transition="background-color 0.15s ease",ee.addEventListener("mouseenter",()=>{ee.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ee.addEventListener("mouseleave",()=>{ee.style.backgroundColor="transparent"});let bt=me(ve,ue,"currentColor",1.5);bt?ee.appendChild(bt):ee.textContent="\u{1F4CE}",ee.addEventListener("click",gn=>{gn.preventDefault(),D==null||D.click()}),te.appendChild(ee);let Zt=(xe=Xe.buttonTooltipText)!=null?xe:"Attach file",un=h("div","persona-send-button-tooltip");un.textContent=Zt,te.appendChild(un)}s.addEventListener("click",ve=>{ve.target!==w&&ve.target!==N&&ve.target!==Y&&ve.target!==ae&&ve.target!==ee&&ve.target!==te&&o.focus()}),U&&(U.style.gap="8px",s.append(U)),D&&s.append(D),s.append(o);let oe=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),he=h("div","persona-flex persona-items-center persona-gap-2");te&&he.append(te);let ht=h("div","persona-flex persona-items-center persona-gap-1");ae&&ht.append(ae),ht.append(N),oe.append(he,ht),s.append(oe);let at=h("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");at.setAttribute("data-persona-composer-status","");let gt=(Le=n==null?void 0:n.statusIndicator)!=null?Le:{},Wt=(He=gt.visible)!=null?He:!0;return at.style.display=Wt?"":"none",at.textContent=(pt=gt.idleText)!=null?pt:"Online",t.append(r,s,at),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:N,micButton:Y,micButtonWrapper:ae,statusText:at,attachmentButton:ee,attachmentButtonWrapper:te,attachmentInput:D,attachmentPreviewsContainer:U,actionsRow:oe,leftActions:he,rightActions:ht}};var tc=e=>{var c,g,p,f,m,C,v;let n=(g=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?g:!0;if(Ut(e)){let E=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return E.appendChild(x),{wrapper:E,panel:x}}if(!n){let E=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),k=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?f:"100%";return E.style.width=k,x.style.width="100%",E.appendChild(x),{wrapper:E,panel:x}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},s=r.position&&pn[r.position]?pn[r.position]:pn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-z-50 persona-transition`),a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(v=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?v:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},nc=(e,n=!0)=>{var v,E,x,k,q,M,N,w,F;let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let r=(v=e==null?void 0:e.layout)==null?void 0:v.header,s=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,o=r?Ar(e,r,{showClose:n}):Pn({config:e,showClose:n}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm"),d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let c=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");c.textContent=(M=(q=e==null?void 0:e.copy)==null?void 0:q.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",i.append(d,c);let g=h("div","persona-flex persona-flex-col persona-gap-3"),p=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;p&&(g.style.maxWidth=p,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((w=e==null?void 0:e.copy)==null?void 0:w.showWelcomeCard)!==!1?a.append(i,g):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(g));let m=Er({config:e}),C=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;return s?or(t,o,e):(o.header.style.display="none",or(t,o,e)),t.append(a),C||(m.footer.style.display="none"),t.append(m.footer),{container:t,body:a,messagesWrapper:g,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:c,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions}};var Hd=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Bd=320,Fd=320,$d=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Nd=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Bd}px`,c.style.maxHeight=`${Fd}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;s+=1,c.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{g=!0}),Hd(i.image)?(c.src=i.image,r.appendChild(c)):(g=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},sr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},Bs=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:sr};if(n){let s=n(r);if(s!==null)return s}return sr()},Od=(e,n)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},rc=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Dd=(e,n="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Fs=(e,n,t)=>{var m,C,v,E,x,k;let r=(m=n.showCopy)!=null?m:!0,s=(C=n.showUpvote)!=null?C:!0,o=(v=n.showDownvote)!=null?v:!0;if(!r&&!s&&!o){let q=h("div");return q.style.display="none",q.id=`actions-${e.id}`,q.setAttribute("data-actions-for",e.id),q}let a=(E=n.visibility)!=null?E:"hover",i=(x=n.align)!=null?x:"right",d=(k=n.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${g} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(q,M,N)=>{let w=document.createElement("button");w.className="persona-message-action-btn",w.setAttribute("aria-label",M),w.setAttribute("title",M),w.setAttribute("data-action",N);let F=me(q,14,"currentColor",2);return F&&w.appendChild(F),w};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Tr=(e,n,t,r,s,o)=>{var ae,z,ge,Ie,Xe,ye,ee;let a=t!=null?t:{},i=(ae=a.layout)!=null?ae:"bubble",d=a.avatar,c=a.timestamp,g=(z=d==null?void 0:d.show)!=null?z:!1,p=(ge=c==null?void 0:c.show)!=null?ge:!1,f=(Ie=d==null?void 0:d.position)!=null?Ie:"left",m=(Xe=c==null?void 0:c.position)!=null?Xe:"below",C=Dd(e.role,i),v=h("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=$d(e),x=(ee=(ye=e.content)==null?void 0:ye.trim())!=null?ee:"",q=E.length>0&&x===Do,M=document.createElement("div");M.classList.add("persona-message-content");let N=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),w=null;if(q?(w=document.createElement("div"),w.innerHTML=N,w.style.display="none",M.appendChild(w)):M.innerHTML=N,p&&m==="inline"&&e.createdAt){let te=rc(e,c);te.classList.add("persona-ml-2","persona-inline"),M.appendChild(te)}if(E.length>0){let te=Nd(E,!q&&!!x,()=>{q&&w&&(w.style.display="")});te?v.appendChild(te):q&&w&&(w.style.display="")}if(v.appendChild(M),p&&m==="below"&&e.createdAt){let te=rc(e,c);te.classList.add("persona-mt-1"),v.appendChild(te)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let te=Bs("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);te&&v.appendChild(te)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let te=Fs(e,r,s);v.appendChild(te)}if(!g||e.role==="system")return v;let re=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Y=Od(d,e.role);return f==="right"||f==="left"&&e.role==="user"?re.append(v,Y):re.append(Y,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),re},oc=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Tr(e,n,t,r,s,o)};var Mr=new Set,sc=(e,n)=>{let t=Mr.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t");if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let o=r.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=me(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},$s=e=>{let n=e.reasoning,t=h("div",["vanilla-message-bubble","vanilla-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!n)return t;let r=Mr.has(e.id),s=h("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");s.type="button",s.setAttribute("aria-expanded",r?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=h("div","persona-flex persona-flex-col persona-text-left"),a=h("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=h("span","persona-text-xs persona-text-persona-primary");i.textContent=Ml(n),o.appendChild(i),n.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),g=me(r?"chevron-up":"chevron-down",16,"currentColor",2);g?d.appendChild(g):d.textContent=r?"Hide":"Show";let p=h("div","persona-flex persona-items-center persona-ml-auto");p.append(d),s.append(o,p);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=r?"":"none";let m=n.chunks.join(""),C=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return C.textContent=m||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(C),(()=>{s.setAttribute("aria-expanded",r?"true":"false"),d.innerHTML="";let x=me(r?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=r?"Hide":"Show",f.style.display=r?"":"none"})(),t.append(s,f),t};var kr=new Set,ac=(e,n,t)=>{var c;let r=kr.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=s.toggleTextColor||s.headerTextColor||"currentColor",p=me(r?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=r?"Hide":"Show"}a.style.display=r?"":"none"},Ns=(e,n)=>{var v;let t=e.toolCall,r=(v=n==null?void 0:n.toolCall)!=null?v:{},s=h("div",["vanilla-message-bubble","vanilla-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=kr.has(e.id),a=h("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(a.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(a.style.paddingLeft=r.headerPaddingX,a.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(a.style.paddingTop=r.headerPaddingY,a.style.paddingBottom=r.headerPaddingY);let i=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(d.style.color=r.headerTextColor),d.textContent=kl(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),g=r.toggleTextColor||r.headerTextColor||"currentColor",p=me(o?"chevron-up":"chevron-down",16,g,2);p?c.appendChild(p):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",r.contentBackgroundColor&&(m.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(m.style.color=r.contentTextColor),r.contentPaddingX&&(m.style.paddingLeft=r.contentPaddingX,m.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(m.style.paddingTop=r.contentPaddingY,m.style.paddingBottom=r.contentPaddingY),t.name){let E=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?E.style.color=r.contentTextColor:r.headerTextColor&&(E.style.color=r.headerTextColor),E.textContent=t.name,m.appendChild(E)}if(t.args!==void 0){let E=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Arguments";let k=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=Qr(t.args),E.append(x,k),m.appendChild(E)}if(t.chunks&&t.chunks.length){let E=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Activity";let k=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=t.chunks.join(`
|
|
16
|
+
`),E.append(x,k),m.appendChild(E)}if(t.status==="complete"&&t.result!==void 0){let E=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Result";let k=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=Qr(t.result),E.append(x,k),m.appendChild(E)}if(t.status==="complete"&&typeof t.duration=="number"){let E=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(E.style.color=r.contentTextColor),E.textContent=`Duration: ${t.duration}ms`,m.appendChild(E)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let E=r.toggleTextColor||r.headerTextColor||"currentColor",x=me(o?"chevron-up":"chevron-down",16,E,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var Os=(e,n)=>{var v,E,x,k,q,M,N,w,F,re,Y,ae;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(v=r==null?void 0:r.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(E=r==null?void 0:r.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(x=r==null?void 0:r.titleColor)!=null?x:"currentColor",g=me(d,20,c,2);g&&i.appendChild(g);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",f.appendChild(m),!s){let z=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");z.setAttribute("data-approval-status",t.status),t.status==="approved"?(z.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",z.style.color="var(--persona-palette-colors-success-700, #15803d)",z.textContent="Approved"):t.status==="denied"?(z.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",z.style.color="var(--persona-palette-colors-error-700, #b91c1c)",z.textContent="Denied"):t.status==="timeout"&&(z.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",z.style.color="var(--persona-palette-colors-warning-700, #b45309)",z.textContent="Timeout"),f.appendChild(z)}p.appendChild(f);let C=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(C.style.color=r.descriptionColor),C.textContent=t.description,p.appendChild(C),t.parameters){let z=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(z.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(z.style.color=r.parameterTextColor),z.style.fontSize="0.75rem",z.style.lineHeight="1rem",z.textContent=Qr(t.parameters),p.appendChild(z)}if(s){let z=h("div","persona-flex persona-gap-2 persona-mt-2");z.setAttribute("data-approval-buttons","true");let ge=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ge.type="button",ge.style.backgroundColor=(q=r==null?void 0:r.approveButtonColor)!=null?q:"var(--persona-approval-approve-bg, #22c55e)",ge.style.color=(M=r==null?void 0:r.approveButtonTextColor)!=null?M:"#ffffff",ge.setAttribute("data-approval-action","approve");let Ie=me("shield-check",14,(N=r==null?void 0:r.approveButtonTextColor)!=null?N:"#ffffff",2);Ie&&(Ie.style.marginRight="4px",ge.appendChild(Ie));let Xe=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");ge.appendChild(Xe);let ye=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");ye.type="button",ye.style.backgroundColor=(F=r==null?void 0:r.denyButtonColor)!=null?F:"transparent",ye.style.color=(re=r==null?void 0:r.denyButtonTextColor)!=null?re:"var(--persona-feedback-error, #dc2626)",ye.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ye.setAttribute("data-approval-action","deny");let ee=me("shield-x",14,(Y=r==null?void 0:r.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",ye.appendChild(ee));let te=document.createTextNode((ae=r==null?void 0:r.denyLabel)!=null?ae:"Deny");ye.appendChild(te),z.append(ge,ye),p.appendChild(z)}return a.append(i,p),o.appendChild(a),o};var ic=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let g=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let C=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");C.type="button",C.textContent=m,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),g.appendChild(C),n.push(C)}),e.appendChild(g)}}};var oo=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var so=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function Lr(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var _d={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},jd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Vd=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ud=100;function qd(e,n){let t={..._d,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return jd}function zd(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Jd(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function Kd(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Yd(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Gd(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Xd(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Ds(e,n,t,r,s,o,a,i){var f;let d=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Lr(c,(f=r.classNames)==null?void 0:f.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var ge,Ie;let m=h("div",""),C=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let v=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=me(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let x=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(ge=r.timestampFormat)!=null?ge:"relative";x.textContent=k==="relative"?zd(e.timestamp,t):Jd(e.timestamp);let q=null;r.showSequenceNumbers!==!1&&(q=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),q.textContent=String(n+1));let M=qd(e.type,r.badgeColors),N=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");N.style.backgroundColor=M.bg,N.style.color=M.text,N.style.borderColor=M.text+"50",N.textContent=e.type;let w=(Ie=r.descriptionFields)!=null?Ie:Vd,F=Kd(e.payload,w),re=null;F&&(re=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),re.textContent=F);let Y=h("div","persona-flex-1 persona-min-w-0"),ae=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),z=me("clipboard","12px","currentColor",1.5);return z&&ae.appendChild(z),ae.addEventListener("click",async Xe=>{Xe.stopPropagation(),await Yd(Gd(e)),ae.innerHTML="";let ye=me("check","12px","currentColor",1.5);ye&&ae.appendChild(ye),setTimeout(()=>{ae.innerHTML="";let ee=me("clipboard","12px","currentColor",1.5);ee&&ae.appendChild(ee)},1500)}),C.appendChild(v),C.appendChild(x),q&&C.appendChild(q),C.appendChild(N),re&&C.appendChild(re),C.appendChild(Y),C.appendChild(ae),m.appendChild(C),d&&m.appendChild(Xd(e,a,i)),m}}function lc(e){var c,g;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[]}=e,a=(g=(c=s==null?void 0:s.features)==null?void 0:c.eventStream)!=null?g:{},i=o.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let p=i.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>d().element,onClose:r});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Lr(f,p==null?void 0:p.panel);let m=[],C="",v="",E=null,x=[],k={},q=0,M=!1,N=0,w=0,F=!1,re=null,Y=!1,ae=0,z=new Set,ge=new Map,Ie="",Xe="",ye=null,ee,te,D,U,oe;function he(){let Z=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),J=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Lr(J,p==null?void 0:p.headerBar);let _=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");_.textContent="Events",ee=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ee.textContent="0";let xe=h("div","persona-flex-1");te=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Le=h("option","");Le.value="",Le.textContent="All events",te.appendChild(Le),D=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),D.type="button",D.title="Copy All";let pt=me("clipboard-copy","12px","currentColor",1.5);pt&&D.appendChild(pt);let ve=h("span","persona-text-xs");ve.textContent="Copy All",D.appendChild(ve),J.appendChild(_),J.appendChild(ee),J.appendChild(xe),J.appendChild(te),J.appendChild(D);let Ce=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Lr(Ce,p==null?void 0:p.searchBar);let Be=me("search","14px","var(--persona-muted, #9ca3af)",1.5),ue=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Be&&ue.appendChild(Be),U=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Lr(U,p==null?void 0:p.searchInput),U.type="text",U.placeholder="Search event payloads...",oe=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),oe.type="button",oe.style.display="none";let bt=me("x","12px","currentColor",2);return bt&&oe.appendChild(bt),Ce.appendChild(ue),Ce.appendChild(U),Ce.appendChild(oe),Z.appendChild(J),Z.appendChild(Ce),Z}let ht,at=o.find(Z=>Z.renderEventStreamToolbar);if(at!=null&&at.renderEventStreamToolbar&&s){let Z=at.renderEventStreamToolbar({config:s,defaultRenderer:()=>he(),eventCount:n.getSize(),filteredCount:0,onFilterChange:J=>{C=J,K(),Ve()},onSearchChange:J=>{v=J,K(),Ve()}});ht=Z!=null?Z:he()}else ht=he();let gt=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");gt.style.display="none";let Wt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),de=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");de.style.height="100%";let ie=h("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");Lr(ie,p==null?void 0:p.scrollIndicator),ie.style.display="none";let qe=me("arrow-down","12px","currentColor",2);qe&&ie.appendChild(qe);let j=h("span","");ie.appendChild(j);let G=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");G.style.display="none",Wt.appendChild(de),Wt.appendChild(G),Wt.appendChild(ie),f.setAttribute("tabindex","0"),f.appendChild(ht),f.appendChild(gt),f.appendChild(Wt);function be(){let Z=n.getAll(),J={};for(let ve of Z)J[ve.type]=(J[ve.type]||0)+1;let _=Object.keys(J).sort(),xe=_.length!==x.length||!_.every((ve,Ce)=>ve===x[Ce]),Le=!xe&&_.some(ve=>J[ve]!==k[ve]),He=Z.length!==Object.values(k).reduce((ve,Ce)=>ve+Ce,0);if(!xe&&!Le&&!He||(x=_,k=J,!te))return;let pt=te.value;if(te.options[0].textContent="All events",xe){for(;te.options.length>1;)te.remove(1);for(let ve of _){let Ce=h("option","");Ce.value=ve,Ce.textContent=`${ve} (${J[ve]||0})`,te.appendChild(Ce)}pt&&_.includes(pt)?te.value=pt:pt&&(te.value="",C="")}else for(let ve=1;ve<te.options.length;ve++){let Ce=te.options[ve];Ce.textContent=`${Ce.value} (${J[Ce.value]||0})`}}function ze(){let Z=n.getAll();if(C&&(Z=Z.filter(J=>J.type===C)),v){let J=v.toLowerCase();Z=Z.filter(_=>_.type.toLowerCase().includes(J)||_.payload.toLowerCase().includes(J))}return Z}function X(){return C!==""||v!==""}function K(){q=0,N=0,M=!1,ie.style.display="none"}function tt(Z){z.has(Z)?z.delete(Z):z.add(Z),ye=Z;let J=de.scrollTop,_=M;Y=!0,M=!0,Ve(),de.scrollTop=J,M=_,Y=!1}function We(){return de.scrollHeight-de.scrollTop-de.clientHeight<=50}function Ve(){w=Date.now(),F=!1,be();let Z=n.getEvictedCount();Z>0?(gt.textContent=`${Z.toLocaleString()} older events truncated`,gt.style.display=""):gt.style.display="none",m=ze();let J=m.length,_=n.getSize()>0;ee&&(ee.textContent=String(n.getSize())),J===0&&_&&X()?(G.textContent=v?`No events matching '${v}'`:"No events matching filter",G.style.display="",de.style.display="none"):(G.style.display="none",de.style.display=""),D&&(D.title=X()?`Copy Filtered (${J})`:"Copy All"),M&&J>q&&(N+=J-q,j.textContent=`${N} new event${N===1?"":"s"}`,ie.style.display=""),q=J;let xe=n.getAll(),Le=xe.length>0?xe[0].timestamp:0,He=new Set(m.map(Ce=>Ce.id));for(let Ce of z)He.has(Ce)||z.delete(Ce);let pt=C!==Ie||v!==Xe,ve=ge.size===0&&m.length>0;if(pt||ve||m.length===0){de.innerHTML="",ge.clear();let Ce=document.createDocumentFragment();for(let Be=0;Be<m.length;Be++){let ue=Ds(m[Be],Be,Le,a,z,tt,o,s);ge.set(m[Be].id,ue),Ce.appendChild(ue)}de.appendChild(Ce),Ie=C,Xe=v,ye=null}else{if(ye!==null){let Be=ge.get(ye);if(Be&&Be.parentNode===de){let ue=m.findIndex(bt=>bt.id===ye);if(ue>=0){let bt=Ds(m[ue],ue,Le,a,z,tt,o,s);de.insertBefore(bt,Be),Be.remove(),ge.set(ye,bt)}}ye=null}let Ce=new Set(m.map(Be=>Be.id));for(let[Be,ue]of ge)Ce.has(Be)||(ue.remove(),ge.delete(Be));for(let Be=0;Be<m.length;Be++){let ue=m[Be];if(!ge.has(ue.id)){let bt=Ds(ue,Be,Le,a,z,tt,o,s);ge.set(ue.id,bt),de.appendChild(bt)}}}M||(de.scrollTop=de.scrollHeight)}function Tt(){if(Date.now()-w>=Ud){re!==null&&(cancelAnimationFrame(re),re=null),Ve();return}F||(F=!0,re=requestAnimationFrame(()=>{re=null,Ve()}))}let _t=(Z,J)=>{if(!D)return;D.innerHTML="";let _=me(Z,"12px","currentColor",1.5);_&&D.appendChild(_);let xe=h("span","persona-text-xs");xe.textContent="Copy All",D.appendChild(xe),setTimeout(()=>{D.innerHTML="";let Le=me("clipboard-copy","12px","currentColor",1.5);Le&&D.appendChild(Le);let He=h("span","persona-text-xs");He.textContent="Copy All",D.appendChild(He),D.disabled=!1},J)},ce=async()=>{if(D){D.disabled=!0;try{let Z;X()?Z=m:t?(Z=await t(),Z.length===0&&(Z=n.getAll())):Z=n.getAll();let J=Z.map(_=>{try{return JSON.parse(_.payload)}catch{return _.payload}});await navigator.clipboard.writeText(JSON.stringify(J,null,2)),_t("check",1500)}catch{_t("x",1500)}}},Je=()=>{te&&(C=te.value,K(),Ve())},Me=()=>{!U||!oe||(oe.style.display=U.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{v=U.value,K(),Ve()},150))},nt=()=>{!U||!oe||(U.value="",v="",oe.style.display="none",E&&clearTimeout(E),K(),Ve())},je=()=>{if(Y)return;let Z=de.scrollTop,J=Z>ae;ae=Z,We()&&J?(M=!1,N=0,ie.style.display="none"):We()||(M=!0)},Ze=Z=>{Z.deltaY<0&&(M=!0)},Rt=()=>{de.scrollTop=de.scrollHeight,M=!1,N=0,ie.style.display="none"},Ht=Z=>{let J=Z.target;if(!J||J.closest("button"))return;let _=J.closest("[data-event-id]");if(!_)return;let xe=_.getAttribute("data-event-id");xe&&tt(xe)},Mt=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),U==null||U.focus(),U==null||U.select();return}Z.key==="Escape"&&(U&&document.activeElement===U?(nt(),U.blur(),f.focus()):r&&r())};D&&D.addEventListener("click",ce),te&&te.addEventListener("change",Je),U&&U.addEventListener("input",Me),oe&&oe.addEventListener("click",nt),de.addEventListener("scroll",je),de.addEventListener("wheel",Ze,{passive:!0}),de.addEventListener("click",Ht),ie.addEventListener("click",Rt),f.addEventListener("keydown",Mt);function B(){E&&clearTimeout(E),re!==null&&(cancelAnimationFrame(re),re=null),F=!1,ge.clear(),D&&D.removeEventListener("click",ce),te&&te.removeEventListener("change",Je),U&&U.removeEventListener("input",Me),oe&&oe.removeEventListener("click",nt),de.removeEventListener("scroll",je),de.removeEventListener("wheel",Ze),de.removeEventListener("click",Ht),ie.removeEventListener("click",Rt),f.removeEventListener("keydown",Mt)}return{element:f,update:Tt,destroy:B}}}var cc=e=>{let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",t=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",o=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",a=document.createElement("div");a.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.backgroundColor="var(--persona-bg, #ffffff)",a.style.cursor="pointer",a.tabIndex=0,a.setAttribute("role","button"),a.setAttribute("aria-label",`Open ${n} in artifact panel`),t&&a.setAttribute("data-open-artifact",t);let i=document.createElement("div");i.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.color="var(--persona-muted, #9ca3af)",i.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let c=document.createElement("div");c.className="persona-truncate persona-text-sm persona-font-medium",c.style.color="var(--persona-text, #1f2937)",c.textContent=n;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #3b82f6)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let f=document.createElement("span");f.textContent=`Generating ${o.toLowerCase()}...`,g.appendChild(f)}else g.textContent=o;if(d.append(c,g),a.append(i,d),r==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${n}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",t),a.append(p)}return a};var _s=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},In=new _s;In.register("PersonaArtifactCard",cc);function Zd(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function ao(e,n,t=""){let r=h("button",`persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-p-1 persona-text-persona-primary hover:persona-bg-persona-container ${t}`);r.type="button",r.setAttribute("aria-label",n),r.title=n;let s=me(e,16,"currentColor",2);return s&&r.appendChild(s),r}function io(e,n,t){let r=h("button",`persona-artifact-doc-icon-btn ${t}`.trim());r.type="button",r.setAttribute("aria-label",n),r.title=n;let s=me(e,16,"currentColor",2);return s&&r.appendChild(s),r}function dc(e){let n=h("button","persona-artifact-doc-copy-btn");n.type="button",n.setAttribute("aria-label","Copy"),n.title="Copy";let t=me("copy",e?14:16,"currentColor",2);if(t&&n.appendChild(t),e){let r=h("span","persona-artifact-doc-copy-label");r.textContent="Copy",n.appendChild(r)}return n}function Qd(){let e=h("button","persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn");e.type="button",e.setAttribute("aria-label","More copy options"),e.setAttribute("aria-haspopup","true"),e.setAttribute("aria-expanded","false");let n=me("chevron-down",14,"currentColor",2);return n&&e.appendChild(n),e}function pc(e,n){var Wt,de,ie,qe;let t=(de=(Wt=e.features)==null?void 0:Wt.artifacts)==null?void 0:de.layout,s=((ie=t==null?void 0:t.toolbarPreset)!=null?ie:"default")==="document",o=(qe=t==null?void 0:t.panePadding)==null?void 0:qe.trim(),a=e.markdown?Zn(e.markdown):null,i=xr(e.sanitize),d=j=>{let G=a?a(j):br(j);return i?i(G):G},c=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")};c&&c.addEventListener("click",()=>{var j;g(),(j=n.onDismiss)==null||j.call(n)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let C=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var j;g(),(j=n.onDismiss)==null||j.call(n)});let v="rendered",E=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),x=s?io("eye","Rendered view","persona-artifact-view-btn"):ao("eye","Rendered view",""),k=s?io("code-2","Source","persona-artifact-code-btn"):ao("code-2","Source",""),q=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,N=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,F=!!(N&&w&&w.length>0),re=null,Y,ae=null,z=null;if(s&&(M||N)&&!F){if(Y=dc(M),N){let j=me("chevron-down",14,"currentColor",2);j&&Y.appendChild(j)}}else if(s&&F){re=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Y=dc(M),ae=Qd(),re.append(Y,ae),z=h("div","persona-artifact-doc-copy-menu persona-absolute persona-right-0 persona-top-full persona-z-20 persona-mt-1 persona-min-w-[10rem] persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-py-1 persona-shadow-md persona-hidden"),re.appendChild(z);for(let j of w){let G=h("button","persona-block persona-w-full persona-text-left persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary hover:persona-bg-persona-container");G.type="button",G.textContent=j.label,G.dataset.copyMenuId=j.id,z.appendChild(G)}}else s?Y=io("copy","Copy",""):Y=ao("copy","Copy","");let ge=s?io("refresh-cw","Refresh",""):ao("refresh-cw","Refresh",""),Ie=s?io("x","Close",""):ao("x","Close",""),Xe=()=>{var X,K,tt;let j=(X=oe.find(We=>We.id===he))!=null?X:oe[oe.length-1],G=(K=j==null?void 0:j.id)!=null?K:null,be=(j==null?void 0:j.artifactType)==="markdown"&&(tt=j.markdown)!=null?tt:"",ze=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:be,jsonPayload:ze,id:G}},ye=async()=>{var X;let{markdown:j,jsonPayload:G}=Xe(),be=(X=oe.find(K=>K.id===he))!=null?X:oe[oe.length-1],ze=(be==null?void 0:be.artifactType)==="markdown"?j:be?G:"";try{await navigator.clipboard.writeText(ze)}catch{}};if(Y.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&F){let{markdown:G,jsonPayload:be,id:ze}=Xe();try{await j({actionId:"primary",artifactId:ze,markdown:G,jsonPayload:be})}catch{}return}await ye()}),ae&&z){let j=()=>{z.classList.add("persona-hidden"),ae.setAttribute("aria-expanded","false")};ae.addEventListener("click",G=>{G.stopPropagation(),z.classList.contains("persona-hidden")?(z.classList.remove("persona-hidden"),ae.setAttribute("aria-expanded","true")):j()}),typeof document!="undefined"&&document.addEventListener("click",j),z.addEventListener("click",async G=>{let be=G.target.closest("button[data-copy-menu-id]");if(!(be!=null&&be.dataset.copyMenuId))return;G.stopPropagation();let ze=be.dataset.copyMenuId,{markdown:X,jsonPayload:K,id:tt}=Xe(),We=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{We?await We({actionId:ze,artifactId:tt,markdown:X,jsonPayload:K}):ze==="markdown"||ze==="md"?await navigator.clipboard.writeText(X):ze==="json"||ze==="source"?await navigator.clipboard.writeText(K):await navigator.clipboard.writeText(X||K)}catch{}j()})}ge.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}at()}),Ie.addEventListener("click",()=>{var j;g(),(j=n.onDismiss)==null||j.call(n)});let ee=()=>{s&&(x.setAttribute("aria-pressed",v==="rendered"?"true":"false"),k.setAttribute("aria-pressed",v==="source"?"true":"false"))};x.addEventListener("click",()=>{v="rendered",ee(),at()}),k.addEventListener("click",()=>{v="source",ee(),at()});let te=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),E.append(x,k),re?q.append(re,ge,Ie):q.append(Y,ge,Ie),f.append(E,te,q),ee()):(f.appendChild(m),f.appendChild(C)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let D=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),U=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(D.style.paddingLeft=o,D.style.paddingRight=o,U.style.padding=o),p.appendChild(f),p.appendChild(D),p.appendChild(U);let oe=[],he=null,ht=!1,at=()=>{var ze,X,K,tt;let j=s&&oe.length<=1;D.classList.toggle("persona-hidden",j),D.replaceChildren();for(let We of oe){let Ve=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary hover:persona-bg-persona-container");Ve.type="button",Ve.textContent=We.title||We.id.slice(0,8),We.id===he&&Ve.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ve.addEventListener("click",()=>n.onSelect(We.id)),D.appendChild(Ve)}U.replaceChildren();let G=he&&oe.find(We=>We.id===he)||oe[oe.length-1];if(!G)return;if(s){let We=G.artifactType==="markdown"?"MD":(ze=G.component)!=null?ze:"Component",Tt=(G.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";te.textContent=`${Tt} \xB7 ${We}`}else m.textContent="Artifacts";if(G.artifactType==="markdown"){if(s&&v==="source"){let Ve=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ve.textContent=(X=G.markdown)!=null?X:"",U.appendChild(Ve);return}let We=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((K=G.markdown)!=null?K:""),U.appendChild(We);return}let be=G.component?In.get(G.component):void 0;if(be){let Ve={message:{id:G.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Tt=be((tt=G.props)!=null?tt:{},Ve);if(Tt){U.appendChild(Tt);return}}catch{}}U.appendChild(Zd(G))},gt=()=>{var G;let j=oe.length>0;if(p.classList.toggle("persona-hidden",!j),c){let be=typeof p.closest=="function"?p.closest("#persona-root"):null,X=((G=be==null?void 0:be.classList.contains("persona-artifact-narrow-host"))!=null?G:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&X&&ht?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(j){var G,be,ze;oe=j.artifacts,he=(ze=(be=j.selectedId)!=null?be:(G=j.artifacts[j.artifacts.length-1])==null?void 0:G.id)!=null?ze:null,oe.length>0&&(ht=!0),at(),gt()},setMobileOpen(j){ht=j,!j&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):gt()}}}function an(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function uc(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!an(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function ep(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Zo(e,n){var d,c,g,p,f,m,C,v,E,x;if(!an(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),ep(e),uc(e,n);return}let t=(c=(d=n.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(g=t==null?void 0:t.splitGap)!=null?g:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(x=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),uc(e,n)}var gc=["panel","seamless"];function Qo(e,n){var i,d,c,g,p,f;for(let m of gc)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!an(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=gc.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(g=t==null?void 0:t.paneBorderRadius)==null?void 0:g.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function mc(e,n){var t,r,s;return!n||!an(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function tp(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function np(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function rp(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function op(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function fc(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function hc(e,n,t,r,s,o){let a=tp(s,200),i=op(n,t,r,200);i=Math.max(a,i);let d=np(o);return d!==null&&(i=Math.min(i,d)),rp(e,a,i)}var yc={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},js=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var C,v,E;if(o.dataset.enhanced==="true")return;let a=(C=o.dataset.tvForm)!=null?C:"init";o.dataset.enhanced="true";let i=(v=yc[a])!=null?v:yc.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let x=h("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var w,F;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${n.id}-${a}-${x.name}`;let q=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");q.textContent=x.label,k.appendChild(q);let M=(w=x.type)!=null?w:"text",N;M==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=M),N.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",N.id=`${n.id}-${a}-${x.name}`,N.name=x.name,N.placeholder=(F=x.placeholder)!=null?F:"",x.required&&(N.required=!0),k.appendChild(N),g.appendChild(k)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(f),p.appendChild(m),g.appendChild(p),o.replaceChildren(d,g),g.addEventListener("submit",async x=>{var N,w;x.preventDefault();let k=(N=t.formEndpoint)!=null?N:"/form",q=new FormData(g),M={};q.forEach((F,re)=>{M[re]=F}),M.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let F=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!F.ok)throw new Error(`Form submission failed (${F.status})`);let re=await F.json();f.textContent=(w=re.message)!=null?w:"Thanks! We'll be in touch soon.",re.success&&re.nextPrompt&&await r.sendMessage(String(re.nextPrompt))}catch(F){f.textContent=F instanceof Error?F.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Vs=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},lo=new Vs;var Us={primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},qs={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},ut={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Us,darkTheme:qs,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px",collapsedWidth:"72px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function es(e){var n,t,r,s,o,a,i,d,c,g,p,f,m,C,v,E,x,k,q,M,N;return e?{...ut,...e,theme:{...ut.theme,...e.theme},darkTheme:{...ut.darkTheme,...e.darkTheme},launcher:{...ut.launcher,...e.launcher,dock:{...(n=ut.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=ut.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...ut.copy,...e.copy},sendButton:{...ut.sendButton,...e.sendButton},statusIndicator:{...ut.statusIndicator,...e.statusIndicator},voiceRecognition:{...ut.voiceRecognition,...e.voiceRecognition},features:(()=>{var Y,ae;let w=(Y=ut.features)==null?void 0:Y.artifacts,F=(ae=e.features)==null?void 0:ae.artifacts,re=w===void 0&&F===void 0?void 0:{...w,...F,layout:{...w==null?void 0:w.layout,...F==null?void 0:F.layout}};return{...ut.features,...e.features,...re!==void 0?{artifacts:re}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:ut.suggestionChips,suggestionChipsConfig:{...ut.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ut.layout,...e.layout,header:{...(a=ut.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=ut.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(g=ut.layout)==null?void 0:g.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(v=(C=ut.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(x=(E=e.layout)==null?void 0:E.messages)==null?void 0:x.timestamp}},slots:{...(k=ut.layout)==null?void 0:k.slots,...(q=e.layout)==null?void 0:q.slots}},markdown:{...ut.markdown,...e.markdown,options:{...(M=ut.markdown)==null?void 0:M.options,...(N=e.markdown)==null?void 0:N.options}},messageActions:{...ut.messageActions,...e.messageActions}}:ut}var bc=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var sp=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},ap=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},co=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=sp(e),t=ap(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},zs=e=>typeof e=="string"?e:e==null?"":String(e),ar={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:zs(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=zs(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:zs(t.text)}}},xc=e=>Array.isArray(e)?e.map(n=>String(n)):[],po=e=>{let n=new Set(xc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(xc(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,g)=>c||(g==null?void 0:g({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let g=()=>{e.emit("action:resubmit",d)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:g});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:t}};var ip=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},lp=e=>e.map(n=>({...n,streaming:!1})),ts=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?ip(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?lp(t.messages):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Pr=require("partial-json");function cp(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function dp(e,n){if(!cp(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function ns(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=(0,Pr.parse)(t,Pr.STR|Pr.OBJ),o=dp(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function vc(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function rs(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=In.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Cc(){let e=ns();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function os(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ss(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var pp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function as(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=pp}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=r,m.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,m.appendChild(v),f.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let w=1;w<=5;w++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-star-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${c[w-1]}`),F.title=c[w-1],F.dataset.rating=String(w),F.innerHTML=`
|
|
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
|
-
`,F.addEventListener("click",()=>{p=w,x.forEach((Q,K)=>{let oe=K<w;Q.classList.toggle("selected",oe),Q.setAttribute("aria-checked",K===w-1?"true":"false")})}),x.push(F),E.appendChild(F)}y.appendChild(E);let k=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),w.appendChild(k),y.appendChild(w)}let q=document.createElement("div");q.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{t==null||t(),g.remove()});let N=document.createElement("button");return N.type="button",N.className="persona-feedback-btn persona-feedback-btn-submit",N.textContent=a,N.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let w=(k==null?void 0:k.value.trim())||void 0;await n(p,w),g.remove()}catch(w){N.disabled=!1,N.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),q.appendChild(M),q.appendChild(N),y.appendChild(q),g.appendChild(y),g}function as(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:g="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let y=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,C.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,C.appendChild(E),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 k=document.createElement("div");k.className="persona-feedback-labels";let q=document.createElement("span");q.className="persona-feedback-label-low",q.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=g,k.appendChild(q),k.appendChild(M);let N=document.createElement("div");N.className="persona-feedback-numbers";let w=[];for(let J=0;J<=10;J++){let me=document.createElement("button");me.type="button",me.className="persona-feedback-rating-btn persona-feedback-number-btn",me.setAttribute("role","radio"),me.setAttribute("aria-checked","false"),me.setAttribute("aria-label",`Rating ${J} out of 10`),me.textContent=String(J),me.dataset.rating=String(J),J<=6?me.classList.add("persona-feedback-detractor"):J<=8?me.classList.add("persona-feedback-passive"):me.classList.add("persona-feedback-promoter"),me.addEventListener("click",()=>{y=J,w.forEach((We,Ge)=>{We.classList.toggle("selected",Ge===J),We.setAttribute("aria-checked",Ge===J?"true":"false")})}),w.push(me),N.appendChild(me)}x.appendChild(k),x.appendChild(N),m.appendChild(x);let F=null;if(d){let J=document.createElement("div");J.className="persona-feedback-comment-container",F=document.createElement("textarea"),F.className="persona-feedback-comment",F.placeholder=o,F.rows=3,F.setAttribute("aria-label","Additional comments"),J.appendChild(F),m.appendChild(J)}let Q=document.createElement("div");Q.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=i,K.addEventListener("click",()=>{t==null||t(),p.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=a,oe.addEventListener("click",async()=>{if(y===null){N.classList.add("persona-feedback-shake"),setTimeout(()=>N.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let J=(F==null?void 0:F.value.trim())||void 0;await n(y,J),p.remove()}catch(J){oe.disabled=!1,oe.textContent=a,console.error("[NPS Feedback] Failed to submit:",J)}}),Q.appendChild(K),Q.appendChild(oe),m.appendChild(Q),p.appendChild(m),p}var Pr="persona-chat-history",ap=30*1e3,ip={"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 lp(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=ip[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function cp(e){var n,t,r,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function dp(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var qs=e=>!e||typeof e!="object"?{}:{...e},bc=e=>e.map(n=>({...n,streaming:!1})),xc=(e,n,t)=>{let r=e!=null&&e.markdown?Zn(e.markdown):null;return s=>{var i,d,c;let o=(i=s.text)!=null?i:"",a=(d=s.message.rawContent)!=null?d:null;if(n){let g=n.process({text:o,raw:a!=null?a:o,message:s.message,streaming:s.streaming});g!==null&&(o=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&t&&t())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...s,text:o,raw:(c=a!=null?a:s.text)!=null?c:""}):r?r(o):br(o)}},is=(e,n,t)=>{var le,Se,ot,Mt,wt,Ht,kt,st,it,At,lt,Bt,Yt,on,sa,aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let r=Qo(n),s=io.getForInstance(r.plugins);r.components&&In.registerAll(r.components);let o=mc(),a=(le=r.storageAdapter)!=null?le:es(),i={},d=null,c=l=>{if(r.onStateLoaded)try{return r.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return c(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=c(u);h.metadata&&(i=qs(h.metadata)),(Se=h.messages)!=null&&Se.length&&(r={...r,initialMessages:h.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=c({messages:[],metadata:{}});(ot=l.messages)!=null&&ot.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>i,p=l=>{var h;i=(h=l({...i}))!=null?h:{},Or()},y=r.actionParsers&&r.actionParsers.length?r.actionParsers:[lo],m=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ar.message,ar.messageAndClick],C=co({parsers:y,handlers:m,getSessionMetadata:g,updateSessionMetadata:p,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let v=(wt=(Mt=r.launcher)==null?void 0:Mt.enabled)!=null?wt:!0,E=(kt=(Ht=r.launcher)==null?void 0:Ht.autoExpand)!=null?kt:!1,x=(st=r.autoFocusInput)!=null?st:!1,k=E,q=v,M=(At=(it=r.layout)==null?void 0:it.header)==null?void 0:At.layout,N=!1,w=v?E:!0,F=!1,Q=null,K=()=>{F=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},oe=xc(r,C,K),J=(Bt=(lt=r.features)==null?void 0:lt.showReasoning)!=null?Bt:!0,me=(on=(Yt=r.features)==null?void 0:Yt.showToolCalls)!=null?on:!0,We=(aa=(sa=r.features)==null?void 0:sa.showEventStreamToggle)!=null?aa:!1,ye=`${(la=typeof r.persistState=="object"?(ia=r.persistState)==null?void 0:ia.keyPrefix:void 0)!=null?la:"persona-"}event-stream`,ee=We?new oo(ye):null,Y=(pa=(da=(ca=r.features)==null?void 0:ca.eventStream)==null?void 0:da.maxEvents)!=null?pa:2e3,_=We?new ro(Y,ee):null,D=null,ue=!1,be=null,gt=0;ee==null||ee.open().then(()=>_==null?void 0:_.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ct={onCopy:l=>{var u,h;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(S=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(S=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},mt=(ua=r.statusIndicator)!=null?ua:{},It=l=>{var u,h,S,R;return l==="idle"?(u=mt.idleText)!=null?u:jt.idle:l==="connecting"?(h=mt.connectingText)!=null?h:jt.connecting:l==="connected"?(S=mt.connectedText)!=null?S:jt.connected:l==="error"?(R=mt.errorText)!=null?R:jt.error:jt[l]},{wrapper:de,panel:ae}=Gl(r),U=Zl(r,v),{container:ne,body:ie,messagesWrapper:Te,suggestions:Xe,textarea:te,sendButton:X,sendButtonWrapper:He,composerForm:Ue,statusText:tt,introTitle:Ut,introSubtitle:Dt,closeButton:ce,iconHolder:ze,headerTitle:ke,headerSubtitle:nt,header:Ve,footer:Ze,actionsRow:Wt,leftActions:Rt,rightActions:Tt}=U,B=U.micButton,G=U.micButtonWrapper,z=U.attachmentButton,j=U.attachmentButtonWrapper,xe=U.attachmentInput,Pe=U.attachmentPreviewsContainer,Be=null,pt=null,ve=s.find(l=>l.renderHeader);if(ve!=null&&ve.renderHeader){let l=ve.renderHeader({config:r,defaultRenderer:()=>{let u=Pn({config:r,showClose:v});return or(ne,u,r),u.header},onClose:()=>ft(!1,"user")});if(l){let u=ne.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),Ve=l)}}let Ce=()=>{var u,h,S,R;if(!_)return;if(ue=!0,!D&&_&&(D=oc({buffer:_,getFullHistory:()=>_.getAllFromStore(),onClose:()=>Fe(),config:r,plugins:s})),D&&(ie.style.display="none",(u=Ze.parentNode)==null||u.insertBefore(D.element,Ze),D.update()),ge){ge.classList.remove("persona-text-persona-muted"),ge.classList.add("persona-text-persona-accent"),ge.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let L=(R=(S=(h=r.features)==null?void 0:h.eventStream)==null?void 0:S.classNames)==null?void 0:R.toggleButtonActive;L&&L.split(/\s+/).forEach(P=>P&&ge.classList.add(P))}let l=()=>{if(!ue)return;let L=Date.now();L-gt>=200&&(D==null||D.update(),gt=L),be=requestAnimationFrame(l)};gt=0,be=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},Fe=()=>{var l,u,h;if(ue){if(ue=!1,D&&D.element.remove(),ie.style.display="",ge){ge.classList.remove("persona-text-persona-accent"),ge.classList.add("persona-text-persona-muted"),ge.style.boxShadow="";let S=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;S&&S.split(/\s+/).forEach(R=>R&&ge.classList.remove(R))}be!==null&&(cancelAnimationFrame(be),be=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},ge=null;if(We){let l=(ma=(ga=r.features)==null?void 0:ga.eventStream)==null?void 0:ma.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ge=f("button",u),ge.style.width="28px",ge.style.height="28px",ge.type="button",ge.setAttribute("aria-label","Event Stream"),ge.title="Event Stream";let h=fe("activity","18px","currentColor",1.5);h&&ge.appendChild(h);let S=U.clearChatButtonWrapper,R=U.closeButtonWrapper,L=S||R;L&&L.parentNode===Ve?Ve.insertBefore(ge,L):Ve.appendChild(ge),ge.addEventListener("click",()=>{ue?Fe():Ce()})}let bt=l=>{var S,R,L;let u=r.attachments;if(!(u!=null&&u.enabled))return;let h=l.querySelector(".persona-attachment-previews");if(!h){h=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let P=l.querySelector("[data-persona-composer-form]");P!=null&&P.parentNode?P.parentNode.insertBefore(h,P):l.insertBefore(h,l.firstChild)}if(!l.querySelector('input[type="file"]')){let P=f("input");P.type="file",P.accept=((S=u.allowedTypes)!=null?S:Ln).join(","),P.multiple=((R=u.maxFiles)!=null?R:4)>1,P.style.display="none",P.setAttribute("aria-label",(L=u.buttonTooltipText)!=null?L:"Attach files"),l.appendChild(P)}},Zt=s.find(l=>l.renderComposer);if(Zt!=null&&Zt.renderComposer){let l=r.composer,u=Zt.renderComposer({config:r,defaultRenderer:()=>Ar({config:r}).footer,onSubmit:h=>{H&&!H.isStreaming()&&H.sendMessage(h)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{xe==null||xe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h}},onVoiceToggle:((fa=r.voiceRecognition)==null?void 0:fa.enabled)===!0?()=>{pt==null||pt()}:void 0});u&&(Ze.replaceWith(u),Ze=u)}let un=l=>{let u=l.querySelector("[data-persona-composer-form]"),h=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),L=l.querySelector("[data-persona-composer-status]");u&&(Ue=u),h&&(te=h),S&&(X=S),R&&(B=R,G=R.parentElement),L&&(tt=L);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(Xe=P);let V=l.querySelector(".persona-attachment-button");V&&(z=V,j=V.parentElement),xe=l.querySelector('input[type="file"]'),Pe=l.querySelector(".persona-attachment-previews");let $=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");$&&(Wt=$)};bt(Ze),un(Ze);let gn=(ha=r.layout)==null?void 0:ha.contentMaxWidth;gn&&Ue&&(Ue.style.maxWidth=gn,Ue.style.marginLeft="auto",Ue.style.marginRight="auto"),(ya=r.attachments)!=null&&ya.enabled&&xe&&Pe&&(Be=rr.fromConfig(r.attachments),Be.setPreviewsContainer(Pe),xe.addEventListener("change",l=>{let u=l.target;Be==null||Be.handleFileSelect(u.files),u.value=""})),(()=>{var S,R;let l=(R=(S=r.layout)==null?void 0:S.slots)!=null?R:{},u=L=>{switch(L){case"body-top":return ne.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Te;case"footer-top":return Xe;case"composer":return Ue;case"footer-bottom":return tt;default:return null}},h=(L,P)=>{var V;switch(L){case"header-left":case"header-center":case"header-right":if(L==="header-left")Ve.insertBefore(P,Ve.firstChild);else if(L==="header-right")Ve.appendChild(P);else{let $=Ve.querySelector(".persona-flex-col");$?(V=$.parentNode)==null||V.insertBefore(P,$.nextSibling):Ve.appendChild(P)}break;case"body-top":{let $=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");$?$.replaceWith(P):ie.insertBefore(P,ie.firstChild);break}case"body-bottom":ie.appendChild(P);break;case"footer-top":Xe.replaceWith(P);break;case"footer-bottom":tt.replaceWith(P);break;default:break}};for(let[L,P]of Object.entries(l))if(P)try{let V=P({config:r,defaultContent:()=>u(L)});V&&h(L,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${L}":`,V)}})();let Rn=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let S=h.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!S)return;let R=S.getAttribute("data-message-id");if(!R)return;let L=h.getAttribute("data-bubble-type");L==="reasoning"?(Tr.has(R)?Tr.delete(R):Tr.add(R),tc(R,S)):L==="tool"&&(Mr.has(R)?Mr.delete(R):Mr.add(R),nc(R,S,r))};Te.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Rn(l))}),Te.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Rn(l))});let lr=new Map;Te.addEventListener("click",l=>{var P;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let S=h.closest("[data-actions-for]");if(!S)return;let R=S.getAttribute("data-actions-for");if(!R)return;let L=h.getAttribute("data-action");if(L==="copy"){let $=H.getMessages().find(se=>se.id===R);if($&&ct.onCopy){let se=$.content||"";navigator.clipboard.writeText(se).then(()=>{h.classList.add("persona-message-action-success");let he=fe("check",14,"currentColor",2);he&&(h.innerHTML="",h.appendChild(he)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Le=fe("copy",14,"currentColor",2);Le&&(h.innerHTML="",h.appendChild(Le))},2e3)}).catch(he=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",he)}),ct.onCopy($)}}else if(L==="upvote"||L==="downvote")if(((P=lr.get(R))!=null?P:null)===L)lr.delete(R),h.classList.remove("persona-message-action-active");else{let se=L==="upvote"?"downvote":"upvote",he=S.querySelector(`[data-action="${se}"]`);he&&he.classList.remove("persona-message-action-active"),lr.set(R,L),h.classList.add("persona-message-action-active");let Oe=H.getMessages().find(Ae=>Ae.id===R);Oe&&ct.onFeedback&&ct.onFeedback({type:L,messageId:Oe.id,message:Oe})}}),Te.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let S=h.closest(".vanilla-approval-bubble");if(!S)return;let R=S.getAttribute("data-message-id");if(!R)return;let L=h.getAttribute("data-approval-action");if(!L)return;let P=L==="approve"?"approved":"denied",$=H.getMessages().find(he=>he.id===R);if(!($!=null&&$.approval))return;let se=S.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Le=>{Le.disabled=!0,Le.style.opacity="0.5",Le.style.cursor="not-allowed"}),H.resolveApproval($.approval,P)});let Qe=null,mn=null,Hn={artifacts:[],selectedId:null},ln=!1,Ir={current:null};Te.addEventListener("click",l=>{var Le,Oe,Ae,I,Me;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let S=h.getAttribute("data-download-artifact");if(!S||((Ae=(Oe=(Le=r.features)==null?void 0:Le.artifacts)==null?void 0:Oe.onArtifactAction)==null?void 0:Ae.call(Oe,{type:"download",artifactId:S}))===!0)return;let L=H.getArtifactById(S),P=L==null?void 0:L.markdown,V=(L==null?void 0:L.title)||"artifact";if(!P){let Ee=h.closest("[data-open-artifact]"),re=Ee==null?void 0:Ee.closest("[data-message-id]"),Ie=re==null?void 0:re.getAttribute("data-message-id");if(Ie){let Je=H.getMessages().find(pe=>pe.id===Ie);if(Je!=null&&Je.rawContent)try{let pe=JSON.parse(Je.rawContent);P=(I=pe==null?void 0:pe.props)==null?void 0:I.markdown,V=((Me=pe==null?void 0:pe.props)==null?void 0:Me.title)||V}catch{}}}if(!P)return;let $=new Blob([P],{type:"text/markdown"}),se=URL.createObjectURL($),he=document.createElement("a");he.href=se,he.download=`${V}.md`,he.click(),URL.revokeObjectURL(se)}),Te.addEventListener("click",l=>{var L,P,V;let h=l.target.closest("[data-open-artifact]");if(!h)return;let S=h.getAttribute("data-open-artifact");!S||((V=(P=(L=r.features)==null?void 0:L.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:V.call(P,{type:"open",artifactId:S}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(S),hn())}),Te.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let fn=null,dt=null,nn=null,wn=null,Wr=()=>{};function cr(){wn==null||wn(),wn=null}let Rr=()=>{var P;if(!fn||!dt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((P=e.ownerDocument.defaultView)!=null?P:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){dt.style.removeProperty("position"),dt.style.removeProperty("left"),dt.style.removeProperty("top"),dt.style.removeProperty("bottom"),dt.style.removeProperty("width"),dt.style.removeProperty("z-index");return}let S=fn.firstElementChild;if(!S||S===dt)return;let R=10;dt.style.position="absolute",dt.style.top="0",dt.style.bottom="0",dt.style.width=`${R}px`,dt.style.zIndex="5";let L=S.offsetWidth-R/2;dt.style.left=`${Math.max(0,L)}px`},Dn=()=>{},hn=()=>{var h,S,R,L,P;if(!Qe||!an(r))return;Go(e,r),Zo(e,r),Dn();let l=(L=(R=(S=(h=r.features)==null?void 0:h.artifacts)==null?void 0:S.layout)==null?void 0:R.narrowHostMaxWidth)!=null?L:520,u=ae.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Qe.update(Hn),ln?(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),(P=Qe.backdrop)==null||P.classList.add("persona-hidden")):Hn.artifacts.length>0&&(Qe.element.classList.remove("persona-hidden"),Qe.setMobileOpen(!0)),Wr()};if(an(r)){ae.style.position="relative";let l=f("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=f("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ne),Qe=ic(r,{onSelect:h=>{var S;return(S=Ir.current)==null?void 0:S.selectArtifact(h)},onDismiss:()=>{ln=!0,hn()}}),Qe.element.classList.add("persona-hidden"),fn=u,u.appendChild(l),u.appendChild(Qe.element),Qe.backdrop&&ae.appendChild(Qe.backdrop),ae.appendChild(u),Wr=()=>{var S,R,L,P;if(!fn||!Qe)return;if(!(((L=(R=(S=r.features)==null?void 0:S.artifacts)==null?void 0:R.layout)==null?void 0:L.resizable)===!0)){nn==null||nn(),nn=null,cr(),dt&&(dt.remove(),dt=null),Qe.element.style.removeProperty("width"),Qe.element.style.removeProperty("maxWidth");return}if(!dt){let V=f("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let $=e.ownerDocument,se=(P=$.defaultView)!=null?P:window,he=Le=>{var re,Ie;if(!Qe||Le.button!==0||e.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Le.preventDefault(),cr();let Oe=Le.clientX,Ae=Qe.element.getBoundingClientRect().width,I=(Ie=(re=r.features)==null?void 0:re.artifacts)==null?void 0:Ie.layout,Me=rt=>{let Je=fn.getBoundingClientRect().width,pe=e.classList.contains("persona-artifact-appearance-seamless"),Lt=pe?0:pc(fn,se),at=pe?0:V.getBoundingClientRect().width||6,Xt=Ae-(rt.clientX-Oe),_t=uc(Xt,Je,Lt,at,I==null?void 0:I.resizableMinWidth,I==null?void 0:I.resizableMaxWidth);Qe.element.style.width=`${_t}px`,Qe.element.style.maxWidth="none",Rr()},Ee=()=>{$.removeEventListener("pointermove",Me),$.removeEventListener("pointerup",Ee),$.removeEventListener("pointercancel",Ee),wn=null;try{V.releasePointerCapture(Le.pointerId)}catch{}};wn=Ee,$.addEventListener("pointermove",Me),$.addEventListener("pointerup",Ee),$.addEventListener("pointercancel",Ee);try{V.setPointerCapture(Le.pointerId)}catch{}};V.addEventListener("pointerdown",he),dt=V,fn.insertBefore(V,Qe.element),nn=()=>{V.removeEventListener("pointerdown",he)}}if(dt){let V=Hn.artifacts.length>0&&!ln;dt.classList.toggle("persona-hidden",!V),Rr()}},Dn=()=>{var se,he,Le,Oe,Ae,I,Me,Ee,re,Ie,rt,Je,pe,Lt;if(!v||!Qe||((he=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?he:!1))return;let S=(Le=e.ownerDocument.defaultView)!=null?Le:window,R=(Ae=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Ae:!0,L=(Me=(I=r.launcher)==null?void 0:I.mobileBreakpoint)!=null?Me:640;if(R&&S.innerWidth<=L||!dc(r,v))return;let P=(Ie=(re=(Ee=r.launcher)==null?void 0:Ee.width)!=null?re:r.launcherWidth)!=null?Ie:"min(400px, calc(100vw - 24px))",V=(Lt=(pe=(Je=(rt=r.features)==null?void 0:rt.artifacts)==null?void 0:Je.layout)==null?void 0:pe.expandedPanelWidth)!=null?Lt:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!ln?(ae.style.width=V,ae.style.maxWidth=V):(ae.style.width=P,ae.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(mn=new ResizeObserver(()=>{hn()}),mn.observe(ae))}else ae.appendChild(ne);e.appendChild(de);let _n=()=>{var Je,pe,Lt,at,Xt,_t,zt,Ft,sn,je,yt,Eo,To,Mo,ko,Lo,hs,ys,Et,Po,qr;let l=Vt(r),u=(pe=(Je=r.launcher)==null?void 0:Je.sidebarMode)!=null?pe:!1,h=l||u||((at=(Lt=r.launcher)==null?void 0:Lt.fullHeight)!=null?at:!1),S=((Xt=r.launcher)==null?void 0:Xt.enabled)===!1,R=(_t=r.theme)!=null?_t:{},L=(zt=e.ownerDocument.defaultView)!=null?zt:window,P=(sn=(Ft=r.launcher)==null?void 0:Ft.mobileFullscreen)!=null?sn:!0,V=(yt=(je=r.launcher)==null?void 0:je.mobileBreakpoint)!=null?yt:640,$=L.innerWidth<=V,se=P&&$&&v,he=(To=(Eo=r.launcher)==null?void 0:Eo.position)!=null?To:"bottom-left",Le=he==="bottom-left"||he==="top-left",Oe=u||se?"none":"1px solid var(--persona-persona-border)",Ae=se?"none":u?Le?"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))",I=u||se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Me=(Mo=R.panelBorder)!=null?Mo:Oe,Ee=(ko=R.panelShadow)!=null?ko:Ae,re=(Lo=R.panelBorderRadius)!=null?Lo:I;if(e.style.cssText="",de.style.cssText="",ae.style.cssText="",ne.style.cssText="",ie.style.cssText="",Ze.style.cssText="",se){de.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"),de.style.cssText=`
|
|
20
|
+
`,F.addEventListener("click",()=>{p=w,x.forEach((re,Y)=>{let ae=Y<w;re.classList.toggle("selected",ae),re.setAttribute("aria-checked",Y===w-1?"true":"false")})}),x.push(F),E.appendChild(F)}f.appendChild(E);let k=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),w.appendChild(k),f.appendChild(w)}let q=document.createElement("div");q.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{t==null||t(),g.remove()});let N=document.createElement("button");return N.type="button",N.className="persona-feedback-btn persona-feedback-btn-submit",N.textContent=a,N.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let w=(k==null?void 0:k.value.trim())||void 0;await n(p,w),g.remove()}catch(w){N.disabled=!1,N.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),q.appendChild(M),q.appendChild(N),f.appendChild(q),g.appendChild(f),g}function is(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:g="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,C.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,C.appendChild(E),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 k=document.createElement("div");k.className="persona-feedback-labels";let q=document.createElement("span");q.className="persona-feedback-label-low",q.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=g,k.appendChild(q),k.appendChild(M);let N=document.createElement("div");N.className="persona-feedback-numbers";let w=[];for(let z=0;z<=10;z++){let ge=document.createElement("button");ge.type="button",ge.className="persona-feedback-rating-btn persona-feedback-number-btn",ge.setAttribute("role","radio"),ge.setAttribute("aria-checked","false"),ge.setAttribute("aria-label",`Rating ${z} out of 10`),ge.textContent=String(z),ge.dataset.rating=String(z),z<=6?ge.classList.add("persona-feedback-detractor"):z<=8?ge.classList.add("persona-feedback-passive"):ge.classList.add("persona-feedback-promoter"),ge.addEventListener("click",()=>{f=z,w.forEach((Ie,Xe)=>{Ie.classList.toggle("selected",Xe===z),Ie.setAttribute("aria-checked",Xe===z?"true":"false")})}),w.push(ge),N.appendChild(ge)}x.appendChild(k),x.appendChild(N),m.appendChild(x);let F=null;if(d){let z=document.createElement("div");z.className="persona-feedback-comment-container",F=document.createElement("textarea"),F.className="persona-feedback-comment",F.placeholder=o,F.rows=3,F.setAttribute("aria-label","Additional comments"),z.appendChild(F),m.appendChild(z)}let re=document.createElement("div");re.className="persona-feedback-actions";let Y=document.createElement("button");Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-skip",Y.textContent=i,Y.addEventListener("click",()=>{t==null||t(),p.remove()});let ae=document.createElement("button");return ae.type="button",ae.className="persona-feedback-btn persona-feedback-btn-submit",ae.textContent=a,ae.addEventListener("click",async()=>{if(f===null){N.classList.add("persona-feedback-shake"),setTimeout(()=>N.classList.remove("persona-feedback-shake"),500);return}ae.disabled=!0,ae.textContent="Submitting...";try{let z=(F==null?void 0:F.value.trim())||void 0;await n(f,z),p.remove()}catch(z){ae.disabled=!1,ae.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),re.appendChild(Y),re.appendChild(ae),m.appendChild(re),p.appendChild(m),p}var Ir="persona-chat-history",up=30*1e3,gp={"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 mp(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=gp[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function fp(e){var n,t,r,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function hp(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var Js=e=>!e||typeof e!="object"?{}:{...e},wc=e=>e.map(n=>({...n,streaming:!1})),Sc=(e,n,t)=>{let r=e!=null&&e.markdown?Zn(e.markdown):null,s=xr(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,g,p;let a=(c=o.text)!=null?c:"",i=(g=o.message.rawContent)!=null?g:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=br(a),s?s(d):d}},ls=(e,n,t)=>{var le,Se,ot,kt,wt,Bt,Lt,st,lt,At,ct,Ft,Yt,on,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Pa;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let r=es(n),s=lo.getForInstance(r.plugins);r.components&&In.registerAll(r.components);let o=bc(),a=(le=r.storageAdapter)!=null?le:ts(),i={},d=null,c=l=>{if(r.onStateLoaded)try{return r.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(u=>{let y=u!=null?u:{messages:[],metadata:{}};return c(y)});else{let u=l!=null?l:{messages:[],metadata:{}},y=c(u);y.metadata&&(i=Js(y.metadata)),(Se=y.messages)!=null&&Se.length&&(r={...r,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=c({messages:[],metadata:{}});(ot=l.messages)!=null&&ot.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>i,p=l=>{var y;i=(y=l({...i}))!=null?y:{},Dr()},f=r.actionParsers&&r.actionParsers.length?r.actionParsers:[co],m=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ar.message,ar.messageAndClick],C=po({parsers:f,handlers:m,getSessionMetadata:g,updateSessionMetadata:p,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let v=(wt=(kt=r.launcher)==null?void 0:kt.enabled)!=null?wt:!0,E=(Lt=(Bt=r.launcher)==null?void 0:Bt.autoExpand)!=null?Lt:!1,x=(st=r.autoFocusInput)!=null?st:!1,k=E,q=v,M=(At=(lt=r.layout)==null?void 0:lt.header)==null?void 0:At.layout,N=!1,w=v?E:!0,F=!1,re=null,Y=()=>{F=!0,re&&clearTimeout(re),re=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},ae=Sc(r,C,Y),z=(Ft=(ct=r.features)==null?void 0:ct.showReasoning)!=null?Ft:!0,ge=(on=(Yt=r.features)==null?void 0:Yt.showToolCalls)!=null?on:!0,Ie=(la=(ia=r.features)==null?void 0:ia.showEventStreamToggle)!=null?la:!1,ye=`${(da=typeof r.persistState=="object"?(ca=r.persistState)==null?void 0:ca.keyPrefix:void 0)!=null?da:"persona-"}event-stream`,ee=Ie?new so(ye):null,te=(ga=(ua=(pa=r.features)==null?void 0:pa.eventStream)==null?void 0:ua.maxEvents)!=null?ga:2e3,D=Ie?new oo(te,ee):null,U=null,oe=!1,he=null,ht=0;ee==null||ee.open().then(()=>D==null?void 0:D.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let at={onCopy:l=>{var u,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(S=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(y=(u=r.messageActions)==null?void 0:u.onCopy)==null||y.call(u,l)},onFeedback:l=>{var u,y;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(S=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(y=(u=r.messageActions)==null?void 0:u.onFeedback)==null||y.call(u,l)}},gt=(ma=r.statusIndicator)!=null?ma:{},Wt=l=>{var u,y,S,R;return l==="idle"?(u=gt.idleText)!=null?u:Vt.idle:l==="connecting"?(y=gt.connectingText)!=null?y:Vt.connecting:l==="connected"?(S=gt.connectedText)!=null?S:Vt.connected:l==="error"?(R=gt.errorText)!=null?R:Vt.error:Vt[l]},{wrapper:de,panel:ie}=tc(r),qe=nc(r,v),{container:j,body:G,messagesWrapper:be,suggestions:ze,textarea:X,sendButton:K,sendButtonWrapper:tt,composerForm:We,statusText:Ve,introTitle:Tt,introSubtitle:_t,closeButton:ce,iconHolder:Je,headerTitle:Me,headerSubtitle:nt,header:je,footer:Ze,actionsRow:Rt,leftActions:Ht,rightActions:Mt}=qe,B=qe.micButton,Z=qe.micButtonWrapper,J=qe.attachmentButton,_=qe.attachmentButtonWrapper,xe=qe.attachmentInput,Le=qe.attachmentPreviewsContainer,He=null,pt=null,ve=s.find(l=>l.renderHeader);if(ve!=null&&ve.renderHeader){let l=ve.renderHeader({config:r,defaultRenderer:()=>{let u=Pn({config:r,showClose:v});return or(j,u,r),u.header},onClose:()=>mt(!1,"user")});if(l){let u=j.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),je=l)}}let Ce=()=>{var u,y,S,R;if(!D)return;if(oe=!0,!U&&D&&(U=lc({buffer:D,getFullHistory:()=>D.getAllFromStore(),onClose:()=>Be(),config:r,plugins:s})),U&&(G.style.display="none",(u=Ze.parentNode)==null||u.insertBefore(U.element,Ze),U.update()),ue){ue.classList.remove("persona-text-persona-muted"),ue.classList.add("persona-text-persona-accent"),ue.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let L=(R=(S=(y=r.features)==null?void 0:y.eventStream)==null?void 0:S.classNames)==null?void 0:R.toggleButtonActive;L&&L.split(/\s+/).forEach(P=>P&&ue.classList.add(P))}let l=()=>{if(!oe)return;let L=Date.now();L-ht>=200&&(U==null||U.update(),ht=L),he=requestAnimationFrame(l)};ht=0,he=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},Be=()=>{var l,u,y;if(oe){if(oe=!1,U&&U.element.remove(),G.style.display="",ue){ue.classList.remove("persona-text-persona-accent"),ue.classList.add("persona-text-persona-muted"),ue.style.boxShadow="";let S=(y=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:y.toggleButtonActive;S&&S.split(/\s+/).forEach(R=>R&&ue.classList.remove(R))}he!==null&&(cancelAnimationFrame(he),he=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},ue=null;if(Ie){let l=(ha=(fa=r.features)==null?void 0:fa.eventStream)==null?void 0:ha.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ue=h("button",u),ue.style.width="28px",ue.style.height="28px",ue.type="button",ue.setAttribute("aria-label","Event Stream"),ue.title="Event Stream";let y=me("activity","18px","currentColor",1.5);y&&ue.appendChild(y);let S=qe.clearChatButtonWrapper,R=qe.closeButtonWrapper,L=S||R;L&&L.parentNode===je?je.insertBefore(ue,L):je.appendChild(ue),ue.addEventListener("click",()=>{oe?Be():Ce()})}let bt=l=>{var S,R,L;let u=r.attachments;if(!(u!=null&&u.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let 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=h("input");P.type="file",P.accept=((S=u.allowedTypes)!=null?S:Ln).join(","),P.multiple=((R=u.maxFiles)!=null?R:4)>1,P.style.display="none",P.setAttribute("aria-label",(L=u.buttonTooltipText)!=null?L:"Attach files"),l.appendChild(P)}},Zt=s.find(l=>l.renderComposer);if(Zt!=null&&Zt.renderComposer){let l=r.composer,u=Zt.renderComposer({config:r,defaultRenderer:()=>Er({config:r}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{xe==null||xe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y}},onVoiceToggle:((ya=r.voiceRecognition)==null?void 0:ya.enabled)===!0?()=>{pt==null||pt()}:void 0});u&&(Ze.replaceWith(u),Ze=u)}let un=l=>{let u=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),L=l.querySelector("[data-persona-composer-status]");u&&(We=u),y&&(X=y),S&&(K=S),R&&(B=R,Z=R.parentElement),L&&(Ve=L);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(ze=P);let V=l.querySelector(".persona-attachment-button");V&&(J=V,_=V.parentElement),xe=l.querySelector('input[type="file"]'),Le=l.querySelector(".persona-attachment-previews");let $=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");$&&(Rt=$)};bt(Ze),un(Ze);let gn=(ba=r.layout)==null?void 0:ba.contentMaxWidth;gn&&We&&(We.style.maxWidth=gn,We.style.marginLeft="auto",We.style.marginRight="auto"),(xa=r.attachments)!=null&&xa.enabled&&xe&&Le&&(He=rr.fromConfig(r.attachments),He.setPreviewsContainer(Le),xe.addEventListener("change",l=>{let u=l.target;He==null||He.handleFileSelect(u.files),u.value=""})),(()=>{var S,R;let l=(R=(S=r.layout)==null?void 0:S.slots)!=null?R:{},u=L=>{switch(L){case"body-top":return j.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return be;case"footer-top":return ze;case"composer":return We;case"footer-bottom":return Ve;default:return null}},y=(L,P)=>{var V;switch(L){case"header-left":case"header-center":case"header-right":if(L==="header-left")je.insertBefore(P,je.firstChild);else if(L==="header-right")je.appendChild(P);else{let $=je.querySelector(".persona-flex-col");$?(V=$.parentNode)==null||V.insertBefore(P,$.nextSibling):je.appendChild(P)}break;case"body-top":{let $=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");$?$.replaceWith(P):G.insertBefore(P,G.firstChild);break}case"body-bottom":G.appendChild(P);break;case"footer-top":ze.replaceWith(P);break;case"footer-bottom":Ve.replaceWith(P);break;default:break}};for(let[L,P]of Object.entries(l))if(P)try{let V=P({config:r,defaultContent:()=>u(L)});V&&y(L,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${L}":`,V)}})();let Rn=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let S=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!S)return;let R=S.getAttribute("data-message-id");if(!R)return;let L=y.getAttribute("data-bubble-type");L==="reasoning"?(Mr.has(R)?Mr.delete(R):Mr.add(R),sc(R,S)):L==="tool"&&(kr.has(R)?kr.delete(R):kr.add(R),ac(R,S,r))};be.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Rn(l))}),be.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Rn(l))});let lr=new Map;be.addEventListener("click",l=>{var P;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let S=y.closest("[data-actions-for]");if(!S)return;let R=S.getAttribute("data-actions-for");if(!R)return;let L=y.getAttribute("data-action");if(L==="copy"){let $=H.getMessages().find(se=>se.id===R);if($&&at.onCopy){let se=$.content||"";navigator.clipboard.writeText(se).then(()=>{y.classList.add("persona-message-action-success");let fe=me("check",14,"currentColor",2);fe&&(y.innerHTML="",y.appendChild(fe)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ke=me("copy",14,"currentColor",2);ke&&(y.innerHTML="",y.appendChild(ke))},2e3)}).catch(fe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",fe)}),at.onCopy($)}}else if(L==="upvote"||L==="downvote")if(((P=lr.get(R))!=null?P:null)===L)lr.delete(R),y.classList.remove("persona-message-action-active");else{let se=L==="upvote"?"downvote":"upvote",fe=S.querySelector(`[data-action="${se}"]`);fe&&fe.classList.remove("persona-message-action-active"),lr.set(R,L),y.classList.add("persona-message-action-active");let Ne=H.getMessages().find(Ae=>Ae.id===R);Ne&&at.onFeedback&&at.onFeedback({type:L,messageId:Ne.id,message:Ne})}}),be.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let S=y.closest(".vanilla-approval-bubble");if(!S)return;let R=S.getAttribute("data-message-id");if(!R)return;let L=y.getAttribute("data-approval-action");if(!L)return;let P=L==="approve"?"approved":"denied",$=H.getMessages().find(fe=>fe.id===R);if(!($!=null&&$.approval))return;let se=S.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(ke=>{ke.disabled=!0,ke.style.opacity="0.5",ke.style.cursor="not-allowed"}),H.resolveApproval($.approval,P)});let Qe=null,mn=null,Hn={artifacts:[],selectedId:null},ln=!1,Wr={current:null};be.addEventListener("click",l=>{var ke,Ne,Ae,I,Te;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let S=y.getAttribute("data-download-artifact");if(!S||((Ae=(Ne=(ke=r.features)==null?void 0:ke.artifacts)==null?void 0:Ne.onArtifactAction)==null?void 0:Ae.call(Ne,{type:"download",artifactId:S}))===!0)return;let L=H.getArtifactById(S),P=L==null?void 0:L.markdown,V=(L==null?void 0:L.title)||"artifact";if(!P){let Ee=y.closest("[data-open-artifact]"),ne=Ee==null?void 0:Ee.closest("[data-message-id]"),Pe=ne==null?void 0:ne.getAttribute("data-message-id");if(Pe){let Ke=H.getMessages().find(pe=>pe.id===Pe);if(Ke!=null&&Ke.rawContent)try{let pe=JSON.parse(Ke.rawContent);P=(I=pe==null?void 0:pe.props)==null?void 0:I.markdown,V=((Te=pe==null?void 0:pe.props)==null?void 0:Te.title)||V}catch{}}}if(!P)return;let $=new Blob([P],{type:"text/markdown"}),se=URL.createObjectURL($),fe=document.createElement("a");fe.href=se,fe.download=`${V}.md`,fe.click(),URL.revokeObjectURL(se)}),be.addEventListener("click",l=>{var L,P,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let S=y.getAttribute("data-open-artifact");!S||((V=(P=(L=r.features)==null?void 0:L.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:V.call(P,{type:"open",artifactId:S}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(S),hn())}),be.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let fn=null,dt=null,nn=null,wn=null,Rr=()=>{};function cr(){wn==null||wn(),wn=null}let Hr=()=>{var P;if(!fn||!dt)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){dt.style.removeProperty("position"),dt.style.removeProperty("left"),dt.style.removeProperty("top"),dt.style.removeProperty("bottom"),dt.style.removeProperty("width"),dt.style.removeProperty("z-index");return}let S=fn.firstElementChild;if(!S||S===dt)return;let R=10;dt.style.position="absolute",dt.style.top="0",dt.style.bottom="0",dt.style.width=`${R}px`,dt.style.zIndex="5";let L=S.offsetWidth-R/2;dt.style.left=`${Math.max(0,L)}px`},Dn=()=>{},hn=()=>{var y,S,R,L,P;if(!Qe||!an(r))return;Zo(e,r),Qo(e,r),Dn();let l=(L=(R=(S=(y=r.features)==null?void 0:y.artifacts)==null?void 0:S.layout)==null?void 0:R.narrowHostMaxWidth)!=null?L:520,u=ie.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Qe.update(Hn),ln?(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),(P=Qe.backdrop)==null||P.classList.add("persona-hidden")):Hn.artifacts.length>0&&(Qe.element.classList.remove("persona-hidden"),Qe.setMobileOpen(!0)),Rr()};if(an(r)){ie.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(j),Qe=pc(r,{onSelect:y=>{var S;return(S=Wr.current)==null?void 0:S.selectArtifact(y)},onDismiss:()=>{ln=!0,hn()}}),Qe.element.classList.add("persona-hidden"),fn=u,u.appendChild(l),u.appendChild(Qe.element),Qe.backdrop&&ie.appendChild(Qe.backdrop),ie.appendChild(u),Rr=()=>{var S,R,L,P;if(!fn||!Qe)return;if(!(((L=(R=(S=r.features)==null?void 0:S.artifacts)==null?void 0:R.layout)==null?void 0:L.resizable)===!0)){nn==null||nn(),nn=null,cr(),dt&&(dt.remove(),dt=null),Qe.element.style.removeProperty("width"),Qe.element.style.removeProperty("maxWidth");return}if(!dt){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let $=e.ownerDocument,se=(P=$.defaultView)!=null?P:window,fe=ke=>{var ne,Pe;if(!Qe||ke.button!==0||e.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;ke.preventDefault(),cr();let Ne=ke.clientX,Ae=Qe.element.getBoundingClientRect().width,I=(Pe=(ne=r.features)==null?void 0:ne.artifacts)==null?void 0:Pe.layout,Te=rt=>{let Ke=fn.getBoundingClientRect().width,pe=e.classList.contains("persona-artifact-appearance-seamless"),Pt=pe?0:fc(fn,se),it=pe?0:V.getBoundingClientRect().width||6,Gt=Ae-(rt.clientX-Ne),jt=hc(Gt,Ke,Pt,it,I==null?void 0:I.resizableMinWidth,I==null?void 0:I.resizableMaxWidth);Qe.element.style.width=`${jt}px`,Qe.element.style.maxWidth="none",Hr()},Ee=()=>{$.removeEventListener("pointermove",Te),$.removeEventListener("pointerup",Ee),$.removeEventListener("pointercancel",Ee),wn=null;try{V.releasePointerCapture(ke.pointerId)}catch{}};wn=Ee,$.addEventListener("pointermove",Te),$.addEventListener("pointerup",Ee),$.addEventListener("pointercancel",Ee);try{V.setPointerCapture(ke.pointerId)}catch{}};V.addEventListener("pointerdown",fe),dt=V,fn.insertBefore(V,Qe.element),nn=()=>{V.removeEventListener("pointerdown",fe)}}if(dt){let V=Hn.artifacts.length>0&&!ln;dt.classList.toggle("persona-hidden",!V),Hr()}},Dn=()=>{var se,fe,ke,Ne,Ae,I,Te,Ee,ne,Pe,rt,Ke,pe,Pt;if(!v||!Qe||((fe=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?fe:!1))return;let S=(ke=e.ownerDocument.defaultView)!=null?ke:window,R=(Ae=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ae:!0,L=(Te=(I=r.launcher)==null?void 0:I.mobileBreakpoint)!=null?Te:640;if(R&&S.innerWidth<=L||!mc(r,v))return;let P=(Pe=(ne=(Ee=r.launcher)==null?void 0:Ee.width)!=null?ne:r.launcherWidth)!=null?Pe:"min(400px, calc(100vw - 24px))",V=(Pt=(pe=(Ke=(rt=r.features)==null?void 0:rt.artifacts)==null?void 0:Ke.layout)==null?void 0:pe.expandedPanelWidth)!=null?Pt:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!ln?(ie.style.width=V,ie.style.maxWidth=V):(ie.style.width=P,ie.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(mn=new ResizeObserver(()=>{hn()}),mn.observe(ie))}else ie.appendChild(j);e.appendChild(de);let _n=()=>{var Ke,pe,Pt,it,Gt,jt,zt,$t,sn,_e,yt,To,Mo,ko,Lo,Po,ys,bs,Et,Io,zr;let l=Ut(r),u=(pe=(Ke=r.launcher)==null?void 0:Ke.sidebarMode)!=null?pe:!1,y=l||u||((it=(Pt=r.launcher)==null?void 0:Pt.fullHeight)!=null?it:!1),S=((Gt=r.launcher)==null?void 0:Gt.enabled)===!1,R=(jt=r.theme)!=null?jt:{},L=(zt=e.ownerDocument.defaultView)!=null?zt:window,P=(sn=($t=r.launcher)==null?void 0:$t.mobileFullscreen)!=null?sn:!0,V=(yt=(_e=r.launcher)==null?void 0:_e.mobileBreakpoint)!=null?yt:640,$=L.innerWidth<=V,se=P&&$&&v,fe=(Mo=(To=r.launcher)==null?void 0:To.position)!=null?Mo:"bottom-left",ke=fe==="bottom-left"||fe==="top-left",Ne=u||se?"none":"1px solid var(--persona-persona-border)",Ae=se?"none":u?ke?"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))",I=u||se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Te=(ko=R.panelBorder)!=null?ko:Ne,Ee=(Lo=R.panelShadow)!=null?Lo:Ae,ne=(Po=R.panelBorderRadius)!=null?Po:I;if(e.style.cssText="",de.style.cssText="",ie.style.cssText="",j.style.cssText="",G.style.cssText="",Ze.style.cssText="",se){de.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"),de.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
inset: 0 !important;
|
|
23
23
|
width: 100% !important;
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
display: flex !important;
|
|
29
29
|
flex-direction: column !important;
|
|
30
30
|
z-index: inherit !important;
|
|
31
|
-
`,
|
|
31
|
+
`,ie.style.cssText=`
|
|
32
32
|
position: relative !important;
|
|
33
33
|
display: flex !important;
|
|
34
34
|
flex-direction: column !important;
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
padding: 0 !important;
|
|
42
42
|
box-shadow: none !important;
|
|
43
43
|
border-radius: 0 !important;
|
|
44
|
-
`,
|
|
44
|
+
`,j.style.cssText=`
|
|
45
45
|
display: flex !important;
|
|
46
46
|
flex-direction: column !important;
|
|
47
47
|
flex: 1 1 0% !important;
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
overflow: hidden !important;
|
|
53
53
|
border-radius: 0 !important;
|
|
54
54
|
border: none !important;
|
|
55
|
-
`,
|
|
55
|
+
`,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",Ze.style.flexShrink="0",N=!0;return}let Pe=(bs=(ys=r==null?void 0:r.launcher)==null?void 0:ys.width)!=null?bs:r==null?void 0:r.launcherWidth,rt=Pe!=null?Pe:"min(400px, calc(100vw - 24px))";if(!u&&!l?S&&y?(ie.style.width="100%",ie.style.maxWidth="100%"):(ie.style.width=rt,ie.style.maxWidth=rt):l&&(ie.style.width="100%",ie.style.maxWidth="100%"),Dn(),ie.style.boxShadow=Ee,ie.style.borderRadius=ne,j.style.border=Te,j.style.borderRadius=ne,y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",S&&(e.style.width="100%"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",S&&(de.style.overflow="hidden"),ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.height="100%",ie.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",Ze.style.flexShrink="0"),de.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"),!u&&!S&&!l&&((Et=pn[fe])!=null?Et:pn["bottom-right"]).split(" ").forEach(Yn=>de.classList.add(Yn)),u){let Kn=(zr=(Io=r.launcher)==null?void 0:Io.sidebarWidth)!=null?zr:"420px";de.style.cssText=`
|
|
56
56
|
position: fixed !important;
|
|
57
57
|
top: 0 !important;
|
|
58
58
|
bottom: 0 !important;
|
|
@@ -63,8 +63,8 @@
|
|
|
63
63
|
padding: 0 !important;
|
|
64
64
|
display: flex !important;
|
|
65
65
|
flex-direction: column !important;
|
|
66
|
-
${
|
|
67
|
-
`,
|
|
66
|
+
${ke?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
67
|
+
`,ie.style.cssText=`
|
|
68
68
|
position: relative !important;
|
|
69
69
|
display: flex !important;
|
|
70
70
|
flex-direction: column !important;
|
|
@@ -76,8 +76,8 @@
|
|
|
76
76
|
margin: 0 !important;
|
|
77
77
|
padding: 0 !important;
|
|
78
78
|
box-shadow: ${Ee} !important;
|
|
79
|
-
border-radius: ${
|
|
80
|
-
`,
|
|
79
|
+
border-radius: ${ne} !important;
|
|
80
|
+
`,ie.style.setProperty("width","100%","important"),ie.style.setProperty("max-width","100%","important"),j.style.cssText=`
|
|
81
81
|
display: flex !important;
|
|
82
82
|
flex-direction: column !important;
|
|
83
83
|
flex: 1 1 0% !important;
|
|
@@ -86,29 +86,29 @@
|
|
|
86
86
|
min-height: 0 !important;
|
|
87
87
|
max-height: 100% !important;
|
|
88
88
|
overflow: hidden !important;
|
|
89
|
-
border-radius: ${
|
|
90
|
-
border: ${
|
|
89
|
+
border-radius: ${ne} !important;
|
|
90
|
+
border: ${Te} !important;
|
|
91
91
|
`,Ze.style.cssText=`
|
|
92
92
|
flex-shrink: 0 !important;
|
|
93
93
|
border-top: none !important;
|
|
94
94
|
padding: 8px 16px 12px 16px !important;
|
|
95
|
-
`}if(!S&&!l){let Kn="max-height: -moz-available !important; max-height: stretch !important;",Yn=u?"":"padding-top: 1.25em !important;";de.style.cssText+=Kn+Yn}};_n(),On(e,r),Go(e,r),Zo(e,r);let xt=[];mn&&xt.push(()=>{mn==null||mn.disconnect(),mn=null}),xt.push(()=>{nn==null||nn(),nn=null,cr(),dt&&(dt.remove(),dt=null),Qe==null||Qe.element.style.removeProperty("width"),Qe==null||Qe.element.style.removeProperty("maxWidth")}),We&&xt.push(()=>{be!==null&&(cancelAnimationFrame(be),be=null),D==null||D.destroy(),D=null,_==null||_.destroy(),_=null,ee=null});let yn=null,Hr=()=>{yn&&(yn(),yn=null),r.colorScheme==="auto"&&(yn=Yo(()=>{On(e,r)}))};Hr(),xt.push(()=>{yn&&(yn(),yn=null)});let Bn=rc(Xe),bn=null,H,Fn=!1,$n=Jl(),Br=0,Sn=!0,jn=0,Fr=0,An=null,En=!1,dr=0,pr=!1,go=125,mo=2e3,fo=5,$r=50,ur=new Map,qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Nr=(xa=(ba=r.voiceRecognition)==null?void 0:ba.autoResume)!=null?xa:!1,rn=l=>{o.emit("voice:state",{active:qe.active,source:l,timestamp:Date.now()})},Kt=()=>{p(l=>({...l,voiceState:{active:qe.active,timestamp:Date.now(),manuallyDeactivated:qe.manuallyDeactivated}}))},ho=()=>{var S,R;if(((S=r.voiceRecognition)==null?void 0:S.enabled)===!1)return;let l=qs(i.voiceState),u=!!l.active,h=Number((R=l.timestamp)!=null?R:0);qe.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<ap&&setTimeout(()=>{var L,P;qe.active||(qe.manuallyDeactivated=!1,((P=(L=r.voiceRecognition)==null?void 0:L.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{qe.active=H.isVoiceActive(),rn("restore"),H.isVoiceActive()&&Nn()}):qn("restore"))},1e3)},yo=()=>H?bc(H.getMessages()).filter(l=>!l.__skipPersist):[];function Or(l){if(!(a!=null&&a.save))return;let h={messages:l?bc(l):H?yo():[],metadata:i};try{let S=a.save(h);S instanceof Promise&&S.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let Vn=(l=!1)=>{if(!Sn)return;let u=Date.now();En&&u<dr&&!l||(En&&u>=dr&&(En=!1),!(!l&&!Fn)&&(u-Fr<go||(Fr=u,An&&cancelAnimationFrame(An),An=requestAnimationFrame(()=>{En||!Sn||(pr=!0,ie.scrollTop=ie.scrollHeight,jn=ie.scrollTop,requestAnimationFrame(()=>{pr=!1}),An=null)}))))},Tn=null,bo=()=>de.querySelector("#persona-scroll-container")||ie,xo=(l,u=500)=>{let h=l.scrollTop,S=l.clientHeight,R=l.scrollHeight,L=R-h;if(h+S>=R-2||Math.abs(L)<5)return;Tn!==null&&(cancelAnimationFrame(Tn),Tn=null);let V=performance.now(),$=he=>1-Math.pow(1-he,3),se=he=>{let Le=l.scrollHeight;Le!==R&&(R=Le,L=R-h);let Oe=he-V,Ae=Math.min(Oe/u,1),I=$(Ae),Me=h+L*I;l.scrollTop=Me,Ae<1?Tn=requestAnimationFrame(se):(l.scrollTop=l.scrollHeight,Tn=null)};Tn=requestAnimationFrame(se)},vo=l=>{let u=new Map;l.forEach(h=>{let S=ur.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!S&&h.role==="assistant"&&o.emit("assistant:message",h),h.role==="assistant"&&(S!=null&&S.streaming)&&h.streaming===!1&&o.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(S?h.approval.status!=="pending"&&o.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):o.emit("approval:requested",{approval:h.approval,message:h}))}),ur.clear(),u.forEach((h,S)=>{ur.set(S,h)})},Un=(l,u,h)=>{var he,Le,Oe,Ae;let S=document.createElement("div"),L=(()=>{var Me;let I=s.find(Ee=>Ee.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((Me=r.loadingIndicator)!=null&&Me.render)return r.loadingIndicator.render})(),P=new Set;u.forEach(I=>{var pe,Lt;P.add(I.id);let Me=zl(I,Br),Ee=Kl($n,I.id,Me);if(Ee){S.appendChild(Ee.cloneNode(!0));return}let re=null,Ie=s.find(at=>!!(I.variant==="reasoning"&&at.renderReasoning||I.variant==="tool"&&at.renderToolCall||I.variant==="approval"&&at.renderApproval||!I.variant&&at.renderMessage)),rt=(pe=r.layout)==null?void 0:pe.messages;if(Ie)if(I.variant==="reasoning"&&I.reasoning&&Ie.renderReasoning){if(!J)return;re=Ie.renderReasoning({message:I,defaultRenderer:()=>Bs(I),config:r})}else if(I.variant==="tool"&&I.toolCall&&Ie.renderToolCall){if(!me)return;re=Ie.renderToolCall({message:I,defaultRenderer:()=>Fs(I,r),config:r})}else if(I.variant==="approval"&&I.approval&&Ie.renderApproval){if(r.approval===!1)return;re=Ie.renderApproval({message:I,defaultRenderer:()=>$s(I,r),config:r})}else Ie.renderMessage&&(re=Ie.renderMessage({message:I,defaultRenderer:()=>{let at=Er(I,h,rt,r.messageActions,ct,{loadingIndicatorRenderer:L,widgetConfig:r});return I.role!=="user"&&Ds(at,I,r,H),at},config:r}));if(!re&&I.role==="assistant"&&!I.variant&&r.enableComponentStreaming!==!1&&rs(I)){let Xt=os(I);if(Xt){let _t=ns(Xt,{config:r,message:I,transform:h});if(_t)if(r.wrapComponentDirectiveInBubble!==!1){let Ft=document.createElement("div");if(Ft.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(" "),Ft.id=`bubble-${I.id}`,Ft.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let sn=document.createElement("div");sn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",sn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Ft.appendChild(sn)}Ft.appendChild(_t),re=Ft}else{let Ft=document.createElement("div");if(Ft.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ft.id=`bubble-${I.id}`,Ft.setAttribute("data-message-id",I.id),Ft.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let sn=document.createElement("div");sn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",sn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Ft.appendChild(sn)}Ft.appendChild(_t),re=Ft}}}if(!re)if(I.variant==="reasoning"&&I.reasoning){if(!J)return;re=Bs(I)}else if(I.variant==="tool"&&I.toolCall){if(!me)return;re=Fs(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;re=$s(I,r)}else{let at=(Lt=r.layout)==null?void 0:Lt.messages;at!=null&&at.renderUserMessage&&I.role==="user"?re=at.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):at!=null&&at.renderAssistantMessage&&I.role==="assistant"?re=at.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):re=Er(I,h,at,r.messageActions,ct,{loadingIndicatorRenderer:L,widgetConfig:r}),I.role!=="user"&&re&&Ds(re,I,r,H)}let Je=document.createElement("div");Je.className="persona-flex",Je.id=`wrapper-${I.id}`,Je.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Je.classList.add("persona-justify-end"),(re==null?void 0:re.getAttribute("data-persona-component-directive"))==="true"&&Je.classList.add("persona-w-full"),Je.appendChild(re),Yl($n,I.id,Me,Je),S.appendChild(Je)}),Xl($n,P);let V=u.some(I=>I.role==="assistant"&&I.streaming),$=u[u.length-1],se=($==null?void 0:$.role)==="assistant"&&!$.streaming&&$.variant!=="approval";if(Fn&&u.some(I=>I.role==="user")&&!V&&!se){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:sr},Me=s.find(re=>re.renderLoadingIndicator),Ee=null;if(Me!=null&&Me.renderLoadingIndicator&&(Ee=Me.renderLoadingIndicator(I)),Ee===null&&((he=r.loadingIndicator)!=null&&he.render)&&(Ee=r.loadingIndicator.render(I)),Ee===null&&(Ee=sr()),Ee){let re=document.createElement("div"),Ie=((Le=r.loadingIndicator)==null?void 0:Le.showBubble)!==!1;re.className=Ie?["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(" "),re.setAttribute("data-typing-indicator","true"),re.appendChild(Ee);let rt=document.createElement("div");rt.className="persona-flex",rt.id="wrapper-typing-indicator",rt.setAttribute("data-wrapper-id","typing-indicator"),rt.appendChild(re),S.appendChild(rt)}}if(!Fn&&u.length>0){let I=u[u.length-1],Me={config:r,lastMessage:I,messageCount:u.length},Ee=s.find(Ie=>Ie.renderIdleIndicator),re=null;if(Ee!=null&&Ee.renderIdleIndicator&&(re=Ee.renderIdleIndicator(Me)),re===null&&((Oe=r.loadingIndicator)!=null&&Oe.renderIdle)&&(re=r.loadingIndicator.renderIdle(Me)),re){let Ie=document.createElement("div"),rt=((Ae=r.loadingIndicator)==null?void 0:Ae.showBubble)!==!1;Ie.className=rt?["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(" "),Ie.setAttribute("data-idle-indicator","true"),Ie.appendChild(re);let Je=document.createElement("div");Je.className="persona-flex",Je.id="wrapper-idle-indicator",Je.setAttribute("data-wrapper-id","idle-indicator"),Je.appendChild(Ie),S.appendChild(Je)}}ql(l,S),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=bo();xo(I)})})},gr=()=>{if(!v)return;let l=Vt(r);w?(de.style.display=l?"flex":"",de.classList.remove("persona-pointer-events-none","persona-opacity-0"),ae.classList.remove("persona-scale-95","persona-opacity-0"),ae.classList.add("persona-scale-100","persona-opacity-100"),we?we.element.style.display="none":Ne&&(Ne.style.display="none")):(l?(de.style.display="none",de.classList.remove("persona-pointer-events-none","persona-opacity-0"),ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(de.style.display="",de.classList.add("persona-pointer-events-none","persona-opacity-0"),ae.classList.remove("persona-scale-100","persona-opacity-100"),ae.classList.add("persona-scale-95","persona-opacity-0")),we?we.element.style.display="":Ne&&(Ne.style.display=""))},ft=(l,u="user")=>{if(!v||w===l)return;let h=w;w=l,gr(),w&&(vt(),Vn(!0));let S={open:w,source:u,timestamp:Date.now()};w&&!h?o.emit("widget:opened",S):!w&&h&&o.emit("widget:closed",S),o.emit("widget:state",{open:w,launcherEnabled:v,voiceActive:qe.active,streaming:H.isStreaming()})},mr=l=>{X.disabled=l,B&&(B.disabled=l),Bn.buttons.forEach(u=>{u.disabled=l}),Ze.dataset.personaComposerStreaming=l?"true":"false",Ze.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},fr=()=>{qe.active||te&&te.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>fr(),200)});let Dr=()=>{var R,L,P,V,$,se,he,Le,Oe,Ae,I,Me,Ee,re;Ut.textContent=(L=(R=r.copy)==null?void 0:R.welcomeTitle)!=null?L:"Hello \u{1F44B}",Dt.textContent=(V=(P=r.copy)==null?void 0:P.welcomeSubtitle)!=null?V:"Ask anything about your account or products.",te.placeholder=(se=($=r.copy)==null?void 0:$.inputPlaceholder)!=null?se:"How can I help...",(Le=(he=r.sendButton)==null?void 0:he.useIcon)!=null&&Le||(X.textContent=(Ae=(Oe=r.copy)==null?void 0:Oe.sendButtonLabel)!=null?Ae:"Send");let u=(Me=(I=r.theme)==null?void 0:I.inputFontFamily)!=null?Me:"sans-serif",h=(re=(Ee=r.theme)==null?void 0:Ee.inputFontWeight)!=null?re:"400",S=Ie=>{switch(Ie){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};te.style.fontFamily=S(u),te.style.fontWeight=h};if(r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(u=>({...u,sessionId:l}))}}),H=new vr(r,{onMessagesChanged(l){Un(Te,l,oe),H&&(l.some(R=>R.role==="user")?Bn.render([],H,te,l):Bn.render(r.suggestionChips,H,te,l,r.suggestionChipsConfig)),Vn(!Fn),vo(l);let u=[...l].reverse().find(S=>S.role==="user"),h=qe.lastUserMessageId;u&&u.id!==h&&(qe.lastUserMessageId=u.id,o.emit("user:message",u)),qe.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Or(l)},onStatusChanged(l){var S;let u=(S=r.statusIndicator)!=null?S:{},h=R=>{var L,P,V,$;return R==="idle"?(L=u.idleText)!=null?L:jt.idle:R==="connecting"?(P=u.connectingText)!=null?P:jt.connecting:R==="connected"?(V=u.connectedText)!=null?V:jt.connected:R==="error"?($=u.errorText)!=null?$:jt.error:jt[R]};tt.textContent=h(l)},onStreamingChanged(l){Fn=l,mr(l),H&&Un(Te,H.getMessages(),oe),l||Vn(!0)},onVoiceStatusChanged(l){var u,h;if(((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":break;case"processing":dn(),wo();break;case"speaking":dn(),So();break;default:l==="idle"&&H.isBargeInActive()?(dn(),Nn(),B==null||B.setAttribute("aria-label","End voice session")):(qe.active=!1,dn(),rn("system"),Kt());break}},onArtifactsState(l){Hn=l,hn()}}),Ir.current=H,((Ca=(va=r.voiceRecognition)==null?void 0:va.provider)==null?void 0:Ca.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&H.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),_&&H.setSSEEventCallback((l,u)=>{_==null||_.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(i=qs(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let _r=l=>{var R;l.preventDefault();let u=te.value.trim(),h=(R=Be==null?void 0:Be.hasAttachments())!=null?R:!1;if(!u&&!h)return;let S;h&&(S=[],S.push(...Be.getContentParts()),u&&S.push(Do(u))),te.value="",te.style.height="auto",H.sendMessage(u,{contentParts:S}),h&&Be.clearAttachments()},jr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},Vr=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!Be)return;let u=lp(l.clipboardData);u.length!==0&&(l.preventDefault(),await Be.handleFiles(u))},qt=null,Qt=!1,Mn=null,Re=null,Ur=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qn=(l="user")=>{var L,P,V,$,se,he,Le,Oe;if(Qt||H.isStreaming())return;let u=Ur();if(!u)return;qt=new u;let S=(P=((L=r.voiceRecognition)!=null?L:{}).pauseDuration)!=null?P:2e3;qt.continuous=!0,qt.interimResults=!0,qt.lang="en-US";let R=te.value;qt.onresult=Ae=>{let I="",Me="";for(let re=0;re<Ae.results.length;re++){let Ie=Ae.results[re],rt=Ie[0].transcript;Ie.isFinal?I+=rt+" ":Me=rt}let Ee=R+I+Me;te.value=Ee,Mn&&clearTimeout(Mn),(I||Me)&&(Mn=window.setTimeout(()=>{let re=te.value.trim();re&&qt&&Qt&&(cn(),te.value="",te.style.height="auto",H.sendMessage(re,{viaVoice:!0}))},S))},qt.onerror=Ae=>{Ae.error!=="no-speech"&&cn()},qt.onend=()=>{if(Qt){let Ae=te.value.trim();Ae&&Ae!==R.trim()&&(te.value="",te.style.height="auto",H.sendMessage(Ae,{viaVoice:!0})),cn()}};try{if(qt.start(),Qt=!0,qe.active=!0,l!=="system"&&(qe.manuallyDeactivated=!1),rn(l),Kt(),B){let Ae=(V=r.voiceRecognition)!=null?V:{};Re={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:($=Ae.iconName)!=null?$:"mic",iconSize:parseFloat((Le=(he=Ae.iconSize)!=null?he:(se=r.sendButton)==null?void 0:se.size)!=null?Le:"40")||24};let I=(Oe=Ae.recordingBackgroundColor)!=null?Oe:"#ef4444",Me=Ae.recordingIconColor,Ee=Ae.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=I,Me){B.style.color=Me;let re=B.querySelector("svg");re&&re.setAttribute("stroke",Me)}Ee&&(B.style.borderColor=Ee),B.setAttribute("aria-label","Stop voice recognition")}}catch{cn("system")}},cn=(l="user")=>{if(Qt){if(Qt=!1,Mn&&(clearTimeout(Mn),Mn=null),qt){try{qt.stop()}catch{}qt=null}if(qe.active=!1,rn(l),Kt(),B){if(B.classList.remove("persona-voice-recording"),Re){B.style.backgroundColor=Re.backgroundColor,B.style.color=Re.color,B.style.borderColor=Re.borderColor;let u=B.querySelector("svg");u&&u.setAttribute("stroke",Re.color||"currentColor"),Re=null}B.setAttribute("aria-label","Start voice recognition")}}},Co=(l,u)=>{var re,Ie,rt,Je,pe,Lt,at,Xt;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((re=l==null?void 0:l.provider)==null?void 0:re.type)==="runtype";if(!(h||S))return null;let L=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 V=(Ie=l==null?void 0:l.iconName)!=null?Ie:"mic",$=(rt=u==null?void 0:u.size)!=null?rt:"40px",se=(Je=l==null?void 0:l.iconSize)!=null?Je:$,he=parseFloat(se)||24,Le=(pe=l==null?void 0:l.backgroundColor)!=null?pe:u==null?void 0:u.backgroundColor,Oe=(Lt=l==null?void 0:l.iconColor)!=null?Lt:u==null?void 0:u.textColor;P.style.width=se,P.style.height=se,P.style.minWidth=se,P.style.minHeight=se,P.style.fontSize="18px",P.style.lineHeight="1";let Ae=Oe||"currentColor",I=fe(V,he,Ae,1.5);I?(P.appendChild(I),P.style.color=Ae):(P.textContent="\u{1F3A4}",P.style.color=Ae),Le?P.style.backgroundColor=Le:P.classList.add("persona-bg-persona-primary"),Oe?P.style.color=Oe:!Oe&&!(u!=null&&u.textColor)&&P.classList.add("persona-text-white"),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),L.appendChild(P);let Me=(at=l==null?void 0:l.tooltipText)!=null?at:"Start voice recognition";if(((Xt=l==null?void 0:l.showTooltip)!=null?Xt:!1)&&Me){let _t=f("div","persona-send-button-tooltip");_t.textContent=Me,L.appendChild(_t)}return{micButton:P,micButtonWrapper:L}},hr=()=>{var u,h,S,R,L;if(!B||Re)return;let l=(u=r.voiceRecognition)!=null?u:{};Re={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((L=(R=l.iconSize)!=null?R:(S=r.sendButton)==null?void 0:S.size)!=null?L:"40")||24}},yr=(l,u)=>{var L,P,V,$,se;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let S=(se=Re==null?void 0:Re.iconSize)!=null?se:parseFloat(($=(V=(L=r.voiceRecognition)==null?void 0:L.iconSize)!=null?V:(P=r.sendButton)==null?void 0:P.size)!=null?$:"40")||24,R=fe(l,S,u,1.5);R&&B.appendChild(R)},zn=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Nn=()=>{var R,L;if(!B)return;hr();let l=(R=r.voiceRecognition)!=null?R:{},u=(L=l.recordingBackgroundColor)!=null?L:"#ef4444",h=l.recordingIconColor,S=l.recordingBorderColor;if(zn(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=u,h){B.style.color=h;let P=B.querySelector("svg");P&&P.setAttribute("stroke",h)}S&&(B.style.borderColor=S),B.setAttribute("aria-label","Stop voice recognition")},wo=()=>{var V,$,se,he,Le,Oe,Ae,I;if(!B)return;hr();let l=(V=r.voiceRecognition)!=null?V:{},u=H.getVoiceInterruptionMode(),h=($=l.processingIconName)!=null?$:"loader",S=(he=(se=l.processingIconColor)!=null?se:Re==null?void 0:Re.color)!=null?he:"",R=(Oe=(Le=l.processingBackgroundColor)!=null?Le:Re==null?void 0:Re.backgroundColor)!=null?Oe:"",L=(I=(Ae=l.processingBorderColor)!=null?Ae:Re==null?void 0:Re.borderColor)!=null?I:"";zn(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=R,B.style.borderColor=L;let P=S||"currentColor";B.style.color=P,yr(h,P),B.setAttribute("aria-label","Processing voice input"),u==="none"&&(B.style.cursor="default")},So=()=>{var se,he,Le,Oe,Ae,I,Me,Ee,re,Ie,rt,Je;if(!B)return;hr();let l=(se=r.voiceRecognition)!=null?se:{},u=H.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",S=(he=l.speakingIconName)!=null?he:h,R=(I=l.speakingIconColor)!=null?I:u==="barge-in"?(Oe=(Le=l.recordingIconColor)!=null?Le:Re==null?void 0:Re.color)!=null?Oe:"":(Ae=Re==null?void 0:Re.color)!=null?Ae:"",L=(re=l.speakingBackgroundColor)!=null?re:u==="barge-in"?(Me=l.recordingBackgroundColor)!=null?Me:"#ef4444":(Ee=Re==null?void 0:Re.backgroundColor)!=null?Ee:"",P=(Je=l.speakingBorderColor)!=null?Je:u==="barge-in"?(Ie=l.recordingBorderColor)!=null?Ie:"":(rt=Re==null?void 0:Re.borderColor)!=null?rt:"";zn(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=L,B.style.borderColor=P;let V=R||"currentColor";B.style.color=V,yr(S,V);let $=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",$),u==="none"&&(B.style.cursor="default"),u==="barge-in"&&B.classList.add("persona-voice-recording")},dn=()=>{var l,u,h;B&&(zn(),Re&&(B.style.backgroundColor=(l=Re.backgroundColor)!=null?l:"",B.style.color=(u=Re.color)!=null?u:"",B.style.borderColor=(h=Re.borderColor)!=null?h:"",yr(Re.iconName,Re.color||"currentColor"),Re=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Jn=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=H.getVoiceStatus(),S=H.getVoiceInterruptionMode();if(S==="none"&&(h==="processing"||h==="speaking"))return;if(S==="cancel"&&(h==="processing"||h==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,Kt(),rn("user"),dn()});return}H.toggleVoice().then(()=>{qe.active=H.isVoiceActive(),qe.manuallyDeactivated=!H.isVoiceActive(),Kt(),rn("user"),H.isVoiceActive()?Nn():dn()});return}if(Qt){let h=te.value.trim();qe.manuallyDeactivated=!0,Kt(),cn("user"),h&&(te.value="",te.style.height="auto",H.sendMessage(h))}else qe.manuallyDeactivated=!1,Kt(),qn("user")};pt=Jn,B&&(B.addEventListener("click",Jn),xt.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),dn()):cn("system"),B&&B.removeEventListener("click",Jn)}));let Ao=o.on("assistant:complete",()=>{Nr&&(qe.active||qe.manuallyDeactivated||Nr==="assistant"&&!qe.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!qe.active&&!qe.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?H.toggleVoice().then(()=>{qe.active=H.isVoiceActive(),rn("auto"),H.isVoiceActive()&&Nn()}):qn("auto"))},600))});xt.push(Ao);let Z=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});xt.push(Z);let $e=()=>{ft(!w,"user")},we=null,Ne=null;if(v){let l=s.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:r,defaultRenderer:()=>no(r,$e).element,onToggle:$e});u&&(Ne=u)}Ne||(we=no(r,$e))}we?e.appendChild(we.element):Ne&&e.appendChild(Ne),gr(),Bn.render(r.suggestionChips,H,te,void 0,r.suggestionChipsConfig),Dr(),mr(H.isStreaming()),Vn(!0),ho(),x&&(v?w&&setTimeout(()=>fr(),200):setTimeout(()=>fr(),0));let vt=()=>{var $,se,he,Le,Oe,Ae,I,Me,Ee,re,Ie,rt,Je;let l=Vt(r),u=(se=($=r.launcher)==null?void 0:$.sidebarMode)!=null?se:!1,h=l||u||((Le=(he=r.launcher)==null?void 0:he.fullHeight)!=null?Le:!1),S=(Oe=e.ownerDocument.defaultView)!=null?Oe:window,R=(I=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?I:!0,L=(Ee=(Me=r.launcher)==null?void 0:Me.mobileBreakpoint)!=null?Ee:640,P=S.innerWidth<=L;if(R&&P&&v){_n(),On(e,r);return}if(N&&(N=!1,_n(),On(e,r)),!v&&!l){ae.style.height="",ae.style.width="";return}if(!u&&!l){let pe=(Ie=(re=r==null?void 0:r.launcher)==null?void 0:re.width)!=null?Ie:r==null?void 0:r.launcherWidth,Lt=pe!=null?pe:"min(400px, calc(100vw - 24px))";ae.style.width=Lt,ae.style.maxWidth=Lt}if(Dn(),!h){let pe=S.innerHeight,Lt=64,at=(Je=(rt=r.launcher)==null?void 0:rt.heightOffset)!=null?Je:0,Xt=Math.max(200,pe-Lt),_t=Math.min(640,Xt),zt=Math.max(200,_t-at);ae.style.height=`${zt}px`}};vt();let Nt=(wa=e.ownerDocument.defaultView)!=null?wa:window;Nt.addEventListener("resize",vt),xt.push(()=>Nt.removeEventListener("resize",vt)),jn=ie.scrollTop;let Ct=()=>{let l=ie.scrollTop,u=ie.scrollHeight,h=ie.clientHeight,S=u-l-h,R=Math.abs(l-jn);if(jn=l,!pr&&!(R<=fo)){if(!Sn&&S<$r){En=!1,Sn=!0;return}Sn&&S>$r&&(En=!0,dr=Date.now()+mo,Sn=!1)}};ie.addEventListener("scroll",Ct,{passive:!0}),xt.push(()=>ie.removeEventListener("scroll",Ct)),xt.push(()=>{An&&cancelAnimationFrame(An)});let b=()=>{ce&&(bn&&(ce.removeEventListener("click",bn),bn=null),v?(ce.style.display="",bn=()=>{ft(!1,"user")},ce.addEventListener("click",bn)):ce.style.display="none")};b(),(()=>{let{clearChatButton:l}=U;l&&l.addEventListener("click",()=>{H.clearMessages(),$n.clear();try{localStorage.removeItem(Pr),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Pr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Pr)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),a!=null&&a.clear)try{let h=a.clear();h instanceof Promise&&h.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}i={},C.syncFromMetadata(),_==null||_.clear(),D==null||D.update()})})(),Ue&&Ue.addEventListener("submit",_r),te==null||te.addEventListener("keydown",jr),te==null||te.addEventListener("paste",Vr),xt.push(()=>{Ue&&Ue.removeEventListener("submit",_r),te==null||te.removeEventListener("keydown",jr),te==null||te.removeEventListener("paste",Vr)}),xt.push(()=>{H.cancel()}),we?xt.push(()=>{we==null||we.destroy()}):Ne&&xt.push(()=>{Ne==null||Ne.remove()});let T={update(l){var La,Pa,Ia,Wa,Ra,Ha,Ba,Fa,$a,Na,Oa,Da,_a,ja,Va,Ua,qa,za,Ja,Ka,Ya,Xa,Ga,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Pi,Ii,Wi,Ri,Hi,Bi,Fi,$i,Ni,Oi,Di,_i,ji,Vi,Ui,qi,zi,Ji,Ki,Yi,Xi,Gi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,gl,ml,fl;let u=r.toolCall,h=r.messageActions,S=(La=r.layout)==null?void 0:La.messages,R=r.colorScheme,L=r.loadingIndicator,P=r.iterationDisplay;r={...r,...l},_n(),On(e,r),Go(e,r),Zo(e,r),hn(),r.colorScheme!==R&&Hr();let V=io.getForInstance(r.plugins);s.length=0,s.push(...V),v=(Ia=(Pa=r.launcher)==null?void 0:Pa.enabled)!=null?Ia:!0,E=(Ra=(Wa=r.launcher)==null?void 0:Wa.autoExpand)!=null?Ra:!1,J=(Ba=(Ha=r.features)==null?void 0:Ha.showReasoning)!=null?Ba:!0,me=($a=(Fa=r.features)==null?void 0:Fa.showToolCalls)!=null?$a:!0;let $=We;if(We=(Oa=(Na=r.features)==null?void 0:Na.showEventStreamToggle)!=null?Oa:!1,We&&!$){if(_||(ee=new oo(ye),_=new ro(Y,ee),ee.open().then(()=>_==null?void 0:_.restore()).catch(()=>{}),H.setSSEEventCallback((O,Ke)=>{_.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:O,timestamp:Date.now(),payload:JSON.stringify(Ke)})})),!ge&&Ve){let O=(_a=(Da=r.features)==null?void 0:Da.eventStream)==null?void 0:_a.classNames,Ke="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(O!=null&&O.toggleButton?" "+O.toggleButton:"");ge=f("button",Ke),ge.style.width="28px",ge.style.height="28px",ge.type="button",ge.setAttribute("aria-label","Event Stream"),ge.title="Event Stream";let ht=fe("activity","18px","currentColor",1.5);ht&&ge.appendChild(ht);let De=U.clearChatButtonWrapper,et=U.closeButtonWrapper,Pt=De||et;Pt&&Pt.parentNode===Ve?Ve.insertBefore(ge,Pt):Ve.appendChild(ge),ge.addEventListener("click",()=>{ue?Fe():Ce()})}}else!We&&$&&(Fe(),ge&&(ge.remove(),ge=null),_==null||_.clear(),ee==null||ee.destroy(),_=null,ee=null);if(((ja=r.launcher)==null?void 0:ja.enabled)===!1&&we&&(we.destroy(),we=null),((Va=r.launcher)==null?void 0:Va.enabled)===!1&&Ne&&(Ne.remove(),Ne=null),((Ua=r.launcher)==null?void 0:Ua.enabled)!==!1&&!we&&!Ne){let O=s.find(Ke=>Ke.renderLauncher);if(O!=null&&O.renderLauncher){let Ke=O.renderLauncher({config:r,defaultRenderer:()=>no(r,$e).element,onToggle:$e});Ke&&(Ne=Ke,e.appendChild(Ne))}Ne||(we=no(r,$e),e.appendChild(we.element))}we&&we.update(r),ke&&((qa=r.launcher)==null?void 0:qa.title)!==void 0&&(ke.textContent=r.launcher.title),nt&&((za=r.launcher)==null?void 0:za.subtitle)!==void 0&&(nt.textContent=r.launcher.subtitle);let se=(Ja=r.layout)==null?void 0:Ja.header;if((se==null?void 0:se.layout)!==M&&Ve){let O=se?Sr(r,se,{showClose:v,onClose:()=>ft(!1,"user")}):Pn({config:r,showClose:v,onClose:()=>ft(!1,"user")});Ve.replaceWith(O.header),Ve=O.header,ze=O.iconHolder,ke=O.headerTitle,nt=O.headerSubtitle,ce=O.closeButton,M=se==null?void 0:se.layout}else if(se&&(ze&&(ze.style.display=se.showIcon===!1?"none":""),ke&&(ke.style.display=se.showTitle===!1?"none":""),nt&&(nt.style.display=se.showSubtitle===!1?"none":""),ce&&(ce.style.display=se.showCloseButton===!1?"none":""),U.clearChatButtonWrapper)){let O=se.showClearChat;if(O!==void 0){U.clearChatButtonWrapper.style.display=O?"":"none";let{closeButtonWrapper:Ke}=U;Ke&&!Ke.classList.contains("persona-absolute")&&(O?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}let Le=((Ka=r.layout)==null?void 0:Ka.showHeader)!==!1;Ve&&(Ve.style.display=Le?"":"none");let Oe=((Ya=r.layout)==null?void 0:Ya.showFooter)!==!1;Ze&&(Ze.style.display=Oe?"":"none"),v!==q?v?ft(E,"auto"):(w=!0,gr()):E!==k&&ft(E,"auto"),k=E,q=v,vt(),b();let Me=JSON.stringify(l.toolCall)!==JSON.stringify(u),Ee=JSON.stringify(r.messageActions)!==JSON.stringify(h),re=JSON.stringify((Xa=r.layout)==null?void 0:Xa.messages)!==JSON.stringify(S),Ie=((Ga=r.loadingIndicator)==null?void 0:Ga.render)!==(L==null?void 0:L.render)||((Za=r.loadingIndicator)==null?void 0:Za.renderIdle)!==(L==null?void 0:L.renderIdle)||((Qa=r.loadingIndicator)==null?void 0:Qa.showBubble)!==(L==null?void 0:L.showBubble),rt=r.iterationDisplay!==P;(Me||Ee||re||Ie||rt)&&H&&(Br++,Un(Te,H.getMessages(),oe));let pe=(ei=r.launcher)!=null?ei:{},Lt=(ti=pe.headerIconHidden)!=null?ti:!1,at=(ri=(ni=r.layout)==null?void 0:ni.header)==null?void 0:ri.showIcon,Xt=Lt||at===!1,_t=pe.headerIconName,zt=(oi=pe.headerIconSize)!=null?oi:"48px";if(ze){let O=ne.querySelector(".persona-border-b-persona-divider"),Ke=O==null?void 0:O.querySelector(".persona-flex-col");if(Xt)ze.style.display="none",O&&Ke&&!O.contains(Ke)&&O.insertBefore(Ke,O.firstChild);else{if(ze.style.display="",ze.style.height=zt,ze.style.width=zt,O&&Ke&&(O.contains(ze)?ze.nextSibling!==Ke&&(ze.remove(),O.insertBefore(ze,Ke)):O.insertBefore(ze,Ke)),_t){let De=parseFloat(zt)||24,et=fe(_t,De*.6,"#ffffff",2);et?ze.replaceChildren(et):ze.textContent=(si=pe.agentIconText)!=null?si:"\u{1F4AC}"}else if(pe.iconUrl){let De=ze.querySelector("img");if(De)De.src=pe.iconUrl,De.style.height=zt,De.style.width=zt;else{let et=document.createElement("img");et.src=pe.iconUrl,et.alt="",et.className="persona-rounded-xl persona-object-cover",et.style.height=zt,et.style.width=zt,ze.replaceChildren(et)}}else{let De=ze.querySelector("svg"),et=ze.querySelector("img");(De||et)&&ze.replaceChildren(),ze.textContent=(ai=pe.agentIconText)!=null?ai:"\u{1F4AC}"}let ht=ze.querySelector("img");ht&&(ht.style.height=zt,ht.style.width=zt)}}let Ft=(li=(ii=r.layout)==null?void 0:ii.header)==null?void 0:li.showTitle,sn=(di=(ci=r.layout)==null?void 0:ci.header)==null?void 0:di.showSubtitle;if(ke&&(ke.style.display=Ft===!1?"none":""),nt&&(nt.style.display=sn===!1?"none":""),ce){((ui=(pi=r.layout)==null?void 0:pi.header)==null?void 0:ui.showCloseButton)===!1?ce.style.display="none":ce.style.display="";let Ke=(gi=pe.closeButtonSize)!=null?gi:"32px",ht=(mi=pe.closeButtonPlacement)!=null?mi:"inline";ce.style.height=Ke,ce.style.width=Ke;let{closeButtonWrapper:De}=U,et=ht==="top-right",Pt=De==null?void 0:De.classList.contains("persona-absolute");if(De&&et!==Pt)if(De.remove(),et)De.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ne.style.position="relative",ne.appendChild(De);else{let Ye=(hi=(fi=pe.clearChat)==null?void 0:fi.placement)!=null?hi:"inline",$t=(bi=(yi=pe.clearChat)==null?void 0:yi.enabled)!=null?bi:!0;De.className=$t&&Ye==="inline"?"":"persona-ml-auto";let Gt=ne.querySelector(".persona-border-b-persona-divider");Gt&&Gt.appendChild(De)}if(pe.closeButtonColor?(ce.style.color=pe.closeButtonColor,ce.classList.remove("persona-text-persona-muted")):(ce.style.color="",ce.classList.add("persona-text-persona-muted")),pe.closeButtonBackgroundColor?(ce.style.backgroundColor=pe.closeButtonBackgroundColor,ce.classList.remove("hover:persona-bg-gray-100")):(ce.style.backgroundColor="",ce.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let Ye=pe.closeButtonBorderWidth||"0px",$t=pe.closeButtonBorderColor||"transparent";ce.style.border=`${Ye} solid ${$t}`,ce.classList.remove("persona-border-none")}else ce.style.border="",ce.classList.add("persona-border-none");pe.closeButtonBorderRadius?(ce.style.borderRadius=pe.closeButtonBorderRadius,ce.classList.remove("persona-rounded-full")):(ce.style.borderRadius="",ce.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(ce.style.paddingLeft=pe.closeButtonPaddingX,ce.style.paddingRight=pe.closeButtonPaddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),pe.closeButtonPaddingY?(ce.style.paddingTop=pe.closeButtonPaddingY,ce.style.paddingBottom=pe.closeButtonPaddingY):(ce.style.paddingTop="",ce.style.paddingBottom="");let Ot=(xi=pe.closeButtonIconName)!=null?xi:"x",en=(vi=pe.closeButtonIconText)!=null?vi:"\xD7";ce.innerHTML="";let Jt=fe(Ot,"20px",pe.closeButtonColor||"",2);Jt?ce.appendChild(Jt):ce.textContent=en;let St=(Ci=pe.closeButtonTooltipText)!=null?Ci:"Close chat",tn=(wi=pe.closeButtonShowTooltip)!=null?wi:!0;if(ce.setAttribute("aria-label",St),De&&(De._cleanupTooltip&&(De._cleanupTooltip(),delete De._cleanupTooltip),tn&&St)){let Ye=null,$t=()=>{if(Ye||!ce)return;let Xn=ce.ownerDocument,Yr=Xn.body;if(!Yr)return;Ye=vn(Xn,"div","persona-clear-chat-tooltip"),Ye.textContent=St;let Xr=vn(Xn,"div");Xr.className="persona-clear-chat-tooltip-arrow",Ye.appendChild(Xr);let Gn=ce.getBoundingClientRect();Ye.style.position="fixed",Ye.style.left=`${Gn.left+Gn.width/2}px`,Ye.style.top=`${Gn.top-8}px`,Ye.style.transform="translate(-50%, -100%)",Yr.appendChild(Ye)},Gt=()=>{Ye&&Ye.parentNode&&(Ye.parentNode.removeChild(Ye),Ye=null)};De.addEventListener("mouseenter",$t),De.addEventListener("mouseleave",Gt),ce.addEventListener("focus",$t),ce.addEventListener("blur",Gt),De._cleanupTooltip=()=>{Gt(),De&&(De.removeEventListener("mouseenter",$t),De.removeEventListener("mouseleave",Gt)),ce&&(ce.removeEventListener("focus",$t),ce.removeEventListener("blur",Gt))}}}let{clearChatButton:je,clearChatButtonWrapper:yt}=U;if(je){let O=(Si=pe.clearChat)!=null?Si:{},Ke=(Ai=O.enabled)!=null?Ai:!0,ht=(Ti=(Ei=r.layout)==null?void 0:Ei.header)==null?void 0:Ti.showClearChat,De=ht!==void 0?ht:Ke,et=(Mi=O.placement)!=null?Mi:"inline";if(yt){yt.style.display=De?"":"none";let{closeButtonWrapper:Pt}=U;Pt&&!Pt.classList.contains("persona-absolute")&&(De?Pt.classList.remove("persona-ml-auto"):Pt.classList.add("persona-ml-auto"));let Ot=et==="top-right",en=yt.classList.contains("persona-absolute");if(Ot!==en&&De){if(yt.remove(),Ot)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",ne.style.position="relative",ne.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let St=ne.querySelector(".persona-border-b-persona-divider"),tn=U.closeButtonWrapper;St&&tn&&tn.parentElement===St?St.insertBefore(yt,tn):St&&St.appendChild(yt)}let Jt=U.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(Ot?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(De){let Pt=(ki=O.size)!=null?ki:"32px";je.style.height=Pt,je.style.width=Pt;let Ot=(Li=O.iconName)!=null?Li:"refresh-cw",en=(Pi=O.iconColor)!=null?Pi:"";je.innerHTML="";let Jt=fe(Ot,"20px",en||"",2);if(Jt&&je.appendChild(Jt),en?(je.style.color=en,je.classList.remove("persona-text-persona-muted")):(je.style.color="",je.classList.add("persona-text-persona-muted")),O.backgroundColor?(je.style.backgroundColor=O.backgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),O.borderWidth||O.borderColor){let Ye=O.borderWidth||"0px",$t=O.borderColor||"transparent";je.style.border=`${Ye} solid ${$t}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");O.borderRadius?(je.style.borderRadius=O.borderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),O.paddingX?(je.style.paddingLeft=O.paddingX,je.style.paddingRight=O.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),O.paddingY?(je.style.paddingTop=O.paddingY,je.style.paddingBottom=O.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let St=(Ii=O.tooltipText)!=null?Ii:"Clear chat",tn=(Wi=O.showTooltip)!=null?Wi:!0;if(je.setAttribute("aria-label",St),yt&&(yt._cleanupTooltip&&(yt._cleanupTooltip(),delete yt._cleanupTooltip),tn&&St)){let Ye=null,$t=()=>{if(Ye||!je)return;let Xn=je.ownerDocument,Yr=Xn.body;if(!Yr)return;Ye=vn(Xn,"div","persona-clear-chat-tooltip"),Ye.textContent=St;let Xr=vn(Xn,"div");Xr.className="persona-clear-chat-tooltip-arrow",Ye.appendChild(Xr);let Gn=je.getBoundingClientRect();Ye.style.position="fixed",Ye.style.left=`${Gn.left+Gn.width/2}px`,Ye.style.top=`${Gn.top-8}px`,Ye.style.transform="translate(-50%, -100%)",Yr.appendChild(Ye)},Gt=()=>{Ye&&Ye.parentNode&&(Ye.parentNode.removeChild(Ye),Ye=null)};yt.addEventListener("mouseenter",$t),yt.addEventListener("mouseleave",Gt),je.addEventListener("focus",$t),je.addEventListener("blur",Gt),yt._cleanupTooltip=()=>{Gt(),yt&&(yt.removeEventListener("mouseenter",$t),yt.removeEventListener("mouseleave",Gt)),je&&(je.removeEventListener("focus",$t),je.removeEventListener("blur",Gt))}}}}let Eo=r.actionParsers&&r.actionParsers.length?r.actionParsers:[lo],To=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ar.message,ar.messageAndClick];C=co({parsers:Eo,handlers:To,getSessionMetadata:g,updateSessionMetadata:p,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),oe=xc(r,C,K),H.updateConfig(r),Un(Te,H.getMessages(),oe),Bn.render(r.suggestionChips,H,te,void 0,r.suggestionChipsConfig),Dr(),mr(H.isStreaming());let Mo=((Ri=r.voiceRecognition)==null?void 0:Ri.enabled)===!0,ko=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Lo=((Bi=(Hi=r.voiceRecognition)==null?void 0:Hi.provider)==null?void 0:Bi.type)==="runtype";if(Mo&&(ko||Lo))if(!B||!G){let O=Co(r.voiceRecognition,r.sendButton);O&&(B=O.micButton,G=O.micButtonWrapper,Tt.insertBefore(G,He),B.addEventListener("click",Jn),B.disabled=H.isStreaming())}else{let O=(Fi=r.voiceRecognition)!=null?Fi:{},Ke=($i=r.sendButton)!=null?$i:{},ht=(Ni=O.iconName)!=null?Ni:"mic",De=(Oi=Ke.size)!=null?Oi:"40px",et=(Di=O.iconSize)!=null?Di:De,Pt=parseFloat(et)||24;B.style.width=et,B.style.height=et,B.style.minWidth=et,B.style.minHeight=et;let Ot=(ji=(_i=O.iconColor)!=null?_i:Ke.textColor)!=null?ji:"currentColor";B.innerHTML="";let en=fe(ht,Pt,Ot,2);en?B.appendChild(en):B.textContent="\u{1F3A4}";let Jt=(Vi=O.backgroundColor)!=null?Vi:Ke.backgroundColor;Jt?(B.style.backgroundColor=Jt,B.classList.remove("persona-bg-persona-primary")):(B.style.backgroundColor="",B.classList.add("persona-bg-persona-primary")),Ot?(B.style.color=Ot,B.classList.remove("persona-text-white")):!Ot&&!Ke.textColor&&(B.style.color="",B.classList.add("persona-text-white")),O.borderWidth?(B.style.borderWidth=O.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),O.borderColor?B.style.borderColor=O.borderColor:B.style.borderColor="",O.paddingX?(B.style.paddingLeft=O.paddingX,B.style.paddingRight=O.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),O.paddingY?(B.style.paddingTop=O.paddingY,B.style.paddingBottom=O.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let St=G==null?void 0:G.querySelector(".persona-send-button-tooltip"),tn=(Ui=O.tooltipText)!=null?Ui:"Start voice recognition";if(((qi=O.showTooltip)!=null?qi:!1)&&tn)if(St)St.textContent=tn,St.style.display="";else{let $t=document.createElement("div");$t.className="persona-send-button-tooltip",$t.textContent=tn,G==null||G.insertBefore($t,B)}else St&&(St.style.display="none");G.style.display="",B.disabled=H.isStreaming()}else B&&G&&(G.style.display="none",((Ji=(zi=r.voiceRecognition)==null?void 0:zi.provider)==null?void 0:Ji.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():Qt&&cn());if(((Ki=r.attachments)==null?void 0:Ki.enabled)===!0)if(!j||!z){let O=(Yi=r.attachments)!=null?Yi:{},ht=(Gi=((Xi=r.sendButton)!=null?Xi:{}).size)!=null?Gi:"40px";Pe||(Pe=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Pe.style.display="none",Ue.insertBefore(Pe,te)),xe||(xe=document.createElement("input"),xe.type="file",xe.accept=((Zi=O.allowedTypes)!=null?Zi:Ln).join(","),xe.multiple=((Qi=O.maxFiles)!=null?Qi:4)>1,xe.style.display="none",xe.setAttribute("aria-label","Attach files"),Ue.insertBefore(xe,te)),j=f("div","persona-send-button-wrapper"),z=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),z.type="button",z.setAttribute("aria-label",(el=O.buttonTooltipText)!=null?el:"Attach file");let De=(tl=O.buttonIconName)!=null?tl:"paperclip",et=ht,Pt=parseFloat(et)||40,Ot=Math.round(Pt*.6);z.style.width=et,z.style.height=et,z.style.minWidth=et,z.style.minHeight=et,z.style.fontSize="18px",z.style.lineHeight="1",z.style.backgroundColor="transparent",z.style.color="var(--persona-primary, #111827)",z.style.border="none",z.style.borderRadius="6px",z.style.transition="background-color 0.15s ease",z.addEventListener("mouseenter",()=>{z.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),z.addEventListener("mouseleave",()=>{z.style.backgroundColor="transparent"});let en=fe(De,Ot,"currentColor",1.5);en?z.appendChild(en):z.textContent="\u{1F4CE}",z.addEventListener("click",tn=>{tn.preventDefault(),xe==null||xe.click()}),j.appendChild(z);let Jt=(nl=O.buttonTooltipText)!=null?nl:"Attach file",St=f("div","persona-send-button-tooltip");St.textContent=Jt,j.appendChild(St),Rt.append(j),!Be&&xe&&Pe&&(Be=rr.fromConfig(O),Be.setPreviewsContainer(Pe),xe.addEventListener("change",async()=>{Be&&(xe!=null&&xe.files)&&(await Be.handleFileSelect(xe.files),xe.value="")}))}else{j.style.display="";let O=(rl=r.attachments)!=null?rl:{};xe&&(xe.accept=((ol=O.allowedTypes)!=null?ol:Ln).join(","),xe.multiple=((sl=O.maxFiles)!=null?sl:4)>1),Be&&Be.updateConfig({allowedTypes:O.allowedTypes,maxFileSize:O.maxFileSize,maxFiles:O.maxFiles})}else j&&(j.style.display="none"),Be&&Be.clearAttachments();let Et=(al=r.sendButton)!=null?al:{},Po=(il=Et.useIcon)!=null?il:!1,qr=(ll=Et.iconText)!=null?ll:"\u2191",Kn=Et.iconName,Yn=(cl=Et.tooltipText)!=null?cl:"Send message",Yc=(dl=Et.showTooltip)!=null?dl:!1,zr=(pl=Et.size)!=null?pl:"40px",Io=Et.backgroundColor,xn=Et.textColor;if(Po){if(X.style.width=zr,X.style.height=zr,X.style.minWidth=zr,X.style.minHeight=zr,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Kn){let O=parseFloat(zr)||24,Ke=xn&&typeof xn=="string"&&xn.trim()?xn.trim():"currentColor",ht=fe(Kn,O,Ke,2);ht?(X.appendChild(ht),X.style.color=Ke):(X.textContent=qr,xn?X.style.color=xn:X.classList.add("persona-text-white"))}else X.textContent=qr,xn?X.style.color=xn:X.classList.add("persona-text-white");X.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Io?(X.style.backgroundColor=Io,X.classList.remove("persona-bg-persona-primary")):X.classList.add("persona-bg-persona-primary")}else X.textContent=(gl=(ul=r.copy)==null?void 0:ul.sendButtonLabel)!=null?gl:"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",Io?(X.style.backgroundColor=Io,X.classList.remove("persona-bg-persona-accent")):X.classList.add("persona-bg-persona-accent"),xn?X.style.color=xn:X.classList.add("persona-text-white");Et.borderWidth?(X.style.borderWidth=Et.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),Et.borderColor?X.style.borderColor=Et.borderColor:X.style.borderColor="",Et.paddingX?(X.style.paddingLeft=Et.paddingX,X.style.paddingRight=Et.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),Et.paddingY?(X.style.paddingTop=Et.paddingY,X.style.paddingBottom=Et.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let Jr=He==null?void 0:He.querySelector(".persona-send-button-tooltip");if(Yc&&Yn)if(Jr)Jr.textContent=Yn,Jr.style.display="";else{let O=document.createElement("div");O.className="persona-send-button-tooltip",O.textContent=Yn,He==null||He.insertBefore(O,X)}else Jr&&(Jr.style.display="none");let Kr=(ml=r.statusIndicator)!=null?ml:{},Xc=(fl=Kr.visible)!=null?fl:!0;if(tt.style.display=Xc?"":"none",H){let O=H.getStatus(),Ke=ht=>{var De,et,Pt,Ot;return ht==="idle"?(De=Kr.idleText)!=null?De:jt.idle:ht==="connecting"?(et=Kr.connectingText)!=null?et:jt.connecting:ht==="connected"?(Pt=Kr.connectedText)!=null?Pt:jt.connected:ht==="error"?(Ot=Kr.errorText)!=null?Ot:jt.error:jt[ht]};tt.textContent=Ke(O)}},open(){v&&ft(!0,"api")},close(){v&&ft(!1,"api")},toggle(){v&&ft(!w,"api")},clearChat(){ln=!1,H.clearMessages(),$n.clear();try{localStorage.removeItem(Pr),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Pr}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Pr)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let u=a.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}i={},C.syncFromMetadata(),_==null||_.clear(),D==null||D.update()},setMessage(l){return!te||H.isStreaming()?!1:(!w&&v&&ft(!0,"system"),te.value=l,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let u=(l==null?void 0:l.trim())||te.value.trim();return u?(!w&&v&&ft(!0,"system"),te.value="",te.style.height="auto",H.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return H.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(H.isVoiceActive()||(!w&&v&&ft(!0,"system"),qe.manuallyDeactivated=!1,Kt(),H.toggleVoice().then(()=>{qe.active=H.isVoiceActive(),rn("user"),H.isVoiceActive()&&Nn()})),!0):Qt?!0:Ur()?(!w&&v&&ft(!0,"system"),qe.manuallyDeactivated=!1,Kt(),qn("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,Kt(),rn("user"),dn()}),!0):!1:Qt?(qe.manuallyDeactivated=!0,Kt(),cn("user"),!0):!1},injectMessage(l){return!w&&v&&ft(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!w&&v&&ft(!0,"system");let u=H.injectAssistantMessage(l);return F&&(F=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),u},injectUserMessage(l){return!w&&v&&ft(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!w&&v&&ft(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!w&&v&&ft(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!w&&v&&ft(!0,"system"),H.injectTestEvent(l)},async connectStream(l,u){return H.connectStream(l,u)},__pushEventStreamEvent(l){_&&_.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!We||!_||Ce()},hideEventStream(){ue&&Fe()},isEventStreamVisible(){return ue},showArtifacts(){an(r)&&(ln=!1,hn(),Qe==null||Qe.setMobileOpen(!0))},hideArtifacts(){an(r)&&(ln=!0,hn())},upsertArtifact(l){return an(r)?(ln=!1,H.upsertArtifact(l)):null},selectArtifact(l){an(r)&&H.selectArtifact(l)},clearArtifacts(){an(r)&&H.clearArtifacts()},focusInput(){return v&&!w||!te?!1:(te.focus(),!0)},async resolveApproval(l,u){let S=H.getMessages().find(R=>{var L;return R.variant==="approval"&&((L=R.approval)==null?void 0:L.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(S.approval,u)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){p(l)},on(l,u){return o.on(l,u)},off(l,u){o.off(l,u)},isOpen(){return v&&w},isVoiceActive(){return qe.active},getState(){return{open:v&&w,launcherEnabled:v,voiceActive:qe.active,streaming:H.isStreaming()}},showCSATFeedback(l){!w&&v&&ft(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let h=ss({onSubmit:async(S,R)=>{var L;H.isClientTokenMode()&&await H.submitCSATFeedback(S,R),(L=l==null?void 0:l.onSubmit)==null||L.call(l,S,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Te.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!w&&v&&ft(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let h=as({onSubmit:async(S,R)=>{var L;H.isClientTokenMode()&&await H.submitNPSFeedback(S,R),(L=l==null?void 0:l.onSubmit)==null||L.call(l,S,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Te.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return H.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return H.submitNPSFeedback(l,u)},destroy(){xt.forEach(l=>l()),de.remove(),we==null||we.destroy(),Ne==null||Ne.remove(),bn&&ce.removeEventListener("click",bn)}};if((((Sa=t==null?void 0:t.debugTools)!=null?Sa:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:T,getMessages:T.getMessages,getStatus:T.getStatus,getMetadata:T.getPersistentMetadata,updateMetadata:T.updatePersistentMetadata,clearHistory:()=>T.clearChat(),setVoiceActive:h=>h?T.startVoiceRecognition():T.stopVoiceRecognition()};window.AgentWidgetBrowser=u,xt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.focusInput()};if(window.addEventListener("persona:focusInput",u),xt.push(()=>{window.removeEventListener("persona:focusInput",u)}),We){let V=se=>{let he=se.detail;(!(he!=null&&he.instanceId)||he.instanceId===l)&&T.showEventStream()},$=se=>{let he=se.detail;(!(he!=null&&he.instanceId)||he.instanceId===l)&&T.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",$),xt.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",$)})}let h=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.showArtifacts()},S=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.hideArtifacts()},R=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==l||$!=null&&$.artifact&&T.upsertArtifact($.artifact)},L=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==l||typeof($==null?void 0:$.id)=="string"&&T.selectArtifact($.id)},P=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",S),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",P),xt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",S),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",P)})}let W=cp(r.persistState);if(W&&v){let l=dp(W.storage),u=`${W.keyPrefix}widget-open`,h=`${W.keyPrefix}widget-voice`,S=`${W.keyPrefix}widget-voice-mode`;if(l){let R=((Aa=W.persist)==null?void 0:Aa.openState)&&l.getItem(u)==="true",L=((Ea=W.persist)==null?void 0:Ea.voiceState)&&l.getItem(h)==="true",P=((Ta=W.persist)==null?void 0:Ta.voiceState)&&l.getItem(S)==="true";if(R&&setTimeout(()=>{T.open(),setTimeout(()=>{var V;if(L||P)T.startVoiceRecognition();else if((V=W.persist)!=null&&V.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0),(Ma=W.persist)!=null&&Ma.openState&&(o.on("widget:opened",()=>{l.setItem(u,"true")}),o.on("widget:closed",()=>{l.setItem(u,"false")})),(ka=W.persist)!=null&&ka.voiceState&&(o.on("voice:state",V=>{l.setItem(h,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(S,V.viaVoice?"true":"false")})),W.clearOnChatClear){let V=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(S)},$=()=>V();window.addEventListener("persona:clear-chat",$),xt.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}return T};var vc=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},zs=(e,n,t,r,s,o)=>{let a=wr(s),i=o?a.width:a.collapsedWidth;e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=a.side,e.dataset.personaDockOpen=o?"true":"false",e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto",n.style.minWidth="0",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.flex=`0 0 ${i}`,t.style.width=i,t.style.maxWidth=i,t.style.minWidth=i,t.style.minHeight="0",t.style.position="relative",t.style.overflow="visible",t.style.transition="width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto",a.side==="left"?e.firstElementChild!==t&&e.replaceChildren(t,n):e.lastElementChild!==t&&e.replaceChildren(n,t)},pp=(e,n)=>{let t=e.ownerDocument.createElement("div");return vc(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){vc(t,r)},destroy(){t.remove()}}},up=(e,n)=>{var p,y,m,C;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("aside"),c=t.createElement("div"),g=(y=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)==null||y?(C=(m=n==null?void 0:n.launcher)==null?void 0:m.autoExpand)!=null?C:!1:!0;return i.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),r.insertBefore(a,e),i.appendChild(e),a.appendChild(i),a.appendChild(d),zs(a,i,d,c,n,g),{mode:"docked",host:c,shell:a,syncWidgetState(v){let E=v.launcherEnabled?v.open:!0;g!==E&&(g=E,zs(a,i,d,c,n,g))},updateConfig(v){var E,x;n=v,((x=(E=n==null?void 0:n.launcher)==null?void 0:E.enabled)!=null?x:!0)===!1&&(g=!0),zs(a,i,d,c,n,g)},destroy(){r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},po=(e,n)=>Vt(n)?up(e,n):pp(e,n);var Js={},gp=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},mp=()=>{try{if(typeof Js!="undefined"&&Js.url)return new URL("../widget.css",Js.url).href}catch{}return null},Cc=(e,n)=>{let t=mp(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},Ks=e=>{var E;let n=gp(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=po(n,s),a,i=[],d=(x,k)=>{var w,F;let M=!((F=(w=k==null?void 0:k.launcher)==null?void 0:w.enabled)!=null?F:!0)||Vt(k),N=r.createElement("div");if(N.id="persona-root",M&&(N.style.height="100%",N.style.display="flex",N.style.flexDirection="column",N.style.flex="1",N.style.minHeight="0"),t){let Q=x.attachShadow({mode:"open"});Q.appendChild(N),Cc(Q,r)}else x.appendChild(N),Cc(x,r);return n.id&&N.setAttribute("data-persona-instance",n.id),N},c=()=>{o.syncWidgetState(a.getState())},g=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(o.host,s);a=is(x,s,{debugTools:e.debugTools}),g()},y=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(E=e.onReady)==null||E.call(e);let m=x=>{y(),o.destroy(),o=po(n,x),s=x,p()},C={update(x){var N,w,F,Q,K,oe;let k={...s,...x,launcher:{...(N=s==null?void 0:s.launcher)!=null?N:{},...(w=x==null?void 0:x.launcher)!=null?w:{},dock:{...(Q=(F=s==null?void 0:s.launcher)==null?void 0:F.dock)!=null?Q:{},...(oe=(K=x==null?void 0:x.launcher)==null?void 0:K.dock)!=null?oe:{}}}},q=Vt(s),M=Vt(k);if(q!==M){m(k);return}s=k,o.updateConfig(s),a.update(x),c()},destroy(){y(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(C,{get(x,k,q){if(k==="host")return o.host;if(k in x)return Reflect.get(x,k,q);let M=a[k];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Tc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),fp=new Set(["button","a","input","select","textarea","details","summary"]),hp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ys=/\b(product|card|item|listing|result)\b/i,Gs=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,yp=3e3,bp=100;function Mc(e){let n=typeof e.className=="string"?e.className:"";if(Ys.test(n)||e.id&&Ys.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Ys.test(r.value))return!0}return!1}function kc(e){var n;return Gs.test(((n=e.textContent)!=null?n:"").trim())}function Lc(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function xp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function wc(e){let n=e.match(Gs);return n?n[0]:null}function Sc(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function vp(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var Cp="commerce-card",wp="result-card";function Ac(e){return!Mc(e)||!kc(e)||!Lc(e)&&!xp(e)?0:5200}function Ec(e){var r;return!Mc(e)||kc(e)||!Lc(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Zs=[{id:Cp,scoreElement(e){return Ac(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||Gs.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,c,g;if(Ac(e)===0)return null;let{title:t,href:r}=Sc(e),s=(g=(c=wc(((d=e.textContent)!=null?d:"").trim()))!=null?c:wc(n.text))!=null?g:"",o=vp(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
96
|
-
`)}},{id:
|
|
97
|
-
`)}}];function
|
|
95
|
+
`}if(!S&&!l){let Kn="max-height: -moz-available !important; max-height: stretch !important;",Yn=u?"":"padding-top: 1.25em !important;";de.style.cssText+=Kn+Yn}};_n(),On(e,r),Zo(e,r),Qo(e,r);let xt=[];mn&&xt.push(()=>{mn==null||mn.disconnect(),mn=null}),xt.push(()=>{nn==null||nn(),nn=null,cr(),dt&&(dt.remove(),dt=null),Qe==null||Qe.element.style.removeProperty("width"),Qe==null||Qe.element.style.removeProperty("maxWidth")}),Ie&&xt.push(()=>{he!==null&&(cancelAnimationFrame(he),he=null),U==null||U.destroy(),U=null,D==null||D.destroy(),D=null,ee=null});let yn=null,Br=()=>{yn&&(yn(),yn=null),r.colorScheme==="auto"&&(yn=Go(()=>{On(e,r)}))};Br(),xt.push(()=>{yn&&(yn(),yn=null)});let Bn=ic(ze),bn=null,H,Fn=!1,$n=Xl(),Fr=0,Sn=!0,jn=0,$r=0,An=null,En=!1,dr=0,pr=!1,mo=125,fo=2e3,ho=5,Nr=50,ur=new Map,Ue={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Or=(Ca=(va=r.voiceRecognition)==null?void 0:va.autoResume)!=null?Ca:!1,rn=l=>{o.emit("voice:state",{active:Ue.active,source:l,timestamp:Date.now()})},Kt=()=>{p(l=>({...l,voiceState:{active:Ue.active,timestamp:Date.now(),manuallyDeactivated:Ue.manuallyDeactivated}}))},yo=()=>{var S,R;if(((S=r.voiceRecognition)==null?void 0:S.enabled)===!1)return;let l=Js(i.voiceState),u=!!l.active,y=Number((R=l.timestamp)!=null?R:0);Ue.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-y<up&&setTimeout(()=>{var L,P;Ue.active||(Ue.manuallyDeactivated=!1,((P=(L=r.voiceRecognition)==null?void 0:L.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{Ue.active=H.isVoiceActive(),rn("restore"),H.isVoiceActive()&&Nn()}):qn("restore"))},1e3)},bo=()=>H?wc(H.getMessages()).filter(l=>!l.__skipPersist):[];function Dr(l){if(!(a!=null&&a.save))return;let y={messages:l?wc(l):H?bo():[],metadata:i};try{let S=a.save(y);S instanceof Promise&&S.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let Vn=(l=!1)=>{if(!Sn)return;let u=Date.now();En&&u<dr&&!l||(En&&u>=dr&&(En=!1),!(!l&&!Fn)&&(u-$r<mo||($r=u,An&&cancelAnimationFrame(An),An=requestAnimationFrame(()=>{En||!Sn||(pr=!0,G.scrollTop=G.scrollHeight,jn=G.scrollTop,requestAnimationFrame(()=>{pr=!1}),An=null)}))))},Tn=null,xo=()=>de.querySelector("#persona-scroll-container")||G,vo=(l,u=500)=>{let y=l.scrollTop,S=l.clientHeight,R=l.scrollHeight,L=R-y;if(y+S>=R-2||Math.abs(L)<5)return;Tn!==null&&(cancelAnimationFrame(Tn),Tn=null);let V=performance.now(),$=fe=>1-Math.pow(1-fe,3),se=fe=>{let ke=l.scrollHeight;ke!==R&&(R=ke,L=R-y);let Ne=fe-V,Ae=Math.min(Ne/u,1),I=$(Ae),Te=y+L*I;l.scrollTop=Te,Ae<1?Tn=requestAnimationFrame(se):(l.scrollTop=l.scrollHeight,Tn=null)};Tn=requestAnimationFrame(se)},Co=l=>{let u=new Map;l.forEach(y=>{let S=ur.get(y.id);u.set(y.id,{streaming:y.streaming,role:y.role}),!S&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(S!=null&&S.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(S?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),ur.clear(),u.forEach((y,S)=>{ur.set(S,y)})},Un=(l,u,y)=>{var fe,ke,Ne,Ae;let S=document.createElement("div"),L=(()=>{var Te;let I=s.find(Ee=>Ee.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((Te=r.loadingIndicator)!=null&&Te.render)return r.loadingIndicator.render})(),P=new Set;u.forEach(I=>{var pe,Pt;P.add(I.id);let Te=Gl(I,Fr),Ee=Zl($n,I.id,Te);if(Ee){S.appendChild(Ee.cloneNode(!0));return}let ne=null,Pe=s.find(it=>!!(I.variant==="reasoning"&&it.renderReasoning||I.variant==="tool"&&it.renderToolCall||I.variant==="approval"&&it.renderApproval||!I.variant&&it.renderMessage)),rt=(pe=r.layout)==null?void 0:pe.messages;if(Pe)if(I.variant==="reasoning"&&I.reasoning&&Pe.renderReasoning){if(!z)return;ne=Pe.renderReasoning({message:I,defaultRenderer:()=>$s(I),config:r})}else if(I.variant==="tool"&&I.toolCall&&Pe.renderToolCall){if(!ge)return;ne=Pe.renderToolCall({message:I,defaultRenderer:()=>Ns(I,r),config:r})}else if(I.variant==="approval"&&I.approval&&Pe.renderApproval){if(r.approval===!1)return;ne=Pe.renderApproval({message:I,defaultRenderer:()=>Os(I,r),config:r})}else Pe.renderMessage&&(ne=Pe.renderMessage({message:I,defaultRenderer:()=>{let it=Tr(I,y,rt,r.messageActions,at,{loadingIndicatorRenderer:L,widgetConfig:r});return I.role!=="user"&&js(it,I,r,H),it},config:r}));if(!ne&&I.role==="assistant"&&!I.variant&&r.enableComponentStreaming!==!1&&os(I)){let Gt=ss(I);if(Gt){let jt=rs(Gt,{config:r,message:I,transform:y});if(jt)if(r.wrapComponentDirectiveInBubble!==!1){let $t=document.createElement("div");if($t.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(" "),$t.id=`bubble-${I.id}`,$t.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let sn=document.createElement("div");sn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",sn.innerHTML=y({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),$t.appendChild(sn)}$t.appendChild(jt),ne=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${I.id}`,$t.setAttribute("data-message-id",I.id),$t.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let sn=document.createElement("div");sn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",sn.innerHTML=y({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),$t.appendChild(sn)}$t.appendChild(jt),ne=$t}}}if(!ne)if(I.variant==="reasoning"&&I.reasoning){if(!z)return;ne=$s(I)}else if(I.variant==="tool"&&I.toolCall){if(!ge)return;ne=Ns(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;ne=Os(I,r)}else{let it=(Pt=r.layout)==null?void 0:Pt.messages;it!=null&&it.renderUserMessage&&I.role==="user"?ne=it.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):it!=null&&it.renderAssistantMessage&&I.role==="assistant"?ne=it.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):ne=Tr(I,y,it,r.messageActions,at,{loadingIndicatorRenderer:L,widgetConfig:r}),I.role!=="user"&&ne&&js(ne,I,r,H)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${I.id}`,Ke.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Ke.classList.add("persona-justify-end"),(ne==null?void 0:ne.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(ne),Ql($n,I.id,Te,Ke),S.appendChild(Ke)}),ec($n,P);let V=u.some(I=>I.role==="assistant"&&I.streaming),$=u[u.length-1],se=($==null?void 0:$.role)==="assistant"&&!$.streaming&&$.variant!=="approval";if(Fn&&u.some(I=>I.role==="user")&&!V&&!se){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:sr},Te=s.find(ne=>ne.renderLoadingIndicator),Ee=null;if(Te!=null&&Te.renderLoadingIndicator&&(Ee=Te.renderLoadingIndicator(I)),Ee===null&&((fe=r.loadingIndicator)!=null&&fe.render)&&(Ee=r.loadingIndicator.render(I)),Ee===null&&(Ee=sr()),Ee){let ne=document.createElement("div"),Pe=((ke=r.loadingIndicator)==null?void 0:ke.showBubble)!==!1;ne.className=Pe?["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(" "),ne.setAttribute("data-typing-indicator","true"),ne.appendChild(Ee);let rt=document.createElement("div");rt.className="persona-flex",rt.id="wrapper-typing-indicator",rt.setAttribute("data-wrapper-id","typing-indicator"),rt.appendChild(ne),S.appendChild(rt)}}if(!Fn&&u.length>0){let I=u[u.length-1],Te={config:r,lastMessage:I,messageCount:u.length},Ee=s.find(Pe=>Pe.renderIdleIndicator),ne=null;if(Ee!=null&&Ee.renderIdleIndicator&&(ne=Ee.renderIdleIndicator(Te)),ne===null&&((Ne=r.loadingIndicator)!=null&&Ne.renderIdle)&&(ne=r.loadingIndicator.renderIdle(Te)),ne){let Pe=document.createElement("div"),rt=((Ae=r.loadingIndicator)==null?void 0:Ae.showBubble)!==!1;Pe.className=rt?["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(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(ne);let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id="wrapper-idle-indicator",Ke.setAttribute("data-wrapper-id","idle-indicator"),Ke.appendChild(Pe),S.appendChild(Ke)}}Yl(l,S),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=xo();vo(I)})})},gr=()=>{if(!v)return;let l=Ut(r);w?(de.style.display=l?"flex":"",de.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-95","persona-opacity-0"),ie.classList.add("persona-scale-100","persona-opacity-100"),we?we.element.style.display="none":$e&&($e.style.display="none")):(l?(de.style.display="none",de.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(de.style.display="",de.classList.add("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100"),ie.classList.add("persona-scale-95","persona-opacity-0")),we?we.element.style.display="":$e&&($e.style.display=""))},mt=(l,u="user")=>{if(!v||w===l)return;let y=w;w=l,gr(),w&&(vt(),Vn(!0));let S={open:w,source:u,timestamp:Date.now()};w&&!y?o.emit("widget:opened",S):!w&&y&&o.emit("widget:closed",S),o.emit("widget:state",{open:w,launcherEnabled:v,voiceActive:Ue.active,streaming:H.isStreaming()})},mr=l=>{K.disabled=l,B&&(B.disabled=l),Bn.buttons.forEach(u=>{u.disabled=l}),Ze.dataset.personaComposerStreaming=l?"true":"false",Ze.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},fr=()=>{Ue.active||X&&X.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>fr(),200)});let _r=()=>{var R,L,P,V,$,se,fe,ke,Ne,Ae,I,Te,Ee,ne;Tt.textContent=(L=(R=r.copy)==null?void 0:R.welcomeTitle)!=null?L:"Hello \u{1F44B}",_t.textContent=(V=(P=r.copy)==null?void 0:P.welcomeSubtitle)!=null?V:"Ask anything about your account or products.",X.placeholder=(se=($=r.copy)==null?void 0:$.inputPlaceholder)!=null?se:"How can I help...",(ke=(fe=r.sendButton)==null?void 0:fe.useIcon)!=null&&ke||(K.textContent=(Ae=(Ne=r.copy)==null?void 0:Ne.sendButtonLabel)!=null?Ae:"Send");let u=(Te=(I=r.theme)==null?void 0:I.inputFontFamily)!=null?Te:"sans-serif",y=(ne=(Ee=r.theme)==null?void 0:Ee.inputFontWeight)!=null?ne:"400",S=Pe=>{switch(Pe){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};X.style.fontFamily=S(u),X.style.fontWeight=y};if(r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(u=>({...u,sessionId:l}))}}),H=new Cr(r,{onMessagesChanged(l){Un(be,l,ae),H&&(l.some(R=>R.role==="user")?Bn.render([],H,X,l):Bn.render(r.suggestionChips,H,X,l,r.suggestionChipsConfig)),Vn(!Fn),Co(l);let u=[...l].reverse().find(S=>S.role==="user"),y=Ue.lastUserMessageId;u&&u.id!==y&&(Ue.lastUserMessageId=u.id,o.emit("user:message",u)),Ue.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Dr(l)},onStatusChanged(l){var S;let u=(S=r.statusIndicator)!=null?S:{},y=R=>{var L,P,V,$;return R==="idle"?(L=u.idleText)!=null?L:Vt.idle:R==="connecting"?(P=u.connectingText)!=null?P:Vt.connecting:R==="connected"?(V=u.connectedText)!=null?V:Vt.connected:R==="error"?($=u.errorText)!=null?$:Vt.error:Vt[R]};Ve.textContent=y(l)},onStreamingChanged(l){Fn=l,mr(l),H&&Un(be,H.getMessages(),ae),l||Vn(!0)},onVoiceStatusChanged(l){var u,y;if(((y=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":dn(),So();break;case"speaking":dn(),Ao();break;default:l==="idle"&&H.isBargeInActive()?(dn(),Nn(),B==null||B.setAttribute("aria-label","End voice session")):(Ue.active=!1,dn(),rn("system"),Kt());break}},onArtifactsState(l){Hn=l,hn()}}),Wr.current=H,((Sa=(wa=r.voiceRecognition)==null?void 0:wa.provider)==null?void 0:Sa.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&H.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&H.setSSEEventCallback((l,u)=>{D==null||D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(i=Js(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let jr=l=>{var R;l.preventDefault();let u=X.value.trim(),y=(R=He==null?void 0:He.hasAttachments())!=null?R:!1;if(!u&&!y)return;let S;y&&(S=[],S.push(...He.getContentParts()),u&&S.push(_o(u))),X.value="",X.style.height="auto",H.sendMessage(u,{contentParts:S}),y&&He.clearAttachments()},Vr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),K.click())},Ur=async l=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!He)return;let u=mp(l.clipboardData);u.length!==0&&(l.preventDefault(),await He.handleFiles(u))},qt=null,Qt=!1,Mn=null,Re=null,qr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qn=(l="user")=>{var L,P,V,$,se,fe,ke,Ne;if(Qt||H.isStreaming())return;let u=qr();if(!u)return;qt=new u;let S=(P=((L=r.voiceRecognition)!=null?L:{}).pauseDuration)!=null?P:2e3;qt.continuous=!0,qt.interimResults=!0,qt.lang="en-US";let R=X.value;qt.onresult=Ae=>{let I="",Te="";for(let ne=0;ne<Ae.results.length;ne++){let Pe=Ae.results[ne],rt=Pe[0].transcript;Pe.isFinal?I+=rt+" ":Te=rt}let Ee=R+I+Te;X.value=Ee,Mn&&clearTimeout(Mn),(I||Te)&&(Mn=window.setTimeout(()=>{let ne=X.value.trim();ne&&qt&&Qt&&(cn(),X.value="",X.style.height="auto",H.sendMessage(ne,{viaVoice:!0}))},S))},qt.onerror=Ae=>{Ae.error!=="no-speech"&&cn()},qt.onend=()=>{if(Qt){let Ae=X.value.trim();Ae&&Ae!==R.trim()&&(X.value="",X.style.height="auto",H.sendMessage(Ae,{viaVoice:!0})),cn()}};try{if(qt.start(),Qt=!0,Ue.active=!0,l!=="system"&&(Ue.manuallyDeactivated=!1),rn(l),Kt(),B){let Ae=(V=r.voiceRecognition)!=null?V:{};Re={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:($=Ae.iconName)!=null?$:"mic",iconSize:parseFloat((ke=(fe=Ae.iconSize)!=null?fe:(se=r.sendButton)==null?void 0:se.size)!=null?ke:"40")||24};let I=(Ne=Ae.recordingBackgroundColor)!=null?Ne:"#ef4444",Te=Ae.recordingIconColor,Ee=Ae.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=I,Te){B.style.color=Te;let ne=B.querySelector("svg");ne&&ne.setAttribute("stroke",Te)}Ee&&(B.style.borderColor=Ee),B.setAttribute("aria-label","Stop voice recognition")}}catch{cn("system")}},cn=(l="user")=>{if(Qt){if(Qt=!1,Mn&&(clearTimeout(Mn),Mn=null),qt){try{qt.stop()}catch{}qt=null}if(Ue.active=!1,rn(l),Kt(),B){if(B.classList.remove("persona-voice-recording"),Re){B.style.backgroundColor=Re.backgroundColor,B.style.color=Re.color,B.style.borderColor=Re.borderColor;let u=B.querySelector("svg");u&&u.setAttribute("stroke",Re.color||"currentColor"),Re=null}B.setAttribute("aria-label","Start voice recognition")}}},wo=(l,u)=>{var ne,Pe,rt,Ke,pe,Pt,it,Gt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((ne=l==null?void 0:l.provider)==null?void 0:ne.type)==="runtype";if(!(y||S))return null;let L=h("div","persona-send-button-wrapper"),P=h("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 V=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",$=(rt=u==null?void 0:u.size)!=null?rt:"40px",se=(Ke=l==null?void 0:l.iconSize)!=null?Ke:$,fe=parseFloat(se)||24,ke=(pe=l==null?void 0:l.backgroundColor)!=null?pe:u==null?void 0:u.backgroundColor,Ne=(Pt=l==null?void 0:l.iconColor)!=null?Pt:u==null?void 0:u.textColor;P.style.width=se,P.style.height=se,P.style.minWidth=se,P.style.minHeight=se,P.style.fontSize="18px",P.style.lineHeight="1";let Ae=Ne||"currentColor",I=me(V,fe,Ae,1.5);I?(P.appendChild(I),P.style.color=Ae):(P.textContent="\u{1F3A4}",P.style.color=Ae),ke?P.style.backgroundColor=ke:P.classList.add("persona-bg-persona-primary"),Ne?P.style.color=Ne:!Ne&&!(u!=null&&u.textColor)&&P.classList.add("persona-text-white"),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),L.appendChild(P);let Te=(it=l==null?void 0:l.tooltipText)!=null?it:"Start voice recognition";if(((Gt=l==null?void 0:l.showTooltip)!=null?Gt:!1)&&Te){let jt=h("div","persona-send-button-tooltip");jt.textContent=Te,L.appendChild(jt)}return{micButton:P,micButtonWrapper:L}},hr=()=>{var u,y,S,R,L;if(!B||Re)return;let l=(u=r.voiceRecognition)!=null?u:{};Re={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((L=(R=l.iconSize)!=null?R:(S=r.sendButton)==null?void 0:S.size)!=null?L:"40")||24}},yr=(l,u)=>{var L,P,V,$,se;if(!B)return;let y=B.querySelector("svg");y&&y.remove();let S=(se=Re==null?void 0:Re.iconSize)!=null?se:parseFloat(($=(V=(L=r.voiceRecognition)==null?void 0:L.iconSize)!=null?V:(P=r.sendButton)==null?void 0:P.size)!=null?$:"40")||24,R=me(l,S,u,1.5);R&&B.appendChild(R)},zn=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Nn=()=>{var R,L;if(!B)return;hr();let l=(R=r.voiceRecognition)!=null?R:{},u=(L=l.recordingBackgroundColor)!=null?L:"#ef4444",y=l.recordingIconColor,S=l.recordingBorderColor;if(zn(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=u,y){B.style.color=y;let P=B.querySelector("svg");P&&P.setAttribute("stroke",y)}S&&(B.style.borderColor=S),B.setAttribute("aria-label","Stop voice recognition")},So=()=>{var V,$,se,fe,ke,Ne,Ae,I;if(!B)return;hr();let l=(V=r.voiceRecognition)!=null?V:{},u=H.getVoiceInterruptionMode(),y=($=l.processingIconName)!=null?$:"loader",S=(fe=(se=l.processingIconColor)!=null?se:Re==null?void 0:Re.color)!=null?fe:"",R=(Ne=(ke=l.processingBackgroundColor)!=null?ke:Re==null?void 0:Re.backgroundColor)!=null?Ne:"",L=(I=(Ae=l.processingBorderColor)!=null?Ae:Re==null?void 0:Re.borderColor)!=null?I:"";zn(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=R,B.style.borderColor=L;let P=S||"currentColor";B.style.color=P,yr(y,P),B.setAttribute("aria-label","Processing voice input"),u==="none"&&(B.style.cursor="default")},Ao=()=>{var se,fe,ke,Ne,Ae,I,Te,Ee,ne,Pe,rt,Ke;if(!B)return;hr();let l=(se=r.voiceRecognition)!=null?se:{},u=H.getVoiceInterruptionMode(),y=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",S=(fe=l.speakingIconName)!=null?fe:y,R=(I=l.speakingIconColor)!=null?I:u==="barge-in"?(Ne=(ke=l.recordingIconColor)!=null?ke:Re==null?void 0:Re.color)!=null?Ne:"":(Ae=Re==null?void 0:Re.color)!=null?Ae:"",L=(ne=l.speakingBackgroundColor)!=null?ne:u==="barge-in"?(Te=l.recordingBackgroundColor)!=null?Te:"#ef4444":(Ee=Re==null?void 0:Re.backgroundColor)!=null?Ee:"",P=(Ke=l.speakingBorderColor)!=null?Ke:u==="barge-in"?(Pe=l.recordingBorderColor)!=null?Pe:"":(rt=Re==null?void 0:Re.borderColor)!=null?rt:"";zn(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=L,B.style.borderColor=P;let V=R||"currentColor";B.style.color=V,yr(S,V);let $=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",$),u==="none"&&(B.style.cursor="default"),u==="barge-in"&&B.classList.add("persona-voice-recording")},dn=()=>{var l,u,y;B&&(zn(),Re&&(B.style.backgroundColor=(l=Re.backgroundColor)!=null?l:"",B.style.color=(u=Re.color)!=null?u:"",B.style.borderColor=(y=Re.borderColor)!=null?y:"",yr(Re.iconName,Re.color||"currentColor"),Re=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Jn=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let y=H.getVoiceStatus(),S=H.getVoiceInterruptionMode();if(S==="none"&&(y==="processing"||y==="speaking"))return;if(S==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{Ue.active=!1,Ue.manuallyDeactivated=!0,Kt(),rn("user"),dn()});return}H.toggleVoice().then(()=>{Ue.active=H.isVoiceActive(),Ue.manuallyDeactivated=!H.isVoiceActive(),Kt(),rn("user"),H.isVoiceActive()?Nn():dn()});return}if(Qt){let y=X.value.trim();Ue.manuallyDeactivated=!0,Kt(),cn("user"),y&&(X.value="",X.style.height="auto",H.sendMessage(y))}else Ue.manuallyDeactivated=!1,Kt(),qn("user")};pt=Jn,B&&(B.addEventListener("click",Jn),xt.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),dn()):cn("system"),B&&B.removeEventListener("click",Jn)}));let Eo=o.on("assistant:complete",()=>{Or&&(Ue.active||Ue.manuallyDeactivated||Or==="assistant"&&!Ue.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!Ue.active&&!Ue.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?H.toggleVoice().then(()=>{Ue.active=H.isVoiceActive(),rn("auto"),H.isVoiceActive()&&Nn()}):qn("auto"))},600))});xt.push(Eo);let Q=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});xt.push(Q);let Fe=()=>{mt(!w,"user")},we=null,$e=null;if(v){let l=s.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:r,defaultRenderer:()=>ro(r,Fe).element,onToggle:Fe});u&&($e=u)}$e||(we=ro(r,Fe))}we?e.appendChild(we.element):$e&&e.appendChild($e),gr(),Bn.render(r.suggestionChips,H,X,void 0,r.suggestionChipsConfig),_r(),mr(H.isStreaming()),Vn(!0),yo(),x&&(v?w&&setTimeout(()=>fr(),200):setTimeout(()=>fr(),0));let vt=()=>{var $,se,fe,ke,Ne,Ae,I,Te,Ee,ne,Pe,rt,Ke;let l=Ut(r),u=(se=($=r.launcher)==null?void 0:$.sidebarMode)!=null?se:!1,y=l||u||((ke=(fe=r.launcher)==null?void 0:fe.fullHeight)!=null?ke:!1),S=(Ne=e.ownerDocument.defaultView)!=null?Ne:window,R=(I=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?I:!0,L=(Ee=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?Ee:640,P=S.innerWidth<=L;if(R&&P&&v){_n(),On(e,r);return}if(N&&(N=!1,_n(),On(e,r)),!v&&!l){ie.style.height="",ie.style.width="";return}if(!u&&!l){let pe=(Pe=(ne=r==null?void 0:r.launcher)==null?void 0:ne.width)!=null?Pe:r==null?void 0:r.launcherWidth,Pt=pe!=null?pe:"min(400px, calc(100vw - 24px))";ie.style.width=Pt,ie.style.maxWidth=Pt}if(Dn(),!y){let pe=S.innerHeight,Pt=64,it=(Ke=(rt=r.launcher)==null?void 0:rt.heightOffset)!=null?Ke:0,Gt=Math.max(200,pe-Pt),jt=Math.min(640,Gt),zt=Math.max(200,jt-it);ie.style.height=`${zt}px`}};vt();let Ot=(Aa=e.ownerDocument.defaultView)!=null?Aa:window;Ot.addEventListener("resize",vt),xt.push(()=>Ot.removeEventListener("resize",vt)),jn=G.scrollTop;let Ct=()=>{let l=G.scrollTop,u=G.scrollHeight,y=G.clientHeight,S=u-l-y,R=Math.abs(l-jn);if(jn=l,!pr&&!(R<=ho)){if(!Sn&&S<Nr){En=!1,Sn=!0;return}Sn&&S>Nr&&(En=!0,dr=Date.now()+fo,Sn=!1)}};G.addEventListener("scroll",Ct,{passive:!0}),xt.push(()=>G.removeEventListener("scroll",Ct)),xt.push(()=>{An&&cancelAnimationFrame(An)});let b=()=>{ce&&(bn&&(ce.removeEventListener("click",bn),bn=null),v?(ce.style.display="",bn=()=>{mt(!1,"user")},ce.addEventListener("click",bn)):ce.style.display="none")};b(),(()=>{let{clearChatButton:l}=qe;l&&l.addEventListener("click",()=>{H.clearMessages(),$n.clear();try{localStorage.removeItem(Ir),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ir}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ir)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},C.syncFromMetadata(),D==null||D.clear(),U==null||U.update()})})(),We&&We.addEventListener("submit",jr),X==null||X.addEventListener("keydown",Vr),X==null||X.addEventListener("paste",Ur),xt.push(()=>{We&&We.removeEventListener("submit",jr),X==null||X.removeEventListener("keydown",Vr),X==null||X.removeEventListener("paste",Ur)}),xt.push(()=>{H.cancel()}),we?xt.push(()=>{we==null||we.destroy()}):$e&&xt.push(()=>{$e==null||$e.remove()});let T={update(l){var Ia,Wa,Ra,Ha,Ba,Fa,$a,Na,Oa,Da,_a,ja,Va,Ua,qa,za,Ja,Ka,Ya,Ga,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Pi,Ii,Wi,Ri,Hi,Bi,Fi,$i,Ni,Oi,Di,_i,ji,Vi,Ui,qi,zi,Ji,Ki,Yi,Gi,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,gl,ml,fl,hl,yl;let u=r.toolCall,y=r.messageActions,S=(Ia=r.layout)==null?void 0:Ia.messages,R=r.colorScheme,L=r.loadingIndicator,P=r.iterationDisplay;r={...r,...l},_n(),On(e,r),Zo(e,r),Qo(e,r),hn(),r.colorScheme!==R&&Br();let V=lo.getForInstance(r.plugins);s.length=0,s.push(...V),v=(Ra=(Wa=r.launcher)==null?void 0:Wa.enabled)!=null?Ra:!0,E=(Ba=(Ha=r.launcher)==null?void 0:Ha.autoExpand)!=null?Ba:!1,z=($a=(Fa=r.features)==null?void 0:Fa.showReasoning)!=null?$a:!0,ge=(Oa=(Na=r.features)==null?void 0:Na.showToolCalls)!=null?Oa:!0;let $=Ie;if(Ie=(_a=(Da=r.features)==null?void 0:Da.showEventStreamToggle)!=null?_a:!1,Ie&&!$){if(D||(ee=new so(ye),D=new oo(te,ee),ee.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),H.setSSEEventCallback((O,Ye)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:O,timestamp:Date.now(),payload:JSON.stringify(Ye)})})),!ue&&je){let O=(Va=(ja=r.features)==null?void 0:ja.eventStream)==null?void 0:Va.classNames,Ye="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(O!=null&&O.toggleButton?" "+O.toggleButton:"");ue=h("button",Ye),ue.style.width="28px",ue.style.height="28px",ue.type="button",ue.setAttribute("aria-label","Event Stream"),ue.title="Event Stream";let ft=me("activity","18px","currentColor",1.5);ft&&ue.appendChild(ft);let Oe=qe.clearChatButtonWrapper,et=qe.closeButtonWrapper,It=Oe||et;It&&It.parentNode===je?je.insertBefore(ue,It):je.appendChild(ue),ue.addEventListener("click",()=>{oe?Be():Ce()})}}else!Ie&&$&&(Be(),ue&&(ue.remove(),ue=null),D==null||D.clear(),ee==null||ee.destroy(),D=null,ee=null);if(((Ua=r.launcher)==null?void 0:Ua.enabled)===!1&&we&&(we.destroy(),we=null),((qa=r.launcher)==null?void 0:qa.enabled)===!1&&$e&&($e.remove(),$e=null),((za=r.launcher)==null?void 0:za.enabled)!==!1&&!we&&!$e){let O=s.find(Ye=>Ye.renderLauncher);if(O!=null&&O.renderLauncher){let Ye=O.renderLauncher({config:r,defaultRenderer:()=>ro(r,Fe).element,onToggle:Fe});Ye&&($e=Ye,e.appendChild($e))}$e||(we=ro(r,Fe),e.appendChild(we.element))}we&&we.update(r),Me&&((Ja=r.launcher)==null?void 0:Ja.title)!==void 0&&(Me.textContent=r.launcher.title),nt&&((Ka=r.launcher)==null?void 0:Ka.subtitle)!==void 0&&(nt.textContent=r.launcher.subtitle);let se=(Ya=r.layout)==null?void 0:Ya.header;if((se==null?void 0:se.layout)!==M&&je){let O=se?Ar(r,se,{showClose:v,onClose:()=>mt(!1,"user")}):Pn({config:r,showClose:v,onClose:()=>mt(!1,"user")});je.replaceWith(O.header),je=O.header,Je=O.iconHolder,Me=O.headerTitle,nt=O.headerSubtitle,ce=O.closeButton,M=se==null?void 0:se.layout}else if(se&&(Je&&(Je.style.display=se.showIcon===!1?"none":""),Me&&(Me.style.display=se.showTitle===!1?"none":""),nt&&(nt.style.display=se.showSubtitle===!1?"none":""),ce&&(ce.style.display=se.showCloseButton===!1?"none":""),qe.clearChatButtonWrapper)){let O=se.showClearChat;if(O!==void 0){qe.clearChatButtonWrapper.style.display=O?"":"none";let{closeButtonWrapper:Ye}=qe;Ye&&!Ye.classList.contains("persona-absolute")&&(O?Ye.classList.remove("persona-ml-auto"):Ye.classList.add("persona-ml-auto"))}}let ke=((Ga=r.layout)==null?void 0:Ga.showHeader)!==!1;je&&(je.style.display=ke?"":"none");let Ne=((Xa=r.layout)==null?void 0:Xa.showFooter)!==!1;Ze&&(Ze.style.display=Ne?"":"none"),v!==q?v?mt(E,"auto"):(w=!0,gr()):E!==k&&mt(E,"auto"),k=E,q=v,vt(),b();let Te=JSON.stringify(l.toolCall)!==JSON.stringify(u),Ee=JSON.stringify(r.messageActions)!==JSON.stringify(y),ne=JSON.stringify((Za=r.layout)==null?void 0:Za.messages)!==JSON.stringify(S),Pe=((Qa=r.loadingIndicator)==null?void 0:Qa.render)!==(L==null?void 0:L.render)||((ei=r.loadingIndicator)==null?void 0:ei.renderIdle)!==(L==null?void 0:L.renderIdle)||((ti=r.loadingIndicator)==null?void 0:ti.showBubble)!==(L==null?void 0:L.showBubble),rt=r.iterationDisplay!==P;(Te||Ee||ne||Pe||rt)&&H&&(Fr++,Un(be,H.getMessages(),ae));let pe=(ni=r.launcher)!=null?ni:{},Pt=(ri=pe.headerIconHidden)!=null?ri:!1,it=(si=(oi=r.layout)==null?void 0:oi.header)==null?void 0:si.showIcon,Gt=Pt||it===!1,jt=pe.headerIconName,zt=(ai=pe.headerIconSize)!=null?ai:"48px";if(Je){let O=j.querySelector(".persona-border-b-persona-divider"),Ye=O==null?void 0:O.querySelector(".persona-flex-col");if(Gt)Je.style.display="none",O&&Ye&&!O.contains(Ye)&&O.insertBefore(Ye,O.firstChild);else{if(Je.style.display="",Je.style.height=zt,Je.style.width=zt,O&&Ye&&(O.contains(Je)?Je.nextSibling!==Ye&&(Je.remove(),O.insertBefore(Je,Ye)):O.insertBefore(Je,Ye)),jt){let Oe=parseFloat(zt)||24,et=me(jt,Oe*.6,"#ffffff",2);et?Je.replaceChildren(et):Je.textContent=(ii=pe.agentIconText)!=null?ii:"\u{1F4AC}"}else if(pe.iconUrl){let Oe=Je.querySelector("img");if(Oe)Oe.src=pe.iconUrl,Oe.style.height=zt,Oe.style.width=zt;else{let et=document.createElement("img");et.src=pe.iconUrl,et.alt="",et.className="persona-rounded-xl persona-object-cover",et.style.height=zt,et.style.width=zt,Je.replaceChildren(et)}}else{let Oe=Je.querySelector("svg"),et=Je.querySelector("img");(Oe||et)&&Je.replaceChildren(),Je.textContent=(li=pe.agentIconText)!=null?li:"\u{1F4AC}"}let ft=Je.querySelector("img");ft&&(ft.style.height=zt,ft.style.width=zt)}}let $t=(di=(ci=r.layout)==null?void 0:ci.header)==null?void 0:di.showTitle,sn=(ui=(pi=r.layout)==null?void 0:pi.header)==null?void 0:ui.showSubtitle;if(Me&&(Me.style.display=$t===!1?"none":""),nt&&(nt.style.display=sn===!1?"none":""),ce){((mi=(gi=r.layout)==null?void 0:gi.header)==null?void 0:mi.showCloseButton)===!1?ce.style.display="none":ce.style.display="";let Ye=(fi=pe.closeButtonSize)!=null?fi:"32px",ft=(hi=pe.closeButtonPlacement)!=null?hi:"inline";ce.style.height=Ye,ce.style.width=Ye;let{closeButtonWrapper:Oe}=qe,et=ft==="top-right",It=Oe==null?void 0:Oe.classList.contains("persona-absolute");if(Oe&&et!==It)if(Oe.remove(),et)Oe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(Oe);else{let Ge=(bi=(yi=pe.clearChat)==null?void 0:yi.placement)!=null?bi:"inline",Nt=(vi=(xi=pe.clearChat)==null?void 0:xi.enabled)!=null?vi:!0;Oe.className=Nt&&Ge==="inline"?"":"persona-ml-auto";let Xt=j.querySelector(".persona-border-b-persona-divider");Xt&&Xt.appendChild(Oe)}if(pe.closeButtonColor?(ce.style.color=pe.closeButtonColor,ce.classList.remove("persona-text-persona-muted")):(ce.style.color="",ce.classList.add("persona-text-persona-muted")),pe.closeButtonBackgroundColor?(ce.style.backgroundColor=pe.closeButtonBackgroundColor,ce.classList.remove("hover:persona-bg-gray-100")):(ce.style.backgroundColor="",ce.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let Ge=pe.closeButtonBorderWidth||"0px",Nt=pe.closeButtonBorderColor||"transparent";ce.style.border=`${Ge} solid ${Nt}`,ce.classList.remove("persona-border-none")}else ce.style.border="",ce.classList.add("persona-border-none");pe.closeButtonBorderRadius?(ce.style.borderRadius=pe.closeButtonBorderRadius,ce.classList.remove("persona-rounded-full")):(ce.style.borderRadius="",ce.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(ce.style.paddingLeft=pe.closeButtonPaddingX,ce.style.paddingRight=pe.closeButtonPaddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),pe.closeButtonPaddingY?(ce.style.paddingTop=pe.closeButtonPaddingY,ce.style.paddingBottom=pe.closeButtonPaddingY):(ce.style.paddingTop="",ce.style.paddingBottom="");let Dt=(Ci=pe.closeButtonIconName)!=null?Ci:"x",en=(wi=pe.closeButtonIconText)!=null?wi:"\xD7";ce.innerHTML="";let Jt=me(Dt,"20px",pe.closeButtonColor||"",2);Jt?ce.appendChild(Jt):ce.textContent=en;let St=(Si=pe.closeButtonTooltipText)!=null?Si:"Close chat",tn=(Ai=pe.closeButtonShowTooltip)!=null?Ai:!0;if(ce.setAttribute("aria-label",St),Oe&&(Oe._cleanupTooltip&&(Oe._cleanupTooltip(),delete Oe._cleanupTooltip),tn&&St)){let Ge=null,Nt=()=>{if(Ge||!ce)return;let Gn=ce.ownerDocument,Gr=Gn.body;if(!Gr)return;Ge=vn(Gn,"div","persona-clear-chat-tooltip"),Ge.textContent=St;let Xr=vn(Gn,"div");Xr.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(Xr);let Xn=ce.getBoundingClientRect();Ge.style.position="fixed",Ge.style.left=`${Xn.left+Xn.width/2}px`,Ge.style.top=`${Xn.top-8}px`,Ge.style.transform="translate(-50%, -100%)",Gr.appendChild(Ge)},Xt=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};Oe.addEventListener("mouseenter",Nt),Oe.addEventListener("mouseleave",Xt),ce.addEventListener("focus",Nt),ce.addEventListener("blur",Xt),Oe._cleanupTooltip=()=>{Xt(),Oe&&(Oe.removeEventListener("mouseenter",Nt),Oe.removeEventListener("mouseleave",Xt)),ce&&(ce.removeEventListener("focus",Nt),ce.removeEventListener("blur",Xt))}}}let{clearChatButton:_e,clearChatButtonWrapper:yt}=qe;if(_e){let O=(Ei=pe.clearChat)!=null?Ei:{},Ye=(Ti=O.enabled)!=null?Ti:!0,ft=(ki=(Mi=r.layout)==null?void 0:Mi.header)==null?void 0:ki.showClearChat,Oe=ft!==void 0?ft:Ye,et=(Li=O.placement)!=null?Li:"inline";if(yt){yt.style.display=Oe?"":"none";let{closeButtonWrapper:It}=qe;It&&!It.classList.contains("persona-absolute")&&(Oe?It.classList.remove("persona-ml-auto"):It.classList.add("persona-ml-auto"));let Dt=et==="top-right",en=yt.classList.contains("persona-absolute");if(Dt!==en&&Oe){if(yt.remove(),Dt)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",j.style.position="relative",j.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let St=j.querySelector(".persona-border-b-persona-divider"),tn=qe.closeButtonWrapper;St&&tn&&tn.parentElement===St?St.insertBefore(yt,tn):St&&St.appendChild(yt)}let Jt=qe.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(Dt?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(Oe){let It=(Pi=O.size)!=null?Pi:"32px";_e.style.height=It,_e.style.width=It;let Dt=(Ii=O.iconName)!=null?Ii:"refresh-cw",en=(Wi=O.iconColor)!=null?Wi:"";_e.innerHTML="";let Jt=me(Dt,"20px",en||"",2);if(Jt&&_e.appendChild(Jt),en?(_e.style.color=en,_e.classList.remove("persona-text-persona-muted")):(_e.style.color="",_e.classList.add("persona-text-persona-muted")),O.backgroundColor?(_e.style.backgroundColor=O.backgroundColor,_e.classList.remove("hover:persona-bg-gray-100")):(_e.style.backgroundColor="",_e.classList.add("hover:persona-bg-gray-100")),O.borderWidth||O.borderColor){let Ge=O.borderWidth||"0px",Nt=O.borderColor||"transparent";_e.style.border=`${Ge} solid ${Nt}`,_e.classList.remove("persona-border-none")}else _e.style.border="",_e.classList.add("persona-border-none");O.borderRadius?(_e.style.borderRadius=O.borderRadius,_e.classList.remove("persona-rounded-full")):(_e.style.borderRadius="",_e.classList.add("persona-rounded-full")),O.paddingX?(_e.style.paddingLeft=O.paddingX,_e.style.paddingRight=O.paddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),O.paddingY?(_e.style.paddingTop=O.paddingY,_e.style.paddingBottom=O.paddingY):(_e.style.paddingTop="",_e.style.paddingBottom="");let St=(Ri=O.tooltipText)!=null?Ri:"Clear chat",tn=(Hi=O.showTooltip)!=null?Hi:!0;if(_e.setAttribute("aria-label",St),yt&&(yt._cleanupTooltip&&(yt._cleanupTooltip(),delete yt._cleanupTooltip),tn&&St)){let Ge=null,Nt=()=>{if(Ge||!_e)return;let Gn=_e.ownerDocument,Gr=Gn.body;if(!Gr)return;Ge=vn(Gn,"div","persona-clear-chat-tooltip"),Ge.textContent=St;let Xr=vn(Gn,"div");Xr.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(Xr);let Xn=_e.getBoundingClientRect();Ge.style.position="fixed",Ge.style.left=`${Xn.left+Xn.width/2}px`,Ge.style.top=`${Xn.top-8}px`,Ge.style.transform="translate(-50%, -100%)",Gr.appendChild(Ge)},Xt=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};yt.addEventListener("mouseenter",Nt),yt.addEventListener("mouseleave",Xt),_e.addEventListener("focus",Nt),_e.addEventListener("blur",Xt),yt._cleanupTooltip=()=>{Xt(),yt&&(yt.removeEventListener("mouseenter",Nt),yt.removeEventListener("mouseleave",Xt)),_e&&(_e.removeEventListener("focus",Nt),_e.removeEventListener("blur",Xt))}}}}let To=r.actionParsers&&r.actionParsers.length?r.actionParsers:[co],Mo=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ar.message,ar.messageAndClick];C=po({parsers:To,handlers:Mo,getSessionMetadata:g,updateSessionMetadata:p,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),ae=Sc(r,C,Y),H.updateConfig(r),Un(be,H.getMessages(),ae),Bn.render(r.suggestionChips,H,X,void 0,r.suggestionChipsConfig),_r(),mr(H.isStreaming());let ko=((Bi=r.voiceRecognition)==null?void 0:Bi.enabled)===!0,Lo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Po=(($i=(Fi=r.voiceRecognition)==null?void 0:Fi.provider)==null?void 0:$i.type)==="runtype";if(ko&&(Lo||Po))if(!B||!Z){let O=wo(r.voiceRecognition,r.sendButton);O&&(B=O.micButton,Z=O.micButtonWrapper,Mt.insertBefore(Z,tt),B.addEventListener("click",Jn),B.disabled=H.isStreaming())}else{let O=(Ni=r.voiceRecognition)!=null?Ni:{},Ye=(Oi=r.sendButton)!=null?Oi:{},ft=(Di=O.iconName)!=null?Di:"mic",Oe=(_i=Ye.size)!=null?_i:"40px",et=(ji=O.iconSize)!=null?ji:Oe,It=parseFloat(et)||24;B.style.width=et,B.style.height=et,B.style.minWidth=et,B.style.minHeight=et;let Dt=(Ui=(Vi=O.iconColor)!=null?Vi:Ye.textColor)!=null?Ui:"currentColor";B.innerHTML="";let en=me(ft,It,Dt,2);en?B.appendChild(en):B.textContent="\u{1F3A4}";let Jt=(qi=O.backgroundColor)!=null?qi:Ye.backgroundColor;Jt?(B.style.backgroundColor=Jt,B.classList.remove("persona-bg-persona-primary")):(B.style.backgroundColor="",B.classList.add("persona-bg-persona-primary")),Dt?(B.style.color=Dt,B.classList.remove("persona-text-white")):!Dt&&!Ye.textColor&&(B.style.color="",B.classList.add("persona-text-white")),O.borderWidth?(B.style.borderWidth=O.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),O.borderColor?B.style.borderColor=O.borderColor:B.style.borderColor="",O.paddingX?(B.style.paddingLeft=O.paddingX,B.style.paddingRight=O.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),O.paddingY?(B.style.paddingTop=O.paddingY,B.style.paddingBottom=O.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let St=Z==null?void 0:Z.querySelector(".persona-send-button-tooltip"),tn=(zi=O.tooltipText)!=null?zi:"Start voice recognition";if(((Ji=O.showTooltip)!=null?Ji:!1)&&tn)if(St)St.textContent=tn,St.style.display="";else{let Nt=document.createElement("div");Nt.className="persona-send-button-tooltip",Nt.textContent=tn,Z==null||Z.insertBefore(Nt,B)}else St&&(St.style.display="none");Z.style.display="",B.disabled=H.isStreaming()}else B&&Z&&(Z.style.display="none",((Yi=(Ki=r.voiceRecognition)==null?void 0:Ki.provider)==null?void 0:Yi.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():Qt&&cn());if(((Gi=r.attachments)==null?void 0:Gi.enabled)===!0)if(!_||!J){let O=(Xi=r.attachments)!=null?Xi:{},ft=(Qi=((Zi=r.sendButton)!=null?Zi:{}).size)!=null?Qi:"40px";Le||(Le=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Le.style.display="none",We.insertBefore(Le,X)),xe||(xe=document.createElement("input"),xe.type="file",xe.accept=((el=O.allowedTypes)!=null?el:Ln).join(","),xe.multiple=((tl=O.maxFiles)!=null?tl:4)>1,xe.style.display="none",xe.setAttribute("aria-label","Attach files"),We.insertBefore(xe,X)),_=h("div","persona-send-button-wrapper"),J=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),J.type="button",J.setAttribute("aria-label",(nl=O.buttonTooltipText)!=null?nl:"Attach file");let Oe=(rl=O.buttonIconName)!=null?rl:"paperclip",et=ft,It=parseFloat(et)||40,Dt=Math.round(It*.6);J.style.width=et,J.style.height=et,J.style.minWidth=et,J.style.minHeight=et,J.style.fontSize="18px",J.style.lineHeight="1",J.style.backgroundColor="transparent",J.style.color="var(--persona-primary, #111827)",J.style.border="none",J.style.borderRadius="6px",J.style.transition="background-color 0.15s ease",J.addEventListener("mouseenter",()=>{J.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),J.addEventListener("mouseleave",()=>{J.style.backgroundColor="transparent"});let en=me(Oe,Dt,"currentColor",1.5);en?J.appendChild(en):J.textContent="\u{1F4CE}",J.addEventListener("click",tn=>{tn.preventDefault(),xe==null||xe.click()}),_.appendChild(J);let Jt=(ol=O.buttonTooltipText)!=null?ol:"Attach file",St=h("div","persona-send-button-tooltip");St.textContent=Jt,_.appendChild(St),Ht.append(_),!He&&xe&&Le&&(He=rr.fromConfig(O),He.setPreviewsContainer(Le),xe.addEventListener("change",async()=>{He&&(xe!=null&&xe.files)&&(await He.handleFileSelect(xe.files),xe.value="")}))}else{_.style.display="";let O=(sl=r.attachments)!=null?sl:{};xe&&(xe.accept=((al=O.allowedTypes)!=null?al:Ln).join(","),xe.multiple=((il=O.maxFiles)!=null?il:4)>1),He&&He.updateConfig({allowedTypes:O.allowedTypes,maxFileSize:O.maxFileSize,maxFiles:O.maxFiles})}else _&&(_.style.display="none"),He&&He.clearAttachments();let Et=(ll=r.sendButton)!=null?ll:{},Io=(cl=Et.useIcon)!=null?cl:!1,zr=(dl=Et.iconText)!=null?dl:"\u2191",Kn=Et.iconName,Yn=(pl=Et.tooltipText)!=null?pl:"Send message",Qc=(ul=Et.showTooltip)!=null?ul:!1,Jr=(gl=Et.size)!=null?gl:"40px",Wo=Et.backgroundColor,xn=Et.textColor;if(Io){if(K.style.width=Jr,K.style.height=Jr,K.style.minWidth=Jr,K.style.minHeight=Jr,K.style.fontSize="18px",K.style.lineHeight="1",K.innerHTML="",Kn){let O=parseFloat(Jr)||24,Ye=xn&&typeof xn=="string"&&xn.trim()?xn.trim():"currentColor",ft=me(Kn,O,Ye,2);ft?(K.appendChild(ft),K.style.color=Ye):(K.textContent=zr,xn?K.style.color=xn:K.classList.add("persona-text-white"))}else K.textContent=zr,xn?K.style.color=xn:K.classList.add("persona-text-white");K.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wo?(K.style.backgroundColor=Wo,K.classList.remove("persona-bg-persona-primary")):K.classList.add("persona-bg-persona-primary")}else K.textContent=(fl=(ml=r.copy)==null?void 0:ml.sendButtonLabel)!=null?fl:"Send",K.style.width="",K.style.height="",K.style.minWidth="",K.style.minHeight="",K.style.fontSize="",K.style.lineHeight="",K.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",Wo?(K.style.backgroundColor=Wo,K.classList.remove("persona-bg-persona-accent")):K.classList.add("persona-bg-persona-accent"),xn?K.style.color=xn:K.classList.add("persona-text-white");Et.borderWidth?(K.style.borderWidth=Et.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),Et.borderColor?K.style.borderColor=Et.borderColor:K.style.borderColor="",Et.paddingX?(K.style.paddingLeft=Et.paddingX,K.style.paddingRight=Et.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),Et.paddingY?(K.style.paddingTop=Et.paddingY,K.style.paddingBottom=Et.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Kr=tt==null?void 0:tt.querySelector(".persona-send-button-tooltip");if(Qc&&Yn)if(Kr)Kr.textContent=Yn,Kr.style.display="";else{let O=document.createElement("div");O.className="persona-send-button-tooltip",O.textContent=Yn,tt==null||tt.insertBefore(O,K)}else Kr&&(Kr.style.display="none");let Yr=(hl=r.statusIndicator)!=null?hl:{},ed=(yl=Yr.visible)!=null?yl:!0;if(Ve.style.display=ed?"":"none",H){let O=H.getStatus(),Ye=ft=>{var Oe,et,It,Dt;return ft==="idle"?(Oe=Yr.idleText)!=null?Oe:Vt.idle:ft==="connecting"?(et=Yr.connectingText)!=null?et:Vt.connecting:ft==="connected"?(It=Yr.connectedText)!=null?It:Vt.connected:ft==="error"?(Dt=Yr.errorText)!=null?Dt:Vt.error:Vt[ft]};Ve.textContent=Ye(O)}},open(){v&&mt(!0,"api")},close(){v&&mt(!1,"api")},toggle(){v&&mt(!w,"api")},clearChat(){ln=!1,H.clearMessages(),$n.clear();try{localStorage.removeItem(Ir),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ir}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ir)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let u=a.clear();u instanceof Promise&&u.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}i={},C.syncFromMetadata(),D==null||D.clear(),U==null||U.update()},setMessage(l){return!X||H.isStreaming()?!1:(!w&&v&&mt(!0,"system"),X.value=l,X.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let u=(l==null?void 0:l.trim())||X.value.trim();return u?(!w&&v&&mt(!0,"system"),X.value="",X.style.height="auto",H.sendMessage(u),!0):!1},startVoiceRecognition(){var u,y;return H.isStreaming()?!1:((y=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!w&&v&&mt(!0,"system"),Ue.manuallyDeactivated=!1,Kt(),H.toggleVoice().then(()=>{Ue.active=H.isVoiceActive(),rn("user"),H.isVoiceActive()&&Nn()})),!0):Qt?!0:qr()?(!w&&v&&mt(!0,"system"),Ue.manuallyDeactivated=!1,Kt(),qn("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{Ue.active=!1,Ue.manuallyDeactivated=!0,Kt(),rn("user"),dn()}),!0):!1:Qt?(Ue.manuallyDeactivated=!0,Kt(),cn("user"),!0):!1},injectMessage(l){return!w&&v&&mt(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!w&&v&&mt(!0,"system");let u=H.injectAssistantMessage(l);return F&&(F=!1,re&&(clearTimeout(re),re=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),u},injectUserMessage(l){return!w&&v&&mt(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!w&&v&&mt(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!w&&v&&mt(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!w&&v&&mt(!0,"system"),H.injectTestEvent(l)},async connectStream(l,u){return H.connectStream(l,u)},__pushEventStreamEvent(l){D&&D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!Ie||!D||Ce()},hideEventStream(){oe&&Be()},isEventStreamVisible(){return oe},showArtifacts(){an(r)&&(ln=!1,hn(),Qe==null||Qe.setMobileOpen(!0))},hideArtifacts(){an(r)&&(ln=!0,hn())},upsertArtifact(l){return an(r)?(ln=!1,H.upsertArtifact(l)):null},selectArtifact(l){an(r)&&H.selectArtifact(l)},clearArtifacts(){an(r)&&H.clearArtifacts()},focusInput(){return v&&!w||!X?!1:(X.focus(),!0)},async resolveApproval(l,u){let S=H.getMessages().find(R=>{var L;return R.variant==="approval"&&((L=R.approval)==null?void 0:L.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(S.approval,u)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){p(l)},on(l,u){return o.on(l,u)},off(l,u){o.off(l,u)},isOpen(){return v&&w},isVoiceActive(){return Ue.active},getState(){return{open:v&&w,launcherEnabled:v,voiceActive:Ue.active,streaming:H.isStreaming()}},showCSATFeedback(l){!w&&v&&mt(!0,"system");let u=be.querySelector(".persona-feedback-container");u&&u.remove();let y=as({onSubmit:async(S,R)=>{var L;H.isClientTokenMode()&&await H.submitCSATFeedback(S,R),(L=l==null?void 0:l.onSubmit)==null||L.call(l,S,R)},onDismiss:l==null?void 0:l.onDismiss,...l});be.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!w&&v&&mt(!0,"system");let u=be.querySelector(".persona-feedback-container");u&&u.remove();let y=is({onSubmit:async(S,R)=>{var L;H.isClientTokenMode()&&await H.submitNPSFeedback(S,R),(L=l==null?void 0:l.onSubmit)==null||L.call(l,S,R)},onDismiss:l==null?void 0:l.onDismiss,...l});be.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return H.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return H.submitNPSFeedback(l,u)},destroy(){xt.forEach(l=>l()),de.remove(),we==null||we.destroy(),$e==null||$e.remove(),bn&&ce.removeEventListener("click",bn)}};if((((Ea=t==null?void 0:t.debugTools)!=null?Ea:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:T,getMessages:T.getMessages,getStatus:T.getStatus,getMetadata:T.getPersistentMetadata,updateMetadata:T.updatePersistentMetadata,clearHistory:()=>T.clearChat(),setVoiceActive:y=>y?T.startVoiceRecognition():T.stopVoiceRecognition()};window.AgentWidgetBrowser=u,xt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.focusInput()};if(window.addEventListener("persona:focusInput",u),xt.push(()=>{window.removeEventListener("persona:focusInput",u)}),Ie){let V=se=>{let fe=se.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===l)&&T.showEventStream()},$=se=>{let fe=se.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===l)&&T.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",$),xt.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",$)})}let y=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.showArtifacts()},S=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.hideArtifacts()},R=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==l||$!=null&&$.artifact&&T.upsertArtifact($.artifact)},L=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==l||typeof($==null?void 0:$.id)=="string"&&T.selectArtifact($.id)},P=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",S),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",P),xt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",S),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",P)})}let W=fp(r.persistState);if(W&&v){let l=hp(W.storage),u=`${W.keyPrefix}widget-open`,y=`${W.keyPrefix}widget-voice`,S=`${W.keyPrefix}widget-voice-mode`;if(l){let R=((Ta=W.persist)==null?void 0:Ta.openState)&&l.getItem(u)==="true",L=((Ma=W.persist)==null?void 0:Ma.voiceState)&&l.getItem(y)==="true",P=((ka=W.persist)==null?void 0:ka.voiceState)&&l.getItem(S)==="true";if(R&&setTimeout(()=>{T.open(),setTimeout(()=>{var V;if(L||P)T.startVoiceRecognition();else if((V=W.persist)!=null&&V.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0),(La=W.persist)!=null&&La.openState&&(o.on("widget:opened",()=>{l.setItem(u,"true")}),o.on("widget:closed",()=>{l.setItem(u,"false")})),(Pa=W.persist)!=null&&Pa.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(S,V.viaVoice?"true":"false")})),W.clearOnChatClear){let V=()=>{l.removeItem(u),l.removeItem(y),l.removeItem(S)},$=()=>V();window.addEventListener("persona:clear-chat",$),xt.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}return T};var Ac=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Ks=(e,n,t,r,s,o)=>{let a=Sr(s),i=o?a.width:a.collapsedWidth;e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=a.side,e.dataset.personaDockOpen=o?"true":"false",e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto",n.style.minWidth="0",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.flex=`0 0 ${i}`,t.style.width=i,t.style.maxWidth=i,t.style.minWidth=i,t.style.minHeight="0",t.style.position="relative",t.style.overflow="visible",t.style.transition="width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto",a.side==="left"?e.firstElementChild!==t&&e.replaceChildren(t,n):e.lastElementChild!==t&&e.replaceChildren(n,t)},yp=(e,n)=>{let t=e.ownerDocument.createElement("div");return Ac(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Ac(t,r)},destroy(){t.remove()}}},bp=(e,n)=>{var p,f,m,C;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("aside"),c=t.createElement("div"),g=(f=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)==null||f?(C=(m=n==null?void 0:n.launcher)==null?void 0:m.autoExpand)!=null?C:!1:!0;return i.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),r.insertBefore(a,e),i.appendChild(e),a.appendChild(i),a.appendChild(d),Ks(a,i,d,c,n,g),{mode:"docked",host:c,shell:a,syncWidgetState(v){let E=v.launcherEnabled?v.open:!0;g!==E&&(g=E,Ks(a,i,d,c,n,g))},updateConfig(v){var E,x;n=v,((x=(E=n==null?void 0:n.launcher)==null?void 0:E.enabled)!=null?x:!0)===!1&&(g=!0),Ks(a,i,d,c,n,g)},destroy(){r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},uo=(e,n)=>Ut(n)?bp(e,n):yp(e,n);var Ys={},xp=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},vp=()=>{try{if(typeof Ys!="undefined"&&Ys.url)return new URL("../widget.css",Ys.url).href}catch{}return null},Ec=(e,n)=>{let t=vp(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},Gs=e=>{var E;let n=xp(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=uo(n,s),a,i=[],d=(x,k)=>{var w,F;let M=!((F=(w=k==null?void 0:k.launcher)==null?void 0:w.enabled)!=null?F:!0)||Ut(k),N=r.createElement("div");if(N.id="persona-root",M&&(N.style.height="100%",N.style.display="flex",N.style.flexDirection="column",N.style.flex="1",N.style.minHeight="0"),t){let re=x.attachShadow({mode:"open"});re.appendChild(N),Ec(re,r)}else x.appendChild(N),Ec(x,r);return n.id&&N.setAttribute("data-persona-instance",n.id),N},c=()=>{o.syncWidgetState(a.getState())},g=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(o.host,s);a=ls(x,s,{debugTools:e.debugTools}),g()},f=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(E=e.onReady)==null||E.call(e);let m=x=>{f(),o.destroy(),o=uo(n,x),s=x,p()},C={update(x){var N,w,F,re,Y,ae;let k={...s,...x,launcher:{...(N=s==null?void 0:s.launcher)!=null?N:{},...(w=x==null?void 0:x.launcher)!=null?w:{},dock:{...(re=(F=s==null?void 0:s.launcher)==null?void 0:F.dock)!=null?re:{},...(ae=(Y=x==null?void 0:x.launcher)==null?void 0:Y.dock)!=null?ae:{}}}},q=Ut(s),M=Ut(k);if(q!==M){m(k);return}s=k,o.updateConfig(s),a.update(x),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(C,{get(x,k,q){if(k==="host")return o.host;if(k in x)return Reflect.get(x,k,q);let M=a[k];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Pc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Cp=new Set(["button","a","input","select","textarea","details","summary"]),wp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Xs=/\b(product|card|item|listing|result)\b/i,Qs=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Sp=3e3,Ap=100;function Ic(e){let n=typeof e.className=="string"?e.className:"";if(Xs.test(n)||e.id&&Xs.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Xs.test(r.value))return!0}return!1}function Wc(e){var n;return Qs.test(((n=e.textContent)!=null?n:"").trim())}function Rc(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Ep(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Tc(e){let n=e.match(Qs);return n?n[0]:null}function Mc(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Tp(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var Mp="commerce-card",kp="result-card";function kc(e){return!Ic(e)||!Wc(e)||!Rc(e)&&!Ep(e)?0:5200}function Lc(e){var r;return!Ic(e)||Wc(e)||!Rc(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var ea=[{id:Mp,scoreElement(e){return kc(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||Qs.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,c,g;if(kc(e)===0)return null;let{title:t,href:r}=Mc(e),s=(g=(c=Tc(((d=e.textContent)!=null?d:"").trim()))!=null?c:Tc(n.text))!=null?g:"",o=Tp(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
96
|
+
`)}},{id:kp,scoreElement(e){return Lc(e)},formatSummary(e,n){if(Lc(e)===0)return null;let{title:t,href:r}=Mc(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
|
|
97
|
+
`)}}];function Lp(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Pp(e){var g,p,f,m,C,v,E,x,k,q,M,N,w;let n=(g=e.options)!=null?g:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(C=(m=n.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",s=(E=(v=n.maxTextLength)!=null?v:e.maxTextLength)!=null?E:200,o=(k=(x=n.visibleOnly)!=null?x:e.visibleOnly)!=null?k:!0,a=(q=n.root)!=null?q:e.root,i=(M=n.mode)!=null?M:"structured",d=(N=n.maxCandidates)!=null?N:Math.max(500,t*10),c=(w=e.rules)!=null?w:ea;return i==="simple"&&e.rules&&e.rules.length>0?(Lp(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function Zs(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Ip=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Wp(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||Cp.has(n)||t&&wp.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Hc(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Rp(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let c=0;c<e.attributes.length;c++){let g=e.attributes[c];g.name.startsWith("data-")&&(n[g.name]=g.value)}return n}function ta(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${Zs(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Ip){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${Zs(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>Zs(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function Hp(e){return e==="static"?Ap:Sp}function Bc(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:ta(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:Wp(e),attributes:Rp(e)}}function Bp(e,n,t,r){let s=Hp(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Fp(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function $p(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,g=c.tagName.toLowerCase();if(Pc.has(g)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Hc(c)){i=a.nextNode();continue}let p=Bc(c,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(E=>E==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:C,formattingRule:v}=Bp(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:C,formattingRule:v}),o+=1}i=a.nextNode()}s.sort((c,g)=>{let p=c.enriched.interactivity==="static"?1:0,f=g.enriched.interactivity==="static"?1:0;return p!==f?p-f:g.score!==c.score?g.score-c.score:c.domIndex-g.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;Fp(d,c)||d.push(c)}return d.sort((c,g)=>{let p=c.enriched.interactivity==="static"?1:0,f=g.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&g.score!==c.score?g.score-c.score:c.domIndex-g.domIndex}),d.map(c=>{var f;let g;if((f=c.formattingRule)!=null&&f.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(g=m)}let p={...c.enriched};return g&&(p.formattedSummary=g),p})}function Np(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,c=d.tagName.toLowerCase();if(Pc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Hc(d)){o=s.nextNode();continue}let g=Bc(d,e.maxTextLength),p=g.text.length>0,f=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}r.has(g.selector)||(r.add(g.selector),t.push(g))}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 Fc(e={}){var r;let n=Pp(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?Np(n,t):$p(n,t):[]}var cs=100;function $c(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
|
|
98
98
|
${a.map(i=>`- ${i.split(`
|
|
99
99
|
`).join(`
|
|
100
100
|
`)}`).join(`
|
|
101
|
-
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
101
|
+
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,cs)}" (clickable)`);r.push(`Interactive elements:
|
|
102
102
|
${a.join(`
|
|
103
|
-
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,
|
|
103
|
+
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,cs)}" (navigable)`);r.push(`Navigation links:
|
|
104
104
|
${a.join(`
|
|
105
|
-
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,
|
|
105
|
+
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,cs)}" (input)`);r.push(`Form inputs:
|
|
106
106
|
${a.join(`
|
|
107
|
-
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
107
|
+
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,cs)}"`);r.push(`Content:
|
|
108
108
|
${a.join(`
|
|
109
109
|
`)}`)}return r.join(`
|
|
110
110
|
|
|
111
|
-
`)}var
|
|
111
|
+
`)}var Nc={name:"@runtypelabs/persona",version:"2.3.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"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","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",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.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 ir=Nc.version;function Wn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function Dp(e){if(e)return{getHeaders:Wn(e.getHeaders),onFeedback:Wn(e.onFeedback),onCopy:Wn(e.onCopy),requestMiddleware:Wn(e.requestMiddleware),actionHandlers:Wn(e.actionHandlers),actionParsers:Wn(e.actionParsers),postprocessMessage:Wn(e.postprocessMessage),contextProviders:Wn(e.contextProviders),streamParser:Wn(e.streamParser)}}var Oc=`({ text, message }: any) => {
|
|
112
112
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
113
113
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
114
114
|
let cleanJson = jsonSource
|
|
@@ -121,7 +121,7 @@ ${a.join(`
|
|
|
121
121
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
122
122
|
} catch (e) { return null; }
|
|
123
123
|
return null;
|
|
124
|
-
}`,
|
|
124
|
+
}`,Dc=`function(ctx) {
|
|
125
125
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
126
126
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
127
127
|
var cleanJson = jsonSource
|
|
@@ -134,7 +134,7 @@ ${a.join(`
|
|
|
134
134
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
135
135
|
} catch (e) { return null; }
|
|
136
136
|
return null;
|
|
137
|
-
}
|
|
137
|
+
}`,_c=`(action: any, context: any) => {
|
|
138
138
|
if (action.type !== 'nav_then_click') return;
|
|
139
139
|
const payload = action.payload || action.raw || {};
|
|
140
140
|
const url = payload?.page;
|
|
@@ -151,7 +151,7 @@ ${a.join(`
|
|
|
151
151
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
152
152
|
window.location.href = targetUrl;
|
|
153
153
|
return { handled: true, displayText: text };
|
|
154
|
-
}`,
|
|
154
|
+
}`,jc=`function(action, context) {
|
|
155
155
|
if (action.type !== 'nav_then_click') return;
|
|
156
156
|
var payload = action.payload || action.raw || {};
|
|
157
157
|
var url = payload.page;
|
|
@@ -168,24 +168,24 @@ ${a.join(`
|
|
|
168
168
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
169
169
|
window.location.href = targetUrl;
|
|
170
170
|
return { handled: true, displayText: text };
|
|
171
|
-
}`,
|
|
171
|
+
}`,_p=`(parsed: any) => {
|
|
172
172
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
173
173
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
174
174
|
if (parsed.action === 'message') return parsed.text || '';
|
|
175
175
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
176
176
|
return parsed.text || null;
|
|
177
|
-
}`,
|
|
177
|
+
}`,jp=`function(parsed) {
|
|
178
178
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
179
179
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
180
180
|
if (parsed.action === 'message') return parsed.text || '';
|
|
181
181
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
182
182
|
return parsed.text || null;
|
|
183
|
-
}`;function
|
|
184
|
-
`)}function
|
|
185
|
-
`)}function Dp(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&(r.push(" theme: {"),Object.entries(e.theme).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.launcher&&ms(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...ds(e," ")),r.push(...ps(e," ",t)),r.push(...us(e," ")),r.push(...gs(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Bp}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Bc}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Bc}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${$c}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${$c}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
186
|
-
`)}function
|
|
187
|
-
`)}function
|
|
183
|
+
}`;function Vp(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function ds(e){var n,t;return(t=(n=e.parserType)!=null?n:Vp(e.streamParser))!=null?t:"plain"}function ps(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function us(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function gs(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function ms(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?t.push(`${n} ${d}: "${c}",`):typeof c=="boolean"&&t.push(`${n} ${d}: ${c},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function na(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function Vc(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),Vc(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function fs(e,n,t,r){t&&(e.push(`${r}${n}: {`),Vc(e,t,`${r} `),e.push(`${r}},`))}function Uc(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:Dp(t.hooks)}:void 0;return n==="esm"?Up(r,s):n==="script-installer"?Jp(r):n==="script-advanced"?Yp(r,s):n==="react-component"?qp(r,s):n==="react-advanced"?zp(r,s):Kp(r,s)}function Up(e,n){let t=n==null?void 0:n.hooks,r=ds(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&(o.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.launcher&&fs(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...ps(e," ")),o.push(...us(e," ",t)),o.push(...gs(e," ")),o.push(...ms(e," ")),o.push(...na(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
|
|
184
|
+
`)}function qp(e,n){let t=n==null?void 0:n.hooks,r=ds(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&(o.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.launcher&&fs(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...ps(e," ")),o.push(...us(e," ",t)),o.push(...gs(e," ")),o.push(...ms(e," ")),o.push(...na(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
|
|
185
|
+
`)}function zp(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&(r.push(" theme: {"),Object.entries(e.theme).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.launcher&&fs(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...ps(e," ")),r.push(...us(e," ",t)),r.push(...gs(e," ")),r.push(...ms(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${_p}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Oc}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Oc}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${_c}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${_c}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
186
|
+
`)}function qc(e){var s;let n=ds(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([g,p])=>{g!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[g]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function Jp(e){let n=qc(e),t=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ir}/dist/install.global.js" data-config='${t}'></script>`}function Kp(e,n){let t=n==null?void 0:n.hooks,r=ds(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ir}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ir}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&(o.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.launcher&&fs(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...ps(e," ")),o.push(...us(e," ",t)),o.push(...gs(e," ")),o.push(...ms(e," ")),o.push(...na(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
|
|
187
|
+
`)}function Yp(e,n){let t=n==null?void 0:n.hooks,r=qc(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
188
188
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
189
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ir}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${
|
|
190
|
-
`)}function
|
|
189
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ir}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${jp});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Dc}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Dc}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${jc}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${jc}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
|
|
190
|
+
`)}function zc(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #1d4ed8)"}}}function Jc(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Kc(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:Cn(e.colors.primary,.95),100:Cn(e.colors.primary,.9),200:Cn(e.colors.primary,.8),300:Cn(e.colors.primary,.7),400:Cn(e.colors.primary,.6),500:e.colors.primary,600:Cn(e.colors.primary,.8),700:Cn(e.colors.primary,.7),800:Cn(e.colors.primary,.6),900:Cn(e.colors.primary,.5),950:Cn(e.colors.primary,.45)}}),{...n,palette:t}}}}function Yc(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Gc(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Cn(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Xc(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var ra={id:"shop",label:"Shopping Assistant",config:{theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:"min(400px, calc(100vw - 24px))"},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},oa={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:{panelBorderRadius:"0",panelShadow:"none"}}},sa={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:{panelBorderRadius:"0",panelShadow:"none"}}},aa={shop:ra,minimal:oa,fullscreen:sa};function Zc(e){return aa[e]}var Gp=Gs;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,THEME_ZONES,VERSION,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createStandardBubble,createTextPart,createTheme,createThemeObserver,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultParseRules,detectColorScheme,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,migrateV1Theme,normalizeContent,pluginRegistry,reducedMotionPlugin,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,validateImageFile,validateTheme,validateV1Theme});
|
|
191
191
|
//# sourceMappingURL=index.cjs.map
|